blob: 52695fe39c710e7fb16f473d0bbf92aac729fad0 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Steve Dower68d663c2017-07-17 11:15:48 +020023/* Redefined below for Windows debug builds after important #includes */
24#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020025
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020026#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
28#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020029 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000031 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020032 PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
34#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
35#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010037/* Include symbols from _socket module */
38#include "socketmodule.h"
39
40static PySocketModule_APIObject PySocketModule;
41
42#if defined(HAVE_POLL_H)
43#include <poll.h>
44#elif defined(HAVE_SYS_POLL_H)
45#include <sys/poll.h>
46#endif
47
Christian Heimes598894f2016-09-05 23:19:05 +020048/* Don't warn about deprecated functions */
49#ifdef __GNUC__
50#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
51#endif
52#ifdef __clang__
53#pragma clang diagnostic ignored "-Wdeprecated-declarations"
54#endif
55
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010056/* Include OpenSSL header files */
57#include "openssl/rsa.h"
58#include "openssl/crypto.h"
59#include "openssl/x509.h"
60#include "openssl/x509v3.h"
61#include "openssl/pem.h"
62#include "openssl/ssl.h"
63#include "openssl/err.h"
64#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020065#include "openssl/bio.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010066
Christian Heimesff5be6e2018-01-20 13:19:21 +010067#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010068# ifdef LIBRESSL_VERSION_NUMBER
69# error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
70# elif OPENSSL_VERSION_NUMBER > 0x1000200fL
Christian Heimesff5be6e2018-01-20 13:19:21 +010071# define HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010072# else
73# error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
Christian Heimesff5be6e2018-01-20 13:19:21 +010074# endif
75#endif
76
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010077/* SSL error object */
78static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070079static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010080static PyObject *PySSLZeroReturnErrorObject;
81static PyObject *PySSLWantReadErrorObject;
82static PyObject *PySSLWantWriteErrorObject;
83static PyObject *PySSLSyscallErrorObject;
84static PyObject *PySSLEOFErrorObject;
85
86/* Error mappings */
87static PyObject *err_codes_to_names;
88static PyObject *err_names_to_codes;
89static PyObject *lib_codes_to_names;
90
91struct py_ssl_error_code {
92 const char *mnemonic;
93 int library, reason;
94};
95struct py_ssl_library_code {
96 const char *library;
97 int code;
98};
99
Steve Dower68d663c2017-07-17 11:15:48 +0200100#if defined(MS_WINDOWS) && defined(Py_DEBUG)
101/* Debug builds on Windows rely on getting errno directly from OpenSSL.
102 * However, because it uses a different CRT, we need to transfer the
103 * value of errno from OpenSSL into our debug CRT.
104 *
105 * Don't be fooled - this is horribly ugly code. The only reasonable
106 * alternative is to do both debug and release builds of OpenSSL, which
107 * requires much uglier code to transform their automatically generated
108 * makefile. This is the lesser of all the evils.
109 */
110
111static void _PySSLFixErrno(void) {
112 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
113 if (!ucrtbase) {
114 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
115 * have a catastrophic failure, but this function is not the
116 * place to raise it. */
117 return;
118 }
119
120 typedef int *(__stdcall *errno_func)(void);
121 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
122 if (ssl_errno) {
123 errno = *ssl_errno();
124 *ssl_errno() = 0;
125 } else {
126 errno = ENOTRECOVERABLE;
127 }
128}
129
130#undef _PySSL_FIX_ERRNO
131#define _PySSL_FIX_ERRNO _PySSLFixErrno()
132#endif
133
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100134/* Include generated data (error codes) */
135#include "_ssl_data.h"
136
Christian Heimes598894f2016-09-05 23:19:05 +0200137#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
138# define OPENSSL_VERSION_1_1 1
139#endif
140
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100141/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
142 http://www.openssl.org/news/changelog.html
143 */
144#if OPENSSL_VERSION_NUMBER >= 0x10001000L
145# define HAVE_TLSv1_2 1
146#else
147# define HAVE_TLSv1_2 0
148#endif
149
Christian Heimes470fba12013-11-28 15:12:15 +0100150/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100151 * This includes the SSL_set_SSL_CTX() function.
152 */
153#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
154# define HAVE_SNI 1
155#else
156# define HAVE_SNI 0
157#endif
158
Benjamin Petersond3308222015-09-27 00:09:02 -0700159#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100160# define HAVE_ALPN 1
161#else
162# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500163#endif
164
Christian Heimes6cdb7952018-02-24 22:12:40 +0100165/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
166 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
167 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
168 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100169 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100170 */
171#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100172# define HAVE_NPN 0
173#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
174# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100175#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100176# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100177#else
Christian Heimes29eab552018-02-25 12:31:33 +0100178# define HAVE_NPN 0
179#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100180
Victor Stinner524714e2016-07-22 17:43:59 +0200181#ifndef INVALID_SOCKET /* MS defines this */
182#define INVALID_SOCKET (-1)
183#endif
184
Christian Heimes598894f2016-09-05 23:19:05 +0200185#ifdef OPENSSL_VERSION_1_1
186/* OpenSSL 1.1.0+ */
187#ifndef OPENSSL_NO_SSL2
188#define OPENSSL_NO_SSL2
189#endif
190#else /* OpenSSL < 1.1.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200191#define HAVE_OPENSSL_CRYPTO_LOCK
Christian Heimes598894f2016-09-05 23:19:05 +0200192
193#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200194#define TLS_client_method SSLv23_client_method
195#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200196
197static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
198{
199 return ne->set;
200}
201
202#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200203/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200204static int COMP_get_type(const COMP_METHOD *meth)
205{
206 return meth->type;
207}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200208/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200209#endif
210
211static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
212{
213 return ctx->default_passwd_callback;
214}
215
216static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
217{
218 return ctx->default_passwd_callback_userdata;
219}
220
221static int X509_OBJECT_get_type(X509_OBJECT *x)
222{
223 return x->type;
224}
225
226static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
227{
228 return x->data.x509;
229}
230
231static int BIO_up_ref(BIO *b)
232{
233 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
234 return 1;
235}
236
237static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
238 return store->objs;
239}
240
Christian Heimes99a65702016-09-10 23:44:53 +0200241static int
242SSL_SESSION_has_ticket(const SSL_SESSION *s)
243{
244 return (s->tlsext_ticklen > 0) ? 1 : 0;
245}
246
247static unsigned long
248SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
249{
250 return s->tlsext_tick_lifetime_hint;
251}
252
Christian Heimes598894f2016-09-05 23:19:05 +0200253#endif /* OpenSSL < 1.1.0 or LibreSSL */
254
Christian Heimes892d66e2018-01-29 14:10:18 +0100255/* Default cipher suites */
256#ifndef PY_SSL_DEFAULT_CIPHERS
257#define PY_SSL_DEFAULT_CIPHERS 1
258#endif
259
260#if PY_SSL_DEFAULT_CIPHERS == 0
261 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
262 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
263 #endif
264#elif PY_SSL_DEFAULT_CIPHERS == 1
265/* Python custom selection of sensible ciper suites
266 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
267 * !aNULL:!eNULL: really no NULL ciphers
268 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
269 * !aDSS: no authentication with discrete logarithm DSA algorithm
270 * !SRP:!PSK: no secure remote password or pre-shared key authentication
271 */
272 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
273#elif PY_SSL_DEFAULT_CIPHERS == 2
274/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
275 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
276#else
277 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
278#endif
279
Christian Heimes598894f2016-09-05 23:19:05 +0200280
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000281enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000282 /* these mirror ssl.h */
283 PY_SSL_ERROR_NONE,
284 PY_SSL_ERROR_SSL,
285 PY_SSL_ERROR_WANT_READ,
286 PY_SSL_ERROR_WANT_WRITE,
287 PY_SSL_ERROR_WANT_X509_LOOKUP,
288 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
289 PY_SSL_ERROR_ZERO_RETURN,
290 PY_SSL_ERROR_WANT_CONNECT,
291 /* start of non ssl.h errorcodes */
292 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
293 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
294 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000295};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000296
Thomas Woutersed03b412007-08-28 21:37:11 +0000297enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000298 PY_SSL_CLIENT,
299 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000300};
301
302enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000303 PY_SSL_CERT_NONE,
304 PY_SSL_CERT_OPTIONAL,
305 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000306};
307
308enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000309 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200310 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200311 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100312#if HAVE_TLSv1_2
313 PY_SSL_VERSION_TLS1,
314 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200315 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100316#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200317 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000318#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200319 PY_SSL_VERSION_TLS_CLIENT=0x10,
320 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100321};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200322
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000323/* serves as a flag to see whether we've initialized the SSL thread support. */
324/* 0 means no, greater than 0 means yes */
325
326static unsigned int _ssl_locks_count = 0;
327
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000328/* SSL socket object */
329
330#define X509_NAME_MAXLEN 256
331
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000332/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
333 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
334 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
335#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000336# define HAVE_SSL_CTX_CLEAR_OPTIONS
337#else
338# undef HAVE_SSL_CTX_CLEAR_OPTIONS
339#endif
340
Antoine Pitroud6494802011-07-21 01:11:30 +0200341/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
342 * older SSL, but let's be safe */
343#define PySSL_CB_MAXLEN 128
344
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100345
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000346typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000347 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000348 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100349#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500350 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100351 int npn_protocols_len;
352#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100353#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500354 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300355 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500356#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100357#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100358 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100359#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100360 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100361 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
362 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
363 */
364 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100365 int protocol;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000366} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000367
Antoine Pitrou152efa22010-05-16 18:19:27 +0000368typedef struct {
369 PyObject_HEAD
370 PyObject *Socket; /* weakref to socket on which we're layered */
371 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100372 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200373 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200374 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200375 PyObject *owner; /* Python level "owner" passed to servername callback */
376 PyObject *server_hostname;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700377 int ssl_errno; /* last seen error from SSL */
378 int c_errno; /* last seen error from libc */
379#ifdef MS_WINDOWS
380 int ws_errno; /* last seen error from winsock */
381#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000382} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000383
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200384typedef struct {
385 PyObject_HEAD
386 BIO *bio;
387 int eof_written;
388} PySSLMemoryBIO;
389
Christian Heimes99a65702016-09-10 23:44:53 +0200390typedef struct {
391 PyObject_HEAD
392 SSL_SESSION *session;
393 PySSLContext *ctx;
394} PySSLSession;
395
Antoine Pitrou152efa22010-05-16 18:19:27 +0000396static PyTypeObject PySSLContext_Type;
397static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200398static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200399static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000400
Steve Dowere6eb48c2017-09-08 15:16:15 -0700401#ifdef MS_WINDOWS
402#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
403 (sock)->ws_errno = WSAGetLastError(); \
404 _PySSL_FIX_ERRNO; \
405 (sock)->c_errno = errno; \
406 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
407 } else { sock->ws_errno = 0; sock->c_errno = 0; sock->ssl_errno = 0; }
408#else
409#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
410 (sock)->c_errno = errno; \
411 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
412 } else { (sock)->c_errno = 0; (sock)->ssl_errno = 0; }
413#endif
414#define _PySSL_UPDATE_ERRNO(sock, retcode) _PySSL_UPDATE_ERRNO_IF(1, (sock), (retcode))
415
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300416/*[clinic input]
417module _ssl
418class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
419class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
420class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200421class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300422[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200423/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300424
425#include "clinic/_ssl.c.h"
426
Victor Stinner14690702015-04-06 22:46:13 +0200427static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000428
Christian Heimes141c5e82018-02-24 21:10:57 +0100429static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
430static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000431#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200432#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200433#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000434
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000435typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000436 SOCKET_IS_NONBLOCKING,
437 SOCKET_IS_BLOCKING,
438 SOCKET_HAS_TIMED_OUT,
439 SOCKET_HAS_BEEN_CLOSED,
440 SOCKET_TOO_LARGE_FOR_SELECT,
441 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000442} timeout_state;
443
Thomas Woutersed03b412007-08-28 21:37:11 +0000444/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000445#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200446#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000447
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200448/* Get the socket from a PySSLSocket, if it has one */
449#define GET_SOCKET(obj) ((obj)->Socket ? \
450 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200451
Victor Stinner14690702015-04-06 22:46:13 +0200452/* If sock is NULL, use a timeout of 0 second */
453#define GET_SOCKET_TIMEOUT(sock) \
454 ((sock != NULL) ? (sock)->sock_timeout : 0)
455
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200456/*
457 * SSL errors.
458 */
459
460PyDoc_STRVAR(SSLError_doc,
461"An error occurred in the SSL implementation.");
462
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700463PyDoc_STRVAR(SSLCertVerificationError_doc,
464"A certificate could not be verified.");
465
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200466PyDoc_STRVAR(SSLZeroReturnError_doc,
467"SSL/TLS session closed cleanly.");
468
469PyDoc_STRVAR(SSLWantReadError_doc,
470"Non-blocking SSL socket needs to read more data\n"
471"before the requested operation can be completed.");
472
473PyDoc_STRVAR(SSLWantWriteError_doc,
474"Non-blocking SSL socket needs to write more data\n"
475"before the requested operation can be completed.");
476
477PyDoc_STRVAR(SSLSyscallError_doc,
478"System error when attempting SSL operation.");
479
480PyDoc_STRVAR(SSLEOFError_doc,
481"SSL/TLS connection terminated abruptly.");
482
483static PyObject *
484SSLError_str(PyOSErrorObject *self)
485{
486 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
487 Py_INCREF(self->strerror);
488 return self->strerror;
489 }
490 else
491 return PyObject_Str(self->args);
492}
493
494static PyType_Slot sslerror_type_slots[] = {
495 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
496 {Py_tp_doc, SSLError_doc},
497 {Py_tp_str, SSLError_str},
498 {0, 0},
499};
500
501static PyType_Spec sslerror_type_spec = {
502 "ssl.SSLError",
503 sizeof(PyOSErrorObject),
504 0,
505 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
506 sslerror_type_slots
507};
508
509static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700510fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
511 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200512{
513 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700514 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200515 PyObject *init_value, *msg, *key;
516 _Py_IDENTIFIER(reason);
517 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700518 _Py_IDENTIFIER(verify_message);
519 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200520
521 if (errcode != 0) {
522 int lib, reason;
523
524 lib = ERR_GET_LIB(errcode);
525 reason = ERR_GET_REASON(errcode);
526 key = Py_BuildValue("ii", lib, reason);
527 if (key == NULL)
528 goto fail;
529 reason_obj = PyDict_GetItem(err_codes_to_names, key);
530 Py_DECREF(key);
531 if (reason_obj == NULL) {
532 /* XXX if reason < 100, it might reflect a library number (!!) */
533 PyErr_Clear();
534 }
535 key = PyLong_FromLong(lib);
536 if (key == NULL)
537 goto fail;
538 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
539 Py_DECREF(key);
540 if (lib_obj == NULL) {
541 PyErr_Clear();
542 }
543 if (errstr == NULL)
544 errstr = ERR_reason_error_string(errcode);
545 }
546 if (errstr == NULL)
547 errstr = "unknown error";
548
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700549 /* verify code for cert validation error */
550 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
551 const char *verify_str = NULL;
552 long verify_code;
553
554 verify_code = SSL_get_verify_result(sslsock->ssl);
555 verify_code_obj = PyLong_FromLong(verify_code);
556 if (verify_code_obj == NULL) {
557 goto fail;
558 }
559
560 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700561#ifdef X509_V_ERR_HOSTNAME_MISMATCH
562 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700563 case X509_V_ERR_HOSTNAME_MISMATCH:
564 verify_obj = PyUnicode_FromFormat(
565 "Hostname mismatch, certificate is not valid for '%S'.",
566 sslsock->server_hostname
567 );
568 break;
Christian Heimes09153602017-09-08 14:47:58 -0700569#endif
570#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700571 case X509_V_ERR_IP_ADDRESS_MISMATCH:
572 verify_obj = PyUnicode_FromFormat(
573 "IP address mismatch, certificate is not valid for '%S'.",
574 sslsock->server_hostname
575 );
576 break;
Christian Heimes09153602017-09-08 14:47:58 -0700577#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700578 default:
579 verify_str = X509_verify_cert_error_string(verify_code);
580 if (verify_str != NULL) {
581 verify_obj = PyUnicode_FromString(verify_str);
582 } else {
583 verify_obj = Py_None;
584 Py_INCREF(verify_obj);
585 }
586 break;
587 }
588 if (verify_obj == NULL) {
589 goto fail;
590 }
591 }
592
593 if (verify_obj && reason_obj && lib_obj)
594 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
595 lib_obj, reason_obj, errstr, verify_obj,
596 lineno);
597 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200598 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
599 lib_obj, reason_obj, errstr, lineno);
600 else if (lib_obj)
601 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
602 lib_obj, errstr, lineno);
603 else
604 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200605 if (msg == NULL)
606 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100607
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200608 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100609 if (init_value == NULL)
610 goto fail;
611
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200612 err_value = PyObject_CallObject(type, init_value);
613 Py_DECREF(init_value);
614 if (err_value == NULL)
615 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100616
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200617 if (reason_obj == NULL)
618 reason_obj = Py_None;
619 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
620 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700621
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200622 if (lib_obj == NULL)
623 lib_obj = Py_None;
624 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
625 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700626
627 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
628 /* Only set verify code / message for SSLCertVerificationError */
629 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
630 verify_code_obj))
631 goto fail;
632 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
633 goto fail;
634 }
635
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200636 PyErr_SetObject(type, err_value);
637fail:
638 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700639 Py_XDECREF(verify_code_obj);
640 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200641}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000642
643static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700644PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000645{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200646 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200647 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000648 int err;
649 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200650 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000651
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000652 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200653 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000654
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700655 if (sslsock->ssl != NULL) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700656 err = sslsock->ssl_errno;
Thomas Woutersed03b412007-08-28 21:37:11 +0000657
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000658 switch (err) {
659 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200660 errstr = "TLS/SSL connection has been closed (EOF)";
661 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000662 p = PY_SSL_ERROR_ZERO_RETURN;
663 break;
664 case SSL_ERROR_WANT_READ:
665 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200666 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000667 p = PY_SSL_ERROR_WANT_READ;
668 break;
669 case SSL_ERROR_WANT_WRITE:
670 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200671 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000672 errstr = "The operation did not complete (write)";
673 break;
674 case SSL_ERROR_WANT_X509_LOOKUP:
675 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000676 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000677 break;
678 case SSL_ERROR_WANT_CONNECT:
679 p = PY_SSL_ERROR_WANT_CONNECT;
680 errstr = "The operation did not complete (connect)";
681 break;
682 case SSL_ERROR_SYSCALL:
683 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000684 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700685 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000686 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000687 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200688 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000689 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200690 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000691 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000692 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700693#ifdef MS_WINDOWS
694 if (sslsock->ws_errno)
695 return PyErr_SetFromWindowsErr(sslsock->ws_errno);
696#endif
697 if (sslsock->c_errno) {
698 errno = sslsock->c_errno;
699 return PyErr_SetFromErrno(PyExc_OSError);
700 }
701 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200702 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000703 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200704 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000705 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000706 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200707 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000708 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000709 }
710 } else {
711 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000712 }
713 break;
714 }
715 case SSL_ERROR_SSL:
716 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000717 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700718 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200719 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000720 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700721 }
722 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
723 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
724 type = PySSLCertVerificationErrorObject;
725 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000726 break;
727 }
728 default:
729 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
730 errstr = "Invalid error code";
731 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000732 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700733 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000734 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000736}
737
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000738static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200739_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000740
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200741 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000742 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200743 else
744 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700745 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000746 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000747 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000748}
749
Christian Heimes61d478c2018-01-27 15:51:38 +0100750/*
751 * SSL objects
752 */
753
754static int
755_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
756{
757 int retval = -1;
758 ASN1_OCTET_STRING *ip;
759 PyObject *hostname;
760 size_t len;
761
762 assert(server_hostname);
763
764 /* Disable OpenSSL's special mode with leading dot in hostname:
765 * When name starts with a dot (e.g ".example.com"), it will be
766 * matched by a certificate valid for any sub-domain of name.
767 */
768 len = strlen(server_hostname);
769 if (len == 0 || *server_hostname == '.') {
770 PyErr_SetString(
771 PyExc_ValueError,
772 "server_hostname cannot be an empty string or start with a "
773 "leading dot.");
774 return retval;
775 }
776
777 /* inet_pton is not available on all platforms. */
778 ip = a2i_IPADDRESS(server_hostname);
779 if (ip == NULL) {
780 ERR_clear_error();
781 }
782
Christian Heimes11a14932018-02-24 02:35:08 +0100783 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100784 if (hostname == NULL) {
785 goto error;
786 }
787 self->server_hostname = hostname;
788
789 /* Only send SNI extension for non-IP hostnames */
790 if (ip == NULL) {
791 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
792 _setSSLError(NULL, 0, __FILE__, __LINE__);
793 }
794 }
795 if (self->ctx->check_hostname) {
796 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
797 if (ip == NULL) {
798 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname, 0)) {
799 _setSSLError(NULL, 0, __FILE__, __LINE__);
800 goto error;
801 }
802 } else {
803 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
804 ASN1_STRING_length(ip))) {
805 _setSSLError(NULL, 0, __FILE__, __LINE__);
806 goto error;
807 }
808 }
809 }
810 retval = 0;
811 error:
812 if (ip != NULL) {
813 ASN1_OCTET_STRING_free(ip);
814 }
815 return retval;
816}
817
Antoine Pitrou152efa22010-05-16 18:19:27 +0000818static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100819newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000820 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200821 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100822 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200823 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000824{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000825 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100826 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200827 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000828
Antoine Pitrou152efa22010-05-16 18:19:27 +0000829 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 if (self == NULL)
831 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000832
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100835 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700836 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200837 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200838 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700839 self->server_hostname = NULL;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700840 self->ssl_errno = 0;
841 self->c_errno = 0;
842#ifdef MS_WINDOWS
843 self->ws_errno = 0;
844#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200845
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000846 /* Make sure the SSL error state is initialized */
847 (void) ERR_get_state();
848 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000849
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000850 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000851 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000852 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200853 SSL_set_app_data(self->ssl, self);
854 if (sock) {
855 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
856 } else {
857 /* BIOs are reference counted and SSL_set_bio borrows our reference.
858 * To prevent a double free in memory_bio_dealloc() we need to take an
859 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200860 BIO_up_ref(inbio->bio);
861 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200862 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
863 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200864 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000865#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200866 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000867#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200868 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000869
Christian Heimes61d478c2018-01-27 15:51:38 +0100870 if (server_hostname != NULL) {
871 if (_ssl_configure_hostname(self, server_hostname) < 0) {
872 Py_DECREF(self);
873 return NULL;
874 }
875 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000876 /* If the socket is in non-blocking mode or timeout mode, set the BIO
877 * to non-blocking mode (blocking is the default)
878 */
Victor Stinnere2452312015-03-28 03:00:46 +0100879 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000880 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
881 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
882 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000883
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000884 PySSL_BEGIN_ALLOW_THREADS
885 if (socket_type == PY_SSL_CLIENT)
886 SSL_set_connect_state(self->ssl);
887 else
888 SSL_set_accept_state(self->ssl);
889 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000890
Antoine Pitroud6494802011-07-21 01:11:30 +0200891 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200892 if (sock != NULL) {
893 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
894 if (self->Socket == NULL) {
895 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200896 return NULL;
897 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100898 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100899 if (owner && owner != Py_None) {
900 if (PySSL_set_owner(self, owner, NULL) == -1) {
901 Py_DECREF(self);
902 return NULL;
903 }
904 }
905 if (session && session != Py_None) {
906 if (PySSL_set_session(self, session, NULL) == -1) {
907 Py_DECREF(self);
908 return NULL;
909 }
910 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000911 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000912}
913
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000914/* SSL object methods */
915
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300916/*[clinic input]
917_ssl._SSLSocket.do_handshake
918[clinic start generated code]*/
919
920static PyObject *
921_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
922/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000923{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000924 int ret;
925 int err;
926 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200927 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200928 _PyTime_t timeout, deadline = 0;
929 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000930
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200931 if (sock) {
932 if (((PyObject*)sock) == Py_None) {
933 _setSSLError("Underlying socket connection gone",
934 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
935 return NULL;
936 }
937 Py_INCREF(sock);
938
939 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100940 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200941 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
942 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000944
Victor Stinner14690702015-04-06 22:46:13 +0200945 timeout = GET_SOCKET_TIMEOUT(sock);
946 has_timeout = (timeout > 0);
947 if (has_timeout)
948 deadline = _PyTime_GetMonotonicClock() + timeout;
949
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000950 /* Actually negotiate SSL connection */
951 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000952 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000953 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000954 ret = SSL_do_handshake(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -0700955 _PySSL_UPDATE_ERRNO_IF(ret < 1, self, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000956 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -0700957 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200958
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000959 if (PyErr_CheckSignals())
960 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200961
Victor Stinner14690702015-04-06 22:46:13 +0200962 if (has_timeout)
963 timeout = deadline - _PyTime_GetMonotonicClock();
964
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000965 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200966 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000967 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200968 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000969 } else {
970 sockstate = SOCKET_OPERATION_OK;
971 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200972
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000973 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000974 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000975 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000976 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000977 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
978 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000979 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000980 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000981 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
982 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000983 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000984 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000985 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
986 break;
987 }
988 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200989 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000990 if (ret < 1)
991 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000992
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200993 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000994
995error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200996 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000997 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000998}
999
Thomas Woutersed03b412007-08-28 21:37:11 +00001000static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001001_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1002{
1003 char buf[X509_NAME_MAXLEN];
1004 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001005 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001006 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001007
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001008 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001009 if (buflen < 0) {
1010 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001011 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001012 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001013 /* initial buffer is too small for oid + terminating null byte */
1014 if (buflen > X509_NAME_MAXLEN - 1) {
1015 /* make OBJ_obj2txt() calculate the required buflen */
1016 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1017 /* allocate len + 1 for terminating NULL byte */
1018 namebuf = PyMem_Malloc(buflen + 1);
1019 if (namebuf == NULL) {
1020 PyErr_NoMemory();
1021 return NULL;
1022 }
1023 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1024 if (buflen < 0) {
1025 _setSSLError(NULL, 0, __FILE__, __LINE__);
1026 goto done;
1027 }
1028 }
1029 if (!buflen && no_name) {
1030 Py_INCREF(Py_None);
1031 name_obj = Py_None;
1032 }
1033 else {
1034 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1035 }
1036
1037 done:
1038 if (buf != namebuf) {
1039 PyMem_Free(namebuf);
1040 }
1041 return name_obj;
1042}
1043
1044static PyObject *
1045_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1046{
1047 Py_ssize_t buflen;
1048 unsigned char *valuebuf = NULL;
1049 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001050
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001051 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1052 if (buflen < 0) {
1053 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001054 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001055 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001056 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001058 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001059}
1060
1061static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001062_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001063{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001064 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1065 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1066 PyObject *rdnt;
1067 PyObject *attr = NULL; /* tuple to hold an attribute */
1068 int entry_count = X509_NAME_entry_count(xname);
1069 X509_NAME_ENTRY *entry;
1070 ASN1_OBJECT *name;
1071 ASN1_STRING *value;
1072 int index_counter;
1073 int rdn_level = -1;
1074 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001076 dn = PyList_New(0);
1077 if (dn == NULL)
1078 return NULL;
1079 /* now create another tuple to hold the top-level RDN */
1080 rdn = PyList_New(0);
1081 if (rdn == NULL)
1082 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001083
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001084 for (index_counter = 0;
1085 index_counter < entry_count;
1086 index_counter++)
1087 {
1088 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001089
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001090 /* check to see if we've gotten to a new RDN */
1091 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001092 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001093 /* yes, new RDN */
1094 /* add old RDN to DN */
1095 rdnt = PyList_AsTuple(rdn);
1096 Py_DECREF(rdn);
1097 if (rdnt == NULL)
1098 goto fail0;
1099 retcode = PyList_Append(dn, rdnt);
1100 Py_DECREF(rdnt);
1101 if (retcode < 0)
1102 goto fail0;
1103 /* create new RDN */
1104 rdn = PyList_New(0);
1105 if (rdn == NULL)
1106 goto fail0;
1107 }
1108 }
Christian Heimes598894f2016-09-05 23:19:05 +02001109 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001110
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 /* now add this attribute to the current RDN */
1112 name = X509_NAME_ENTRY_get_object(entry);
1113 value = X509_NAME_ENTRY_get_data(entry);
1114 attr = _create_tuple_for_attribute(name, value);
1115 /*
1116 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1117 entry->set,
1118 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1119 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1120 */
1121 if (attr == NULL)
1122 goto fail1;
1123 retcode = PyList_Append(rdn, attr);
1124 Py_DECREF(attr);
1125 if (retcode < 0)
1126 goto fail1;
1127 }
1128 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001129 if (rdn != NULL) {
1130 if (PyList_GET_SIZE(rdn) > 0) {
1131 rdnt = PyList_AsTuple(rdn);
1132 Py_DECREF(rdn);
1133 if (rdnt == NULL)
1134 goto fail0;
1135 retcode = PyList_Append(dn, rdnt);
1136 Py_DECREF(rdnt);
1137 if (retcode < 0)
1138 goto fail0;
1139 }
1140 else {
1141 Py_DECREF(rdn);
1142 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001143 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001144
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 /* convert list to tuple */
1146 rdnt = PyList_AsTuple(dn);
1147 Py_DECREF(dn);
1148 if (rdnt == NULL)
1149 return NULL;
1150 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001151
1152 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001153 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001154
1155 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001156 Py_XDECREF(dn);
1157 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001158}
1159
1160static PyObject *
1161_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001162
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001163 /* this code follows the procedure outlined in
1164 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1165 function to extract the STACK_OF(GENERAL_NAME),
1166 then iterates through the stack to add the
1167 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001168
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001169 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001170 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001171 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001172 GENERAL_NAMES *names = NULL;
1173 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 BIO *biobuf = NULL;
1175 char buf[2048];
1176 char *vptr;
1177 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001178
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001179 if (certificate == NULL)
1180 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001181
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 /* get a memory buffer */
1183 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001184
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001185 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1186 certificate, NID_subject_alt_name, NULL, NULL);
1187 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001188 if (peer_alt_names == Py_None) {
1189 peer_alt_names = PyList_New(0);
1190 if (peer_alt_names == NULL)
1191 goto fail;
1192 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001193
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001194 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001195 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001196 int gntype;
1197 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001199 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001200 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001201 switch (gntype) {
1202 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001203 /* we special-case DirName as a tuple of
1204 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001205
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001206 t = PyTuple_New(2);
1207 if (t == NULL) {
1208 goto fail;
1209 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001210
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001211 v = PyUnicode_FromString("DirName");
1212 if (v == NULL) {
1213 Py_DECREF(t);
1214 goto fail;
1215 }
1216 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001217
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001218 v = _create_tuple_for_X509_NAME (name->d.dirn);
1219 if (v == NULL) {
1220 Py_DECREF(t);
1221 goto fail;
1222 }
1223 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001224 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001225
Christian Heimes824f7f32013-08-17 00:54:47 +02001226 case GEN_EMAIL:
1227 case GEN_DNS:
1228 case GEN_URI:
1229 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1230 correctly, CVE-2013-4238 */
1231 t = PyTuple_New(2);
1232 if (t == NULL)
1233 goto fail;
1234 switch (gntype) {
1235 case GEN_EMAIL:
1236 v = PyUnicode_FromString("email");
1237 as = name->d.rfc822Name;
1238 break;
1239 case GEN_DNS:
1240 v = PyUnicode_FromString("DNS");
1241 as = name->d.dNSName;
1242 break;
1243 case GEN_URI:
1244 v = PyUnicode_FromString("URI");
1245 as = name->d.uniformResourceIdentifier;
1246 break;
1247 }
1248 if (v == NULL) {
1249 Py_DECREF(t);
1250 goto fail;
1251 }
1252 PyTuple_SET_ITEM(t, 0, v);
1253 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1254 ASN1_STRING_length(as));
1255 if (v == NULL) {
1256 Py_DECREF(t);
1257 goto fail;
1258 }
1259 PyTuple_SET_ITEM(t, 1, v);
1260 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001261
Christian Heimes1c03abd2016-09-06 23:25:35 +02001262 case GEN_RID:
1263 t = PyTuple_New(2);
1264 if (t == NULL)
1265 goto fail;
1266
1267 v = PyUnicode_FromString("Registered ID");
1268 if (v == NULL) {
1269 Py_DECREF(t);
1270 goto fail;
1271 }
1272 PyTuple_SET_ITEM(t, 0, v);
1273
1274 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1275 if (len < 0) {
1276 Py_DECREF(t);
1277 _setSSLError(NULL, 0, __FILE__, __LINE__);
1278 goto fail;
1279 } else if (len >= (int)sizeof(buf)) {
1280 v = PyUnicode_FromString("<INVALID>");
1281 } else {
1282 v = PyUnicode_FromStringAndSize(buf, len);
1283 }
1284 if (v == NULL) {
1285 Py_DECREF(t);
1286 goto fail;
1287 }
1288 PyTuple_SET_ITEM(t, 1, v);
1289 break;
1290
Christian Heimes824f7f32013-08-17 00:54:47 +02001291 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001292 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001293 switch (gntype) {
1294 /* check for new general name type */
1295 case GEN_OTHERNAME:
1296 case GEN_X400:
1297 case GEN_EDIPARTY:
1298 case GEN_IPADD:
1299 case GEN_RID:
1300 break;
1301 default:
1302 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1303 "Unknown general name type %d",
1304 gntype) == -1) {
1305 goto fail;
1306 }
1307 break;
1308 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001309 (void) BIO_reset(biobuf);
1310 GENERAL_NAME_print(biobuf, name);
1311 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1312 if (len < 0) {
1313 _setSSLError(NULL, 0, __FILE__, __LINE__);
1314 goto fail;
1315 }
1316 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001317 if (vptr == NULL) {
1318 PyErr_Format(PyExc_ValueError,
1319 "Invalid value %.200s",
1320 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001321 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001322 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001323 t = PyTuple_New(2);
1324 if (t == NULL)
1325 goto fail;
1326 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1327 if (v == NULL) {
1328 Py_DECREF(t);
1329 goto fail;
1330 }
1331 PyTuple_SET_ITEM(t, 0, v);
1332 v = PyUnicode_FromStringAndSize((vptr + 1),
1333 (len - (vptr - buf + 1)));
1334 if (v == NULL) {
1335 Py_DECREF(t);
1336 goto fail;
1337 }
1338 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001339 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001341
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001342 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001343
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001344 if (PyList_Append(peer_alt_names, t) < 0) {
1345 Py_DECREF(t);
1346 goto fail;
1347 }
1348 Py_DECREF(t);
1349 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001350 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001351 }
1352 BIO_free(biobuf);
1353 if (peer_alt_names != Py_None) {
1354 v = PyList_AsTuple(peer_alt_names);
1355 Py_DECREF(peer_alt_names);
1356 return v;
1357 } else {
1358 return peer_alt_names;
1359 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001360
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001361
1362 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001363 if (biobuf != NULL)
1364 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001365
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 if (peer_alt_names != Py_None) {
1367 Py_XDECREF(peer_alt_names);
1368 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001369
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001371}
1372
1373static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001374_get_aia_uri(X509 *certificate, int nid) {
1375 PyObject *lst = NULL, *ostr = NULL;
1376 int i, result;
1377 AUTHORITY_INFO_ACCESS *info;
1378
1379 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001380 if (info == NULL)
1381 return Py_None;
1382 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1383 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001384 return Py_None;
1385 }
1386
1387 if ((lst = PyList_New(0)) == NULL) {
1388 goto fail;
1389 }
1390
1391 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1392 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1393 ASN1_IA5STRING *uri;
1394
1395 if ((OBJ_obj2nid(ad->method) != nid) ||
1396 (ad->location->type != GEN_URI)) {
1397 continue;
1398 }
1399 uri = ad->location->d.uniformResourceIdentifier;
1400 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1401 uri->length);
1402 if (ostr == NULL) {
1403 goto fail;
1404 }
1405 result = PyList_Append(lst, ostr);
1406 Py_DECREF(ostr);
1407 if (result < 0) {
1408 goto fail;
1409 }
1410 }
1411 AUTHORITY_INFO_ACCESS_free(info);
1412
1413 /* convert to tuple or None */
1414 if (PyList_Size(lst) == 0) {
1415 Py_DECREF(lst);
1416 return Py_None;
1417 } else {
1418 PyObject *tup;
1419 tup = PyList_AsTuple(lst);
1420 Py_DECREF(lst);
1421 return tup;
1422 }
1423
1424 fail:
1425 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001426 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001427 return NULL;
1428}
1429
1430static PyObject *
1431_get_crl_dp(X509 *certificate) {
1432 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001433 int i, j;
1434 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001435
Christian Heimes598894f2016-09-05 23:19:05 +02001436 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001437
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001438 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001439 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001440
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001441 lst = PyList_New(0);
1442 if (lst == NULL)
1443 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001444
1445 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1446 DIST_POINT *dp;
1447 STACK_OF(GENERAL_NAME) *gns;
1448
1449 dp = sk_DIST_POINT_value(dps, i);
1450 gns = dp->distpoint->name.fullname;
1451
1452 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1453 GENERAL_NAME *gn;
1454 ASN1_IA5STRING *uri;
1455 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001456 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001457
1458 gn = sk_GENERAL_NAME_value(gns, j);
1459 if (gn->type != GEN_URI) {
1460 continue;
1461 }
1462 uri = gn->d.uniformResourceIdentifier;
1463 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1464 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001465 if (ouri == NULL)
1466 goto done;
1467
1468 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001469 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001470 if (err < 0)
1471 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001472 }
1473 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001474
1475 /* Convert to tuple. */
1476 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1477
1478 done:
1479 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001480 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001481 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001482}
1483
1484static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001485_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001486
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001487 PyObject *retval = NULL;
1488 BIO *biobuf = NULL;
1489 PyObject *peer;
1490 PyObject *peer_alt_names = NULL;
1491 PyObject *issuer;
1492 PyObject *version;
1493 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001494 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001495 ASN1_INTEGER *serialNumber;
1496 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001497 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001498 ASN1_TIME *notBefore, *notAfter;
1499 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001500
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001501 retval = PyDict_New();
1502 if (retval == NULL)
1503 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001504
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001505 peer = _create_tuple_for_X509_NAME(
1506 X509_get_subject_name(certificate));
1507 if (peer == NULL)
1508 goto fail0;
1509 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1510 Py_DECREF(peer);
1511 goto fail0;
1512 }
1513 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001514
Antoine Pitroufb046912010-11-09 20:21:19 +00001515 issuer = _create_tuple_for_X509_NAME(
1516 X509_get_issuer_name(certificate));
1517 if (issuer == NULL)
1518 goto fail0;
1519 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001520 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001521 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001523 Py_DECREF(issuer);
1524
1525 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001526 if (version == NULL)
1527 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001528 if (PyDict_SetItemString(retval, "version", version) < 0) {
1529 Py_DECREF(version);
1530 goto fail0;
1531 }
1532 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001533
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001534 /* get a memory buffer */
1535 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001536
Antoine Pitroufb046912010-11-09 20:21:19 +00001537 (void) BIO_reset(biobuf);
1538 serialNumber = X509_get_serialNumber(certificate);
1539 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1540 i2a_ASN1_INTEGER(biobuf, serialNumber);
1541 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1542 if (len < 0) {
1543 _setSSLError(NULL, 0, __FILE__, __LINE__);
1544 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001545 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001546 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1547 if (sn_obj == NULL)
1548 goto fail1;
1549 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1550 Py_DECREF(sn_obj);
1551 goto fail1;
1552 }
1553 Py_DECREF(sn_obj);
1554
1555 (void) BIO_reset(biobuf);
1556 notBefore = X509_get_notBefore(certificate);
1557 ASN1_TIME_print(biobuf, notBefore);
1558 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1559 if (len < 0) {
1560 _setSSLError(NULL, 0, __FILE__, __LINE__);
1561 goto fail1;
1562 }
1563 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1564 if (pnotBefore == NULL)
1565 goto fail1;
1566 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1567 Py_DECREF(pnotBefore);
1568 goto fail1;
1569 }
1570 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001571
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001572 (void) BIO_reset(biobuf);
1573 notAfter = X509_get_notAfter(certificate);
1574 ASN1_TIME_print(biobuf, notAfter);
1575 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1576 if (len < 0) {
1577 _setSSLError(NULL, 0, __FILE__, __LINE__);
1578 goto fail1;
1579 }
1580 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1581 if (pnotAfter == NULL)
1582 goto fail1;
1583 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1584 Py_DECREF(pnotAfter);
1585 goto fail1;
1586 }
1587 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001588
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001589 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001590
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001591 peer_alt_names = _get_peer_alt_names(certificate);
1592 if (peer_alt_names == NULL)
1593 goto fail1;
1594 else if (peer_alt_names != Py_None) {
1595 if (PyDict_SetItemString(retval, "subjectAltName",
1596 peer_alt_names) < 0) {
1597 Py_DECREF(peer_alt_names);
1598 goto fail1;
1599 }
1600 Py_DECREF(peer_alt_names);
1601 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001602
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001603 /* Authority Information Access: OCSP URIs */
1604 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1605 if (obj == NULL) {
1606 goto fail1;
1607 } else if (obj != Py_None) {
1608 result = PyDict_SetItemString(retval, "OCSP", obj);
1609 Py_DECREF(obj);
1610 if (result < 0) {
1611 goto fail1;
1612 }
1613 }
1614
1615 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1616 if (obj == NULL) {
1617 goto fail1;
1618 } else if (obj != Py_None) {
1619 result = PyDict_SetItemString(retval, "caIssuers", obj);
1620 Py_DECREF(obj);
1621 if (result < 0) {
1622 goto fail1;
1623 }
1624 }
1625
1626 /* CDP (CRL distribution points) */
1627 obj = _get_crl_dp(certificate);
1628 if (obj == NULL) {
1629 goto fail1;
1630 } else if (obj != Py_None) {
1631 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1632 Py_DECREF(obj);
1633 if (result < 0) {
1634 goto fail1;
1635 }
1636 }
1637
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001638 BIO_free(biobuf);
1639 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001640
1641 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001642 if (biobuf != NULL)
1643 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001644 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001645 Py_XDECREF(retval);
1646 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001647}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001648
Christian Heimes9a5395a2013-06-17 15:44:12 +02001649static PyObject *
1650_certificate_to_der(X509 *certificate)
1651{
1652 unsigned char *bytes_buf = NULL;
1653 int len;
1654 PyObject *retval;
1655
1656 bytes_buf = NULL;
1657 len = i2d_X509(certificate, &bytes_buf);
1658 if (len < 0) {
1659 _setSSLError(NULL, 0, __FILE__, __LINE__);
1660 return NULL;
1661 }
1662 /* this is actually an immutable bytes sequence */
1663 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1664 OPENSSL_free(bytes_buf);
1665 return retval;
1666}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001667
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001668/*[clinic input]
1669_ssl._test_decode_cert
1670 path: object(converter="PyUnicode_FSConverter")
1671 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001672
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001673[clinic start generated code]*/
1674
1675static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001676_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1677/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001678{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001679 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001680 X509 *x=NULL;
1681 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001682
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001683 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1684 PyErr_SetString(PySSLErrorObject,
1685 "Can't malloc memory to read file");
1686 goto fail0;
1687 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001688
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001689 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001690 PyErr_SetString(PySSLErrorObject,
1691 "Can't open file");
1692 goto fail0;
1693 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001694
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001695 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1696 if (x == NULL) {
1697 PyErr_SetString(PySSLErrorObject,
1698 "Error decoding PEM-encoded file");
1699 goto fail0;
1700 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001701
Antoine Pitroufb046912010-11-09 20:21:19 +00001702 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001703 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001704
1705 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001706 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001707 if (cert != NULL) BIO_free(cert);
1708 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001709}
1710
1711
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001712/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001713_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001714 der as binary_mode: bool = False
1715 /
1716
1717Returns the certificate for the peer.
1718
1719If no certificate was provided, returns None. If a certificate was
1720provided, but not validated, returns an empty dictionary. Otherwise
1721returns a dict containing information about the peer certificate.
1722
1723If the optional argument is True, returns a DER-encoded copy of the
1724peer certificate, or None if no certificate was provided. This will
1725return the certificate even if it wasn't validated.
1726[clinic start generated code]*/
1727
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001728static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001729_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1730/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001731{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001732 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001733 X509 *peer_cert;
1734 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001735
Christian Heimes66dc33b2017-05-23 16:02:02 -07001736 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001737 PyErr_SetString(PyExc_ValueError,
1738 "handshake not done yet");
1739 return NULL;
1740 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001741 peer_cert = SSL_get_peer_certificate(self->ssl);
1742 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001743 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001744
Antoine Pitrou721738f2012-08-15 23:20:39 +02001745 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001746 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001747 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001748 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001749 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001750 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001751 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001752 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001753 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001754 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001755 X509_free(peer_cert);
1756 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001757}
1758
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001759static PyObject *
1760cipher_to_tuple(const SSL_CIPHER *cipher)
1761{
1762 const char *cipher_name, *cipher_protocol;
1763 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001764 if (retval == NULL)
1765 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001766
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001767 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001768 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001769 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001770 PyTuple_SET_ITEM(retval, 0, Py_None);
1771 } else {
1772 v = PyUnicode_FromString(cipher_name);
1773 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001774 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001775 PyTuple_SET_ITEM(retval, 0, v);
1776 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001777
1778 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001779 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001780 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001781 PyTuple_SET_ITEM(retval, 1, Py_None);
1782 } else {
1783 v = PyUnicode_FromString(cipher_protocol);
1784 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001785 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001786 PyTuple_SET_ITEM(retval, 1, v);
1787 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001788
1789 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001790 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001791 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001792 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001793
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001794 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001795
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001796 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001797 Py_DECREF(retval);
1798 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001799}
1800
Christian Heimes25bfcd52016-09-06 00:04:45 +02001801#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1802static PyObject *
1803cipher_to_dict(const SSL_CIPHER *cipher)
1804{
1805 const char *cipher_name, *cipher_protocol;
1806
1807 unsigned long cipher_id;
1808 int alg_bits, strength_bits, len;
1809 char buf[512] = {0};
1810#if OPENSSL_VERSION_1_1
1811 int aead, nid;
1812 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1813#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001814
1815 /* can be NULL */
1816 cipher_name = SSL_CIPHER_get_name(cipher);
1817 cipher_protocol = SSL_CIPHER_get_version(cipher);
1818 cipher_id = SSL_CIPHER_get_id(cipher);
1819 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001820 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1821 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001822 if (len > 1 && buf[len-1] == '\n')
1823 buf[len-1] = '\0';
1824 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1825
1826#if OPENSSL_VERSION_1_1
1827 aead = SSL_CIPHER_is_aead(cipher);
1828 nid = SSL_CIPHER_get_cipher_nid(cipher);
1829 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1830 nid = SSL_CIPHER_get_digest_nid(cipher);
1831 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1832 nid = SSL_CIPHER_get_kx_nid(cipher);
1833 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1834 nid = SSL_CIPHER_get_auth_nid(cipher);
1835 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1836#endif
1837
Victor Stinner410b9882016-09-12 12:00:23 +02001838 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001839 "{sksssssssisi"
1840#if OPENSSL_VERSION_1_1
1841 "sOssssssss"
1842#endif
1843 "}",
1844 "id", cipher_id,
1845 "name", cipher_name,
1846 "protocol", cipher_protocol,
1847 "description", buf,
1848 "strength_bits", strength_bits,
1849 "alg_bits", alg_bits
1850#if OPENSSL_VERSION_1_1
1851 ,"aead", aead ? Py_True : Py_False,
1852 "symmetric", skcipher,
1853 "digest", digest,
1854 "kea", kx,
1855 "auth", auth
1856#endif
1857 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001858}
1859#endif
1860
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001861/*[clinic input]
1862_ssl._SSLSocket.shared_ciphers
1863[clinic start generated code]*/
1864
1865static PyObject *
1866_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1867/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001868{
1869 STACK_OF(SSL_CIPHER) *ciphers;
1870 int i;
1871 PyObject *res;
1872
Christian Heimes598894f2016-09-05 23:19:05 +02001873 ciphers = SSL_get_ciphers(self->ssl);
1874 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001875 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001876 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1877 if (!res)
1878 return NULL;
1879 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1880 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1881 if (!tup) {
1882 Py_DECREF(res);
1883 return NULL;
1884 }
1885 PyList_SET_ITEM(res, i, tup);
1886 }
1887 return res;
1888}
1889
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001890/*[clinic input]
1891_ssl._SSLSocket.cipher
1892[clinic start generated code]*/
1893
1894static PyObject *
1895_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1896/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001897{
1898 const SSL_CIPHER *current;
1899
1900 if (self->ssl == NULL)
1901 Py_RETURN_NONE;
1902 current = SSL_get_current_cipher(self->ssl);
1903 if (current == NULL)
1904 Py_RETURN_NONE;
1905 return cipher_to_tuple(current);
1906}
1907
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001908/*[clinic input]
1909_ssl._SSLSocket.version
1910[clinic start generated code]*/
1911
1912static PyObject *
1913_ssl__SSLSocket_version_impl(PySSLSocket *self)
1914/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001915{
1916 const char *version;
1917
1918 if (self->ssl == NULL)
1919 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001920 if (!SSL_is_init_finished(self->ssl)) {
1921 /* handshake not finished */
1922 Py_RETURN_NONE;
1923 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001924 version = SSL_get_version(self->ssl);
1925 if (!strcmp(version, "unknown"))
1926 Py_RETURN_NONE;
1927 return PyUnicode_FromString(version);
1928}
1929
Christian Heimes29eab552018-02-25 12:31:33 +01001930#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001931/*[clinic input]
1932_ssl._SSLSocket.selected_npn_protocol
1933[clinic start generated code]*/
1934
1935static PyObject *
1936_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1937/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1938{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001939 const unsigned char *out;
1940 unsigned int outlen;
1941
Victor Stinner4569cd52013-06-23 14:58:43 +02001942 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001943 &out, &outlen);
1944
1945 if (out == NULL)
1946 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001947 return PyUnicode_FromStringAndSize((char *)out, outlen);
1948}
1949#endif
1950
Christian Heimes29eab552018-02-25 12:31:33 +01001951#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001952/*[clinic input]
1953_ssl._SSLSocket.selected_alpn_protocol
1954[clinic start generated code]*/
1955
1956static PyObject *
1957_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1958/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1959{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001960 const unsigned char *out;
1961 unsigned int outlen;
1962
1963 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1964
1965 if (out == NULL)
1966 Py_RETURN_NONE;
1967 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001968}
1969#endif
1970
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001971/*[clinic input]
1972_ssl._SSLSocket.compression
1973[clinic start generated code]*/
1974
1975static PyObject *
1976_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1977/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1978{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001979#ifdef OPENSSL_NO_COMP
1980 Py_RETURN_NONE;
1981#else
1982 const COMP_METHOD *comp_method;
1983 const char *short_name;
1984
1985 if (self->ssl == NULL)
1986 Py_RETURN_NONE;
1987 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001988 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001989 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001990 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001991 if (short_name == NULL)
1992 Py_RETURN_NONE;
1993 return PyUnicode_DecodeFSDefault(short_name);
1994#endif
1995}
1996
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001997static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1998 Py_INCREF(self->ctx);
1999 return self->ctx;
2000}
2001
2002static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2003 void *closure) {
2004
2005 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002006#if !HAVE_SNI
2007 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2008 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002009 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002010#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002011 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002012 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002013 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002014#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002015 } else {
2016 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
2017 return -1;
2018 }
2019
2020 return 0;
2021}
2022
2023PyDoc_STRVAR(PySSL_set_context_doc,
2024"_setter_context(ctx)\n\
2025\
2026This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002027used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002028on the SSLContext to change the certificate information associated with the\n\
2029SSLSocket before the cryptographic exchange handshake messages\n");
2030
2031
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002032static PyObject *
2033PySSL_get_server_side(PySSLSocket *self, void *c)
2034{
2035 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2036}
2037
2038PyDoc_STRVAR(PySSL_get_server_side_doc,
2039"Whether this is a server-side socket.");
2040
2041static PyObject *
2042PySSL_get_server_hostname(PySSLSocket *self, void *c)
2043{
2044 if (self->server_hostname == NULL)
2045 Py_RETURN_NONE;
2046 Py_INCREF(self->server_hostname);
2047 return self->server_hostname;
2048}
2049
2050PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2051"The currently set server hostname (for SNI).");
2052
2053static PyObject *
2054PySSL_get_owner(PySSLSocket *self, void *c)
2055{
2056 PyObject *owner;
2057
2058 if (self->owner == NULL)
2059 Py_RETURN_NONE;
2060
2061 owner = PyWeakref_GetObject(self->owner);
2062 Py_INCREF(owner);
2063 return owner;
2064}
2065
2066static int
2067PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2068{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002069 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002070 if (self->owner == NULL)
2071 return -1;
2072 return 0;
2073}
2074
2075PyDoc_STRVAR(PySSL_get_owner_doc,
2076"The Python-level owner of this object.\
2077Passed as \"self\" in servername callback.");
2078
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002079
Antoine Pitrou152efa22010-05-16 18:19:27 +00002080static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002081{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002082 if (self->ssl)
2083 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002084 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002085 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002086 Py_XDECREF(self->server_hostname);
2087 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002088 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002089}
2090
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002091/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002092 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002093 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002094 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002095
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002096static int
Victor Stinner14690702015-04-06 22:46:13 +02002097PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002098{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002099 int rc;
2100#ifdef HAVE_POLL
2101 struct pollfd pollfd;
2102 _PyTime_t ms;
2103#else
2104 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002105 fd_set fds;
2106 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002107#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002108
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002109 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002110 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002111 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002112 else if (timeout < 0) {
2113 if (s->sock_timeout > 0)
2114 return SOCKET_HAS_TIMED_OUT;
2115 else
2116 return SOCKET_IS_BLOCKING;
2117 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002118
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002119 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002120 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002121 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002122
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002123 /* Prefer poll, if available, since you can poll() any fd
2124 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002125#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002126 pollfd.fd = s->sock_fd;
2127 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002128
Victor Stinner14690702015-04-06 22:46:13 +02002129 /* timeout is in seconds, poll() uses milliseconds */
2130 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002131 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002132
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002133 PySSL_BEGIN_ALLOW_THREADS
2134 rc = poll(&pollfd, 1, (int)ms);
2135 PySSL_END_ALLOW_THREADS
2136#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002137 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002138 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002139 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002140
Victor Stinner14690702015-04-06 22:46:13 +02002141 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002142
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002143 FD_ZERO(&fds);
2144 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002145
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002146 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002147 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002148 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002149 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002150 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002151 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002152 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002153 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002154#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002155
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002156 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2157 (when we are able to write or when there's something to read) */
2158 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002159}
2160
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002161/*[clinic input]
2162_ssl._SSLSocket.write
2163 b: Py_buffer
2164 /
2165
2166Writes the bytes-like object b into the SSL object.
2167
2168Returns the number of bytes written.
2169[clinic start generated code]*/
2170
2171static PyObject *
2172_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2173/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002174{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002175 int len;
2176 int sockstate;
2177 int err;
2178 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002179 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002180 _PyTime_t timeout, deadline = 0;
2181 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002182
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002183 if (sock != NULL) {
2184 if (((PyObject*)sock) == Py_None) {
2185 _setSSLError("Underlying socket connection gone",
2186 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2187 return NULL;
2188 }
2189 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002190 }
2191
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002192 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002193 PyErr_Format(PyExc_OverflowError,
2194 "string longer than %d bytes", INT_MAX);
2195 goto error;
2196 }
2197
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002198 if (sock != NULL) {
2199 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002200 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002201 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2202 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2203 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002204
Victor Stinner14690702015-04-06 22:46:13 +02002205 timeout = GET_SOCKET_TIMEOUT(sock);
2206 has_timeout = (timeout > 0);
2207 if (has_timeout)
2208 deadline = _PyTime_GetMonotonicClock() + timeout;
2209
2210 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002211 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002212 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002213 "The write operation timed out");
2214 goto error;
2215 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2216 PyErr_SetString(PySSLErrorObject,
2217 "Underlying socket has been closed.");
2218 goto error;
2219 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2220 PyErr_SetString(PySSLErrorObject,
2221 "Underlying socket too large for select().");
2222 goto error;
2223 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002224
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002225 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002226 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002227 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002228 _PySSL_UPDATE_ERRNO_IF(len <= 0, self, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002229 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07002230 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002231
2232 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002233 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002234
Victor Stinner14690702015-04-06 22:46:13 +02002235 if (has_timeout)
2236 timeout = deadline - _PyTime_GetMonotonicClock();
2237
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002238 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002239 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002240 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002241 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002242 } else {
2243 sockstate = SOCKET_OPERATION_OK;
2244 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002245
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002246 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002247 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002248 "The write operation timed out");
2249 goto error;
2250 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2251 PyErr_SetString(PySSLErrorObject,
2252 "Underlying socket has been closed.");
2253 goto error;
2254 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2255 break;
2256 }
2257 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002258
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002259 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002260 if (len > 0)
2261 return PyLong_FromLong(len);
2262 else
2263 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002264
2265error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002266 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002267 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002268}
2269
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002270/*[clinic input]
2271_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002272
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002273Returns the number of already decrypted bytes available for read, pending on the connection.
2274[clinic start generated code]*/
2275
2276static PyObject *
2277_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2278/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002279{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002280 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002281
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002282 PySSL_BEGIN_ALLOW_THREADS
2283 count = SSL_pending(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002284 _PySSL_UPDATE_ERRNO_IF(count < 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002285 PySSL_END_ALLOW_THREADS
2286 if (count < 0)
2287 return PySSL_SetError(self, count, __FILE__, __LINE__);
2288 else
2289 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002290}
2291
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002292/*[clinic input]
2293_ssl._SSLSocket.read
2294 size as len: int
2295 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002296 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002297 ]
2298 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002299
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002300Read up to size bytes from the SSL socket.
2301[clinic start generated code]*/
2302
2303static PyObject *
2304_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2305 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002306/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002307{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002308 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002309 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002310 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002311 int sockstate;
2312 int err;
2313 int nonblocking;
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 Janssen54cc54c2007-12-14 22:08:56 +00002317
Martin Panter5503d472016-03-27 05:35:19 +00002318 if (!group_right_1 && len < 0) {
2319 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2320 return NULL;
2321 }
2322
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002323 if (sock != NULL) {
2324 if (((PyObject*)sock) == Py_None) {
2325 _setSSLError("Underlying socket connection gone",
2326 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2327 return NULL;
2328 }
2329 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002330 }
2331
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002332 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002333 dest = PyBytes_FromStringAndSize(NULL, len);
2334 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002335 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002336 if (len == 0) {
2337 Py_XDECREF(sock);
2338 return dest;
2339 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002340 mem = PyBytes_AS_STRING(dest);
2341 }
2342 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002343 mem = buffer->buf;
2344 if (len <= 0 || len > buffer->len) {
2345 len = (int) buffer->len;
2346 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002347 PyErr_SetString(PyExc_OverflowError,
2348 "maximum length can't fit in a C 'int'");
2349 goto error;
2350 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002351 if (len == 0) {
2352 count = 0;
2353 goto done;
2354 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002355 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002356 }
2357
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002358 if (sock != NULL) {
2359 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002360 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002361 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2362 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2363 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002364
Victor Stinner14690702015-04-06 22:46:13 +02002365 timeout = GET_SOCKET_TIMEOUT(sock);
2366 has_timeout = (timeout > 0);
2367 if (has_timeout)
2368 deadline = _PyTime_GetMonotonicClock() + timeout;
2369
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002370 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002371 PySSL_BEGIN_ALLOW_THREADS
2372 count = SSL_read(self->ssl, mem, len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002373 _PySSL_UPDATE_ERRNO_IF(count <= 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002374 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002375
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002376 if (PyErr_CheckSignals())
2377 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002378
Victor Stinner14690702015-04-06 22:46:13 +02002379 if (has_timeout)
2380 timeout = deadline - _PyTime_GetMonotonicClock();
2381
Steve Dowere6eb48c2017-09-08 15:16:15 -07002382 err = self->ssl_errno;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002383 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002384 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002385 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002386 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002387 } else if (err == SSL_ERROR_ZERO_RETURN &&
2388 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002389 {
2390 count = 0;
2391 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002392 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002393 else
2394 sockstate = SOCKET_OPERATION_OK;
2395
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002396 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002397 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002398 "The read operation timed out");
2399 goto error;
2400 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2401 break;
2402 }
2403 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002404
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002405 if (count <= 0) {
2406 PySSL_SetError(self, count, __FILE__, __LINE__);
2407 goto error;
2408 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002409
2410done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002411 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002412 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002413 _PyBytes_Resize(&dest, count);
2414 return dest;
2415 }
2416 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002417 return PyLong_FromLong(count);
2418 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002419
2420error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002421 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002422 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002423 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002424 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002425}
2426
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002427/*[clinic input]
2428_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002429
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002430Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002431[clinic start generated code]*/
2432
2433static PyObject *
2434_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002435/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002436{
Steve Dowere6eb48c2017-09-08 15:16:15 -07002437 int err, sockstate, nonblocking;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002438 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002439 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002440 _PyTime_t timeout, deadline = 0;
2441 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002442
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002443 if (sock != NULL) {
2444 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002445 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002446 _setSSLError("Underlying socket connection gone",
2447 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2448 return NULL;
2449 }
2450 Py_INCREF(sock);
2451
2452 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002453 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002454 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2455 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002456 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002457
Victor Stinner14690702015-04-06 22:46:13 +02002458 timeout = GET_SOCKET_TIMEOUT(sock);
2459 has_timeout = (timeout > 0);
2460 if (has_timeout)
2461 deadline = _PyTime_GetMonotonicClock() + timeout;
2462
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002463 while (1) {
2464 PySSL_BEGIN_ALLOW_THREADS
2465 /* Disable read-ahead so that unwrap can work correctly.
2466 * Otherwise OpenSSL might read in too much data,
2467 * eating clear text data that happens to be
2468 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002469 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002470 * function is used and the shutdown_seen_zero != 0
2471 * condition is met.
2472 */
2473 if (self->shutdown_seen_zero)
2474 SSL_set_read_ahead(self->ssl, 0);
2475 err = SSL_shutdown(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002476 _PySSL_UPDATE_ERRNO_IF(err < 0, self, err);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002477 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002478
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002479 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2480 if (err > 0)
2481 break;
2482 if (err == 0) {
2483 /* Don't loop endlessly; instead preserve legacy
2484 behaviour of trying SSL_shutdown() only twice.
2485 This looks necessary for OpenSSL < 0.9.8m */
2486 if (++zeros > 1)
2487 break;
2488 /* Shutdown was sent, now try receiving */
2489 self->shutdown_seen_zero = 1;
2490 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002491 }
2492
Victor Stinner14690702015-04-06 22:46:13 +02002493 if (has_timeout)
2494 timeout = deadline - _PyTime_GetMonotonicClock();
2495
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002496 /* Possibly retry shutdown until timeout or failure */
Steve Dowere6eb48c2017-09-08 15:16:15 -07002497 _PySSL_UPDATE_ERRNO(self, err);
2498 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002499 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002500 else if (self->ssl_errno == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002501 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002502 else
2503 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002504
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002505 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowere6eb48c2017-09-08 15:16:15 -07002506 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002507 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002508 "The read operation timed out");
2509 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002510 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002511 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002512 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002513 }
2514 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2515 PyErr_SetString(PySSLErrorObject,
2516 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002517 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002518 }
2519 else if (sockstate != SOCKET_OPERATION_OK)
2520 /* Retain the SSL error code */
2521 break;
2522 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002523
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002524 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002525 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002526 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002527 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002528 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002529 /* It's already INCREF'ed */
2530 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002531 else
2532 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002533
2534error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002535 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002536 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002537}
2538
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002539/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002540_ssl._SSLSocket.get_channel_binding
2541 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002542
Christian Heimes141c5e82018-02-24 21:10:57 +01002543Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002544
Christian Heimes141c5e82018-02-24 21:10:57 +01002545Raise ValueError if the requested `cb_type` is not supported. Return bytes
2546of the data or None if the data is not available (e.g. before the handshake).
2547Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002548[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002549
Antoine Pitroud6494802011-07-21 01:11:30 +02002550static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002551_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2552 const char *cb_type)
2553/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002554{
Antoine Pitroud6494802011-07-21 01:11:30 +02002555 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002556 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002557
Christian Heimes141c5e82018-02-24 21:10:57 +01002558 if (strcmp(cb_type, "tls-unique") == 0) {
2559 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2560 /* if session is resumed XOR we are the client */
2561 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2562 }
2563 else {
2564 /* if a new session XOR we are the server */
2565 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2566 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002567 }
2568 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002569 PyErr_Format(
2570 PyExc_ValueError,
2571 "'%s' channel binding type not implemented",
2572 cb_type
2573 );
2574 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002575 }
2576
2577 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002578 if (len == 0)
2579 Py_RETURN_NONE;
2580
Christian Heimes141c5e82018-02-24 21:10:57 +01002581 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002582}
2583
Christian Heimes99a65702016-09-10 23:44:53 +02002584#ifdef OPENSSL_VERSION_1_1
2585
2586static SSL_SESSION*
2587_ssl_session_dup(SSL_SESSION *session) {
2588 SSL_SESSION *newsession = NULL;
2589 int slen;
2590 unsigned char *senc = NULL, *p;
2591 const unsigned char *const_p;
2592
2593 if (session == NULL) {
2594 PyErr_SetString(PyExc_ValueError, "Invalid session");
2595 goto error;
2596 }
2597
2598 /* get length */
2599 slen = i2d_SSL_SESSION(session, NULL);
2600 if (slen == 0 || slen > 0xFF00) {
2601 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2602 goto error;
2603 }
2604 if ((senc = PyMem_Malloc(slen)) == NULL) {
2605 PyErr_NoMemory();
2606 goto error;
2607 }
2608 p = senc;
2609 if (!i2d_SSL_SESSION(session, &p)) {
2610 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2611 goto error;
2612 }
2613 const_p = senc;
2614 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2615 if (session == NULL) {
2616 goto error;
2617 }
2618 PyMem_Free(senc);
2619 return newsession;
2620 error:
2621 if (senc != NULL) {
2622 PyMem_Free(senc);
2623 }
2624 return NULL;
2625}
2626#endif
2627
2628static PyObject *
2629PySSL_get_session(PySSLSocket *self, void *closure) {
2630 /* get_session can return sessions from a server-side connection,
2631 * it does not check for handshake done or client socket. */
2632 PySSLSession *pysess;
2633 SSL_SESSION *session;
2634
2635#ifdef OPENSSL_VERSION_1_1
2636 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2637 * https://github.com/openssl/openssl/issues/1550 */
2638 session = SSL_get0_session(self->ssl); /* borrowed reference */
2639 if (session == NULL) {
2640 Py_RETURN_NONE;
2641 }
2642 if ((session = _ssl_session_dup(session)) == NULL) {
2643 return NULL;
2644 }
2645#else
2646 session = SSL_get1_session(self->ssl);
2647 if (session == NULL) {
2648 Py_RETURN_NONE;
2649 }
2650#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002651 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002652 if (pysess == NULL) {
2653 SSL_SESSION_free(session);
2654 return NULL;
2655 }
2656
2657 assert(self->ctx);
2658 pysess->ctx = self->ctx;
2659 Py_INCREF(pysess->ctx);
2660 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002661 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002662 return (PyObject *)pysess;
2663}
2664
2665static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2666 void *closure)
2667 {
2668 PySSLSession *pysess;
2669#ifdef OPENSSL_VERSION_1_1
2670 SSL_SESSION *session;
2671#endif
2672 int result;
2673
2674 if (!PySSLSession_Check(value)) {
2675 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2676 return -1;
2677 }
2678 pysess = (PySSLSession *)value;
2679
2680 if (self->ctx->ctx != pysess->ctx->ctx) {
2681 PyErr_SetString(PyExc_ValueError,
2682 "Session refers to a different SSLContext.");
2683 return -1;
2684 }
2685 if (self->socket_type != PY_SSL_CLIENT) {
2686 PyErr_SetString(PyExc_ValueError,
2687 "Cannot set session for server-side SSLSocket.");
2688 return -1;
2689 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002690 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002691 PyErr_SetString(PyExc_ValueError,
2692 "Cannot set session after handshake.");
2693 return -1;
2694 }
2695#ifdef OPENSSL_VERSION_1_1
2696 /* duplicate session */
2697 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2698 return -1;
2699 }
2700 result = SSL_set_session(self->ssl, session);
2701 /* free duplicate, SSL_set_session() bumps ref count */
2702 SSL_SESSION_free(session);
2703#else
2704 result = SSL_set_session(self->ssl, pysess->session);
2705#endif
2706 if (result == 0) {
2707 _setSSLError(NULL, 0, __FILE__, __LINE__);
2708 return -1;
2709 }
2710 return 0;
2711}
2712
2713PyDoc_STRVAR(PySSL_set_session_doc,
2714"_setter_session(session)\n\
2715\
2716Get / set SSLSession.");
2717
2718static PyObject *
2719PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2720 if (SSL_session_reused(self->ssl)) {
2721 Py_RETURN_TRUE;
2722 } else {
2723 Py_RETURN_FALSE;
2724 }
2725}
2726
2727PyDoc_STRVAR(PySSL_get_session_reused_doc,
2728"Was the client session reused during handshake?");
2729
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002730static PyGetSetDef ssl_getsetlist[] = {
2731 {"context", (getter) PySSL_get_context,
2732 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002733 {"server_side", (getter) PySSL_get_server_side, NULL,
2734 PySSL_get_server_side_doc},
2735 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2736 PySSL_get_server_hostname_doc},
2737 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2738 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002739 {"session", (getter) PySSL_get_session,
2740 (setter) PySSL_set_session, PySSL_set_session_doc},
2741 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2742 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002743 {NULL}, /* sentinel */
2744};
2745
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002746static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002747 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2748 _SSL__SSLSOCKET_WRITE_METHODDEF
2749 _SSL__SSLSOCKET_READ_METHODDEF
2750 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002751 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2752 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002753 _SSL__SSLSOCKET_CIPHER_METHODDEF
2754 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2755 _SSL__SSLSOCKET_VERSION_METHODDEF
2756 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2757 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2758 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2759 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002760 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002761};
2762
Antoine Pitrou152efa22010-05-16 18:19:27 +00002763static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002764 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002765 "_ssl._SSLSocket", /*tp_name*/
2766 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002767 0, /*tp_itemsize*/
2768 /* methods */
2769 (destructor)PySSL_dealloc, /*tp_dealloc*/
2770 0, /*tp_print*/
2771 0, /*tp_getattr*/
2772 0, /*tp_setattr*/
2773 0, /*tp_reserved*/
2774 0, /*tp_repr*/
2775 0, /*tp_as_number*/
2776 0, /*tp_as_sequence*/
2777 0, /*tp_as_mapping*/
2778 0, /*tp_hash*/
2779 0, /*tp_call*/
2780 0, /*tp_str*/
2781 0, /*tp_getattro*/
2782 0, /*tp_setattro*/
2783 0, /*tp_as_buffer*/
2784 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2785 0, /*tp_doc*/
2786 0, /*tp_traverse*/
2787 0, /*tp_clear*/
2788 0, /*tp_richcompare*/
2789 0, /*tp_weaklistoffset*/
2790 0, /*tp_iter*/
2791 0, /*tp_iternext*/
2792 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002793 0, /*tp_members*/
2794 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002795};
2796
Antoine Pitrou152efa22010-05-16 18:19:27 +00002797
2798/*
2799 * _SSLContext objects
2800 */
2801
Christian Heimes5fe668c2016-09-12 00:01:11 +02002802static int
2803_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2804{
2805 int mode;
2806 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2807
2808 switch(n) {
2809 case PY_SSL_CERT_NONE:
2810 mode = SSL_VERIFY_NONE;
2811 break;
2812 case PY_SSL_CERT_OPTIONAL:
2813 mode = SSL_VERIFY_PEER;
2814 break;
2815 case PY_SSL_CERT_REQUIRED:
2816 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2817 break;
2818 default:
2819 PyErr_SetString(PyExc_ValueError,
2820 "invalid value for verify_mode");
2821 return -1;
2822 }
2823 /* keep current verify cb */
2824 verify_cb = SSL_CTX_get_verify_callback(ctx);
2825 SSL_CTX_set_verify(ctx, mode, verify_cb);
2826 return 0;
2827}
2828
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002829/*[clinic input]
2830@classmethod
2831_ssl._SSLContext.__new__
2832 protocol as proto_version: int
2833 /
2834[clinic start generated code]*/
2835
Antoine Pitrou152efa22010-05-16 18:19:27 +00002836static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002837_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2838/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002839{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002840 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002841 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002842 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002843 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002844 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002845#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002846 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002847#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002848
Antoine Pitrou152efa22010-05-16 18:19:27 +00002849 PySSL_BEGIN_ALLOW_THREADS
2850 if (proto_version == PY_SSL_VERSION_TLS1)
2851 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002852#if HAVE_TLSv1_2
2853 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2854 ctx = SSL_CTX_new(TLSv1_1_method());
2855 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2856 ctx = SSL_CTX_new(TLSv1_2_method());
2857#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002858#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002859 else if (proto_version == PY_SSL_VERSION_SSL3)
2860 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002861#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002862#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002863 else if (proto_version == PY_SSL_VERSION_SSL2)
2864 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002865#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002866 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002867 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002868 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2869 ctx = SSL_CTX_new(TLS_client_method());
2870 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2871 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002872 else
2873 proto_version = -1;
2874 PySSL_END_ALLOW_THREADS
2875
2876 if (proto_version == -1) {
2877 PyErr_SetString(PyExc_ValueError,
2878 "invalid protocol version");
2879 return NULL;
2880 }
2881 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002882 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002883 return NULL;
2884 }
2885
2886 assert(type != NULL && type->tp_alloc != NULL);
2887 self = (PySSLContext *) type->tp_alloc(type, 0);
2888 if (self == NULL) {
2889 SSL_CTX_free(ctx);
2890 return NULL;
2891 }
2892 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002893 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01002894 self->protocol = proto_version;
Christian Heimes29eab552018-02-25 12:31:33 +01002895#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02002896 self->npn_protocols = NULL;
2897#endif
Christian Heimes29eab552018-02-25 12:31:33 +01002898#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002899 self->alpn_protocols = NULL;
2900#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002901#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01002902 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002903#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002904 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002905 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2906 self->check_hostname = 1;
2907 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2908 Py_DECREF(self);
2909 return NULL;
2910 }
2911 } else {
2912 self->check_hostname = 0;
2913 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2914 Py_DECREF(self);
2915 return NULL;
2916 }
2917 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002918 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002919 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2920 if (proto_version != PY_SSL_VERSION_SSL2)
2921 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002922 if (proto_version != PY_SSL_VERSION_SSL3)
2923 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002924 /* Minimal security flags for server and client side context.
2925 * Client sockets ignore server-side parameters. */
2926#ifdef SSL_OP_NO_COMPRESSION
2927 options |= SSL_OP_NO_COMPRESSION;
2928#endif
2929#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2930 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2931#endif
2932#ifdef SSL_OP_SINGLE_DH_USE
2933 options |= SSL_OP_SINGLE_DH_USE;
2934#endif
2935#ifdef SSL_OP_SINGLE_ECDH_USE
2936 options |= SSL_OP_SINGLE_ECDH_USE;
2937#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002938 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002939
Semen Zhydenko1295e112017-10-15 21:28:31 +02002940 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02002941 * It's far from perfect but gives users a better head start. */
2942 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01002943#if PY_SSL_DEFAULT_CIPHERS == 2
2944 /* stick to OpenSSL's default settings */
2945 result = 1;
2946#else
2947 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
2948#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02002949 } else {
2950 /* SSLv2 needs MD5 */
2951 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2952 }
2953 if (result == 0) {
2954 Py_DECREF(self);
2955 ERR_clear_error();
2956 PyErr_SetString(PySSLErrorObject,
2957 "No cipher can be selected.");
2958 return NULL;
2959 }
2960
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002961#if defined(SSL_MODE_RELEASE_BUFFERS)
2962 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2963 usage for no cost at all. However, don't do this for OpenSSL versions
2964 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2965 2014-0198. I can't find exactly which beta fixed this CVE, so be
2966 conservative and assume it wasn't fixed until release. We do this check
2967 at runtime to avoid problems from the dynamic linker.
2968 See #25672 for more on this. */
2969 libver = SSLeay();
2970 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2971 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2972 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2973 }
2974#endif
2975
2976
Donald Stufft8ae264c2017-03-02 11:45:29 -05002977#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002978 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2979 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002980 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2981 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002982#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002983 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2984#else
2985 {
2986 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2987 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2988 EC_KEY_free(key);
2989 }
2990#endif
2991#endif
2992
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002993#define SID_CTX "Python"
2994 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2995 sizeof(SID_CTX));
2996#undef SID_CTX
2997
Christian Heimes61d478c2018-01-27 15:51:38 +01002998 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002999#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003000 /* Improve trust chain building when cross-signed intermediate
3001 certificates are present. See https://bugs.python.org/issue23476. */
3002 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003003#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003004 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003005
Antoine Pitrou152efa22010-05-16 18:19:27 +00003006 return (PyObject *)self;
3007}
3008
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003009static int
3010context_traverse(PySSLContext *self, visitproc visit, void *arg)
3011{
3012#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003013 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003014#endif
3015 return 0;
3016}
3017
3018static int
3019context_clear(PySSLContext *self)
3020{
3021#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003022 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003023#endif
3024 return 0;
3025}
3026
Antoine Pitrou152efa22010-05-16 18:19:27 +00003027static void
3028context_dealloc(PySSLContext *self)
3029{
INADA Naokia6296d32017-08-24 14:55:17 +09003030 /* bpo-31095: UnTrack is needed before calling any callbacks */
3031 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003032 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003033 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003034#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003035 PyMem_FREE(self->npn_protocols);
3036#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003037#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003038 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003039#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003040 Py_TYPE(self)->tp_free(self);
3041}
3042
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003043/*[clinic input]
3044_ssl._SSLContext.set_ciphers
3045 cipherlist: str
3046 /
3047[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003048
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003049static PyObject *
3050_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3051/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3052{
3053 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003054 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003055 /* Clearing the error queue is necessary on some OpenSSL versions,
3056 otherwise the error will be reported again when another SSL call
3057 is done. */
3058 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003059 PyErr_SetString(PySSLErrorObject,
3060 "No cipher can be selected.");
3061 return NULL;
3062 }
3063 Py_RETURN_NONE;
3064}
3065
Christian Heimes25bfcd52016-09-06 00:04:45 +02003066#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3067/*[clinic input]
3068_ssl._SSLContext.get_ciphers
3069[clinic start generated code]*/
3070
3071static PyObject *
3072_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3073/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3074{
3075 SSL *ssl = NULL;
3076 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003077 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003078 int i=0;
3079 PyObject *result = NULL, *dct;
3080
3081 ssl = SSL_new(self->ctx);
3082 if (ssl == NULL) {
3083 _setSSLError(NULL, 0, __FILE__, __LINE__);
3084 goto exit;
3085 }
3086 sk = SSL_get_ciphers(ssl);
3087
3088 result = PyList_New(sk_SSL_CIPHER_num(sk));
3089 if (result == NULL) {
3090 goto exit;
3091 }
3092
3093 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3094 cipher = sk_SSL_CIPHER_value(sk, i);
3095 dct = cipher_to_dict(cipher);
3096 if (dct == NULL) {
3097 Py_CLEAR(result);
3098 goto exit;
3099 }
3100 PyList_SET_ITEM(result, i, dct);
3101 }
3102
3103 exit:
3104 if (ssl != NULL)
3105 SSL_free(ssl);
3106 return result;
3107
3108}
3109#endif
3110
3111
Christian Heimes29eab552018-02-25 12:31:33 +01003112#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003113static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003114do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3115 const unsigned char *server_protocols, unsigned int server_protocols_len,
3116 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003117{
Benjamin Peterson88615022015-01-23 17:30:26 -05003118 int ret;
3119 if (client_protocols == NULL) {
3120 client_protocols = (unsigned char *)"";
3121 client_protocols_len = 0;
3122 }
3123 if (server_protocols == NULL) {
3124 server_protocols = (unsigned char *)"";
3125 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003126 }
3127
Benjamin Peterson88615022015-01-23 17:30:26 -05003128 ret = SSL_select_next_proto(out, outlen,
3129 server_protocols, server_protocols_len,
3130 client_protocols, client_protocols_len);
3131 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3132 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003133
3134 return SSL_TLSEXT_ERR_OK;
3135}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003136#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003137
Christian Heimes29eab552018-02-25 12:31:33 +01003138#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003139/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3140static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003141_advertiseNPN_cb(SSL *s,
3142 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003143 void *args)
3144{
3145 PySSLContext *ssl_ctx = (PySSLContext *) args;
3146
3147 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003148 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003149 *len = 0;
3150 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003151 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003152 *len = ssl_ctx->npn_protocols_len;
3153 }
3154
3155 return SSL_TLSEXT_ERR_OK;
3156}
3157/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3158static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003159_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003160 unsigned char **out, unsigned char *outlen,
3161 const unsigned char *server, unsigned int server_len,
3162 void *args)
3163{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003164 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003165 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003166 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003167}
3168#endif
3169
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003170/*[clinic input]
3171_ssl._SSLContext._set_npn_protocols
3172 protos: Py_buffer
3173 /
3174[clinic start generated code]*/
3175
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003176static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003177_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3178 Py_buffer *protos)
3179/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003180{
Christian Heimes29eab552018-02-25 12:31:33 +01003181#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003182 PyMem_Free(self->npn_protocols);
3183 self->npn_protocols = PyMem_Malloc(protos->len);
3184 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003185 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003186 memcpy(self->npn_protocols, protos->buf, protos->len);
3187 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003188
3189 /* set both server and client callbacks, because the context can
3190 * be used to create both types of sockets */
3191 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3192 _advertiseNPN_cb,
3193 self);
3194 SSL_CTX_set_next_proto_select_cb(self->ctx,
3195 _selectNPN_cb,
3196 self);
3197
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003198 Py_RETURN_NONE;
3199#else
3200 PyErr_SetString(PyExc_NotImplementedError,
3201 "The NPN extension requires OpenSSL 1.0.1 or later.");
3202 return NULL;
3203#endif
3204}
3205
Christian Heimes29eab552018-02-25 12:31:33 +01003206#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003207static int
3208_selectALPN_cb(SSL *s,
3209 const unsigned char **out, unsigned char *outlen,
3210 const unsigned char *client_protocols, unsigned int client_protocols_len,
3211 void *args)
3212{
3213 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003214 return do_protocol_selection(1, (unsigned char **)out, outlen,
3215 ctx->alpn_protocols, ctx->alpn_protocols_len,
3216 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003217}
3218#endif
3219
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003220/*[clinic input]
3221_ssl._SSLContext._set_alpn_protocols
3222 protos: Py_buffer
3223 /
3224[clinic start generated code]*/
3225
Benjamin Petersoncca27322015-01-23 16:35:37 -05003226static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003227_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3228 Py_buffer *protos)
3229/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003230{
Christian Heimes29eab552018-02-25 12:31:33 +01003231#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003232 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003233 PyErr_Format(PyExc_OverflowError,
3234 "protocols longer than %d bytes", UINT_MAX);
3235 return NULL;
3236 }
3237
Benjamin Petersoncca27322015-01-23 16:35:37 -05003238 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003239 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003240 if (!self->alpn_protocols)
3241 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003242 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003243 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003244
3245 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3246 return PyErr_NoMemory();
3247 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3248
Benjamin Petersoncca27322015-01-23 16:35:37 -05003249 Py_RETURN_NONE;
3250#else
3251 PyErr_SetString(PyExc_NotImplementedError,
3252 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3253 return NULL;
3254#endif
3255}
3256
Antoine Pitrou152efa22010-05-16 18:19:27 +00003257static PyObject *
3258get_verify_mode(PySSLContext *self, void *c)
3259{
3260 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3261 case SSL_VERIFY_NONE:
3262 return PyLong_FromLong(PY_SSL_CERT_NONE);
3263 case SSL_VERIFY_PEER:
3264 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3265 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3266 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3267 }
3268 PyErr_SetString(PySSLErrorObject,
3269 "invalid return value from SSL_CTX_get_verify_mode");
3270 return NULL;
3271}
3272
3273static int
3274set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3275{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003276 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003277 if (!PyArg_Parse(arg, "i", &n))
3278 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003279 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003280 PyErr_SetString(PyExc_ValueError,
3281 "Cannot set verify_mode to CERT_NONE when "
3282 "check_hostname is enabled.");
3283 return -1;
3284 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003285 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003286}
3287
3288static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003289get_verify_flags(PySSLContext *self, void *c)
3290{
Christian Heimes598894f2016-09-05 23:19:05 +02003291 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003292 unsigned long flags;
3293
Christian Heimes61d478c2018-01-27 15:51:38 +01003294 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003295 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003296 return PyLong_FromUnsignedLong(flags);
3297}
3298
3299static int
3300set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3301{
Christian Heimes598894f2016-09-05 23:19:05 +02003302 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003303 unsigned long new_flags, flags, set, clear;
3304
3305 if (!PyArg_Parse(arg, "k", &new_flags))
3306 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003307 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003308 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003309 clear = flags & ~new_flags;
3310 set = ~flags & new_flags;
3311 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003312 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003313 _setSSLError(NULL, 0, __FILE__, __LINE__);
3314 return -1;
3315 }
3316 }
3317 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003318 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003319 _setSSLError(NULL, 0, __FILE__, __LINE__);
3320 return -1;
3321 }
3322 }
3323 return 0;
3324}
3325
3326static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003327get_options(PySSLContext *self, void *c)
3328{
3329 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3330}
3331
3332static int
3333set_options(PySSLContext *self, PyObject *arg, void *c)
3334{
3335 long new_opts, opts, set, clear;
3336 if (!PyArg_Parse(arg, "l", &new_opts))
3337 return -1;
3338 opts = SSL_CTX_get_options(self->ctx);
3339 clear = opts & ~new_opts;
3340 set = ~opts & new_opts;
3341 if (clear) {
3342#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3343 SSL_CTX_clear_options(self->ctx, clear);
3344#else
3345 PyErr_SetString(PyExc_ValueError,
3346 "can't clear options before OpenSSL 0.9.8m");
3347 return -1;
3348#endif
3349 }
3350 if (set)
3351 SSL_CTX_set_options(self->ctx, set);
3352 return 0;
3353}
3354
Christian Heimes1aa9a752013-12-02 02:41:19 +01003355static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003356get_host_flags(PySSLContext *self, void *c)
3357{
3358 return PyLong_FromUnsignedLong(self->hostflags);
3359}
3360
3361static int
3362set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3363{
3364 X509_VERIFY_PARAM *param;
3365 unsigned int new_flags = 0;
3366
3367 if (!PyArg_Parse(arg, "I", &new_flags))
3368 return -1;
3369
3370 param = SSL_CTX_get0_param(self->ctx);
3371 self->hostflags = new_flags;
3372 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3373 return 0;
3374}
3375
3376static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003377get_check_hostname(PySSLContext *self, void *c)
3378{
3379 return PyBool_FromLong(self->check_hostname);
3380}
3381
3382static int
3383set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3384{
3385 int check_hostname;
3386 if (!PyArg_Parse(arg, "p", &check_hostname))
3387 return -1;
3388 if (check_hostname &&
3389 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003390 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
3391 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
3392 return -1;
3393 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003394 }
3395 self->check_hostname = check_hostname;
3396 return 0;
3397}
3398
Christian Heimes11a14932018-02-24 02:35:08 +01003399static PyObject *
3400get_protocol(PySSLContext *self, void *c) {
3401 return PyLong_FromLong(self->protocol);
3402}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003403
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003404typedef struct {
3405 PyThreadState *thread_state;
3406 PyObject *callable;
3407 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003408 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003409 int error;
3410} _PySSLPasswordInfo;
3411
3412static int
3413_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3414 const char *bad_type_error)
3415{
3416 /* Set the password and size fields of a _PySSLPasswordInfo struct
3417 from a unicode, bytes, or byte array object.
3418 The password field will be dynamically allocated and must be freed
3419 by the caller */
3420 PyObject *password_bytes = NULL;
3421 const char *data = NULL;
3422 Py_ssize_t size;
3423
3424 if (PyUnicode_Check(password)) {
3425 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3426 if (!password_bytes) {
3427 goto error;
3428 }
3429 data = PyBytes_AS_STRING(password_bytes);
3430 size = PyBytes_GET_SIZE(password_bytes);
3431 } else if (PyBytes_Check(password)) {
3432 data = PyBytes_AS_STRING(password);
3433 size = PyBytes_GET_SIZE(password);
3434 } else if (PyByteArray_Check(password)) {
3435 data = PyByteArray_AS_STRING(password);
3436 size = PyByteArray_GET_SIZE(password);
3437 } else {
3438 PyErr_SetString(PyExc_TypeError, bad_type_error);
3439 goto error;
3440 }
3441
Victor Stinner9ee02032013-06-23 15:08:23 +02003442 if (size > (Py_ssize_t)INT_MAX) {
3443 PyErr_Format(PyExc_ValueError,
3444 "password cannot be longer than %d bytes", INT_MAX);
3445 goto error;
3446 }
3447
Victor Stinner11ebff22013-07-07 17:07:52 +02003448 PyMem_Free(pw_info->password);
3449 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003450 if (!pw_info->password) {
3451 PyErr_SetString(PyExc_MemoryError,
3452 "unable to allocate password buffer");
3453 goto error;
3454 }
3455 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003456 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003457
3458 Py_XDECREF(password_bytes);
3459 return 1;
3460
3461error:
3462 Py_XDECREF(password_bytes);
3463 return 0;
3464}
3465
3466static int
3467_password_callback(char *buf, int size, int rwflag, void *userdata)
3468{
3469 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3470 PyObject *fn_ret = NULL;
3471
3472 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3473
3474 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003475 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003476 if (!fn_ret) {
3477 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3478 core python API, so we could use it to add a frame here */
3479 goto error;
3480 }
3481
3482 if (!_pwinfo_set(pw_info, fn_ret,
3483 "password callback must return a string")) {
3484 goto error;
3485 }
3486 Py_CLEAR(fn_ret);
3487 }
3488
3489 if (pw_info->size > size) {
3490 PyErr_Format(PyExc_ValueError,
3491 "password cannot be longer than %d bytes", size);
3492 goto error;
3493 }
3494
3495 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3496 memcpy(buf, pw_info->password, pw_info->size);
3497 return pw_info->size;
3498
3499error:
3500 Py_XDECREF(fn_ret);
3501 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3502 pw_info->error = 1;
3503 return -1;
3504}
3505
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003506/*[clinic input]
3507_ssl._SSLContext.load_cert_chain
3508 certfile: object
3509 keyfile: object = NULL
3510 password: object = NULL
3511
3512[clinic start generated code]*/
3513
Antoine Pitroub5218772010-05-21 09:56:06 +00003514static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003515_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3516 PyObject *keyfile, PyObject *password)
3517/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003518{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003519 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003520 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3521 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003522 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003523 int r;
3524
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003525 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003526 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003527 if (keyfile == Py_None)
3528 keyfile = NULL;
3529 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3530 PyErr_SetString(PyExc_TypeError,
3531 "certfile should be a valid filesystem path");
3532 return NULL;
3533 }
3534 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3535 PyErr_SetString(PyExc_TypeError,
3536 "keyfile should be a valid filesystem path");
3537 goto error;
3538 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003539 if (password && password != Py_None) {
3540 if (PyCallable_Check(password)) {
3541 pw_info.callable = password;
3542 } else if (!_pwinfo_set(&pw_info, password,
3543 "password should be a string or callable")) {
3544 goto error;
3545 }
3546 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3547 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3548 }
3549 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003550 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3551 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003552 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003553 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003554 if (pw_info.error) {
3555 ERR_clear_error();
3556 /* the password callback has already set the error information */
3557 }
3558 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003559 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003560 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003561 }
3562 else {
3563 _setSSLError(NULL, 0, __FILE__, __LINE__);
3564 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003565 goto error;
3566 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003567 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003568 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003569 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3570 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003571 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3572 Py_CLEAR(keyfile_bytes);
3573 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003574 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003575 if (pw_info.error) {
3576 ERR_clear_error();
3577 /* the password callback has already set the error information */
3578 }
3579 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003580 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003581 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003582 }
3583 else {
3584 _setSSLError(NULL, 0, __FILE__, __LINE__);
3585 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003586 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003587 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003588 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003589 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003590 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003591 if (r != 1) {
3592 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003593 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003594 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003595 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3596 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003597 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003598 Py_RETURN_NONE;
3599
3600error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003601 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3602 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003603 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003604 Py_XDECREF(keyfile_bytes);
3605 Py_XDECREF(certfile_bytes);
3606 return NULL;
3607}
3608
Christian Heimesefff7062013-11-21 03:35:02 +01003609/* internal helper function, returns -1 on error
3610 */
3611static int
3612_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3613 int filetype)
3614{
3615 BIO *biobuf = NULL;
3616 X509_STORE *store;
3617 int retval = 0, err, loaded = 0;
3618
3619 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3620
3621 if (len <= 0) {
3622 PyErr_SetString(PyExc_ValueError,
3623 "Empty certificate data");
3624 return -1;
3625 } else if (len > INT_MAX) {
3626 PyErr_SetString(PyExc_OverflowError,
3627 "Certificate data is too long.");
3628 return -1;
3629 }
3630
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003631 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003632 if (biobuf == NULL) {
3633 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3634 return -1;
3635 }
3636
3637 store = SSL_CTX_get_cert_store(self->ctx);
3638 assert(store != NULL);
3639
3640 while (1) {
3641 X509 *cert = NULL;
3642 int r;
3643
3644 if (filetype == SSL_FILETYPE_ASN1) {
3645 cert = d2i_X509_bio(biobuf, NULL);
3646 } else {
3647 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003648 SSL_CTX_get_default_passwd_cb(self->ctx),
3649 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3650 );
Christian Heimesefff7062013-11-21 03:35:02 +01003651 }
3652 if (cert == NULL) {
3653 break;
3654 }
3655 r = X509_STORE_add_cert(store, cert);
3656 X509_free(cert);
3657 if (!r) {
3658 err = ERR_peek_last_error();
3659 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3660 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3661 /* cert already in hash table, not an error */
3662 ERR_clear_error();
3663 } else {
3664 break;
3665 }
3666 }
3667 loaded++;
3668 }
3669
3670 err = ERR_peek_last_error();
3671 if ((filetype == SSL_FILETYPE_ASN1) &&
3672 (loaded > 0) &&
3673 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3674 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3675 /* EOF ASN1 file, not an error */
3676 ERR_clear_error();
3677 retval = 0;
3678 } else if ((filetype == SSL_FILETYPE_PEM) &&
3679 (loaded > 0) &&
3680 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3681 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3682 /* EOF PEM file, not an error */
3683 ERR_clear_error();
3684 retval = 0;
3685 } else {
3686 _setSSLError(NULL, 0, __FILE__, __LINE__);
3687 retval = -1;
3688 }
3689
3690 BIO_free(biobuf);
3691 return retval;
3692}
3693
3694
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003695/*[clinic input]
3696_ssl._SSLContext.load_verify_locations
3697 cafile: object = NULL
3698 capath: object = NULL
3699 cadata: object = NULL
3700
3701[clinic start generated code]*/
3702
Antoine Pitrou152efa22010-05-16 18:19:27 +00003703static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003704_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3705 PyObject *cafile,
3706 PyObject *capath,
3707 PyObject *cadata)
3708/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003709{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003710 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3711 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003712 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003713
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003714 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003715 if (cafile == Py_None)
3716 cafile = NULL;
3717 if (capath == Py_None)
3718 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003719 if (cadata == Py_None)
3720 cadata = NULL;
3721
3722 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003723 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003724 "cafile, capath and cadata cannot be all omitted");
3725 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003726 }
3727 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3728 PyErr_SetString(PyExc_TypeError,
3729 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003730 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003731 }
3732 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003733 PyErr_SetString(PyExc_TypeError,
3734 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003735 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003736 }
Christian Heimesefff7062013-11-21 03:35:02 +01003737
3738 /* validata cadata type and load cadata */
3739 if (cadata) {
3740 Py_buffer buf;
3741 PyObject *cadata_ascii = NULL;
3742
3743 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3744 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3745 PyBuffer_Release(&buf);
3746 PyErr_SetString(PyExc_TypeError,
3747 "cadata should be a contiguous buffer with "
3748 "a single dimension");
3749 goto error;
3750 }
3751 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3752 PyBuffer_Release(&buf);
3753 if (r == -1) {
3754 goto error;
3755 }
3756 } else {
3757 PyErr_Clear();
3758 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3759 if (cadata_ascii == NULL) {
3760 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003761 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003762 "bytes-like object");
3763 goto error;
3764 }
3765 r = _add_ca_certs(self,
3766 PyBytes_AS_STRING(cadata_ascii),
3767 PyBytes_GET_SIZE(cadata_ascii),
3768 SSL_FILETYPE_PEM);
3769 Py_DECREF(cadata_ascii);
3770 if (r == -1) {
3771 goto error;
3772 }
3773 }
3774 }
3775
3776 /* load cafile or capath */
3777 if (cafile || capath) {
3778 if (cafile)
3779 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3780 if (capath)
3781 capath_buf = PyBytes_AS_STRING(capath_bytes);
3782 PySSL_BEGIN_ALLOW_THREADS
3783 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3784 PySSL_END_ALLOW_THREADS
3785 if (r != 1) {
3786 ok = 0;
3787 if (errno != 0) {
3788 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003789 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003790 }
3791 else {
3792 _setSSLError(NULL, 0, __FILE__, __LINE__);
3793 }
3794 goto error;
3795 }
3796 }
3797 goto end;
3798
3799 error:
3800 ok = 0;
3801 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003802 Py_XDECREF(cafile_bytes);
3803 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003804 if (ok) {
3805 Py_RETURN_NONE;
3806 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003807 return NULL;
3808 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003809}
3810
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003811/*[clinic input]
3812_ssl._SSLContext.load_dh_params
3813 path as filepath: object
3814 /
3815
3816[clinic start generated code]*/
3817
Antoine Pitrou152efa22010-05-16 18:19:27 +00003818static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003819_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3820/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003821{
3822 FILE *f;
3823 DH *dh;
3824
Victor Stinnerdaf45552013-08-28 00:53:59 +02003825 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003826 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003827 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003828
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003829 errno = 0;
3830 PySSL_BEGIN_ALLOW_THREADS
3831 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003832 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003833 PySSL_END_ALLOW_THREADS
3834 if (dh == NULL) {
3835 if (errno != 0) {
3836 ERR_clear_error();
3837 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3838 }
3839 else {
3840 _setSSLError(NULL, 0, __FILE__, __LINE__);
3841 }
3842 return NULL;
3843 }
3844 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3845 _setSSLError(NULL, 0, __FILE__, __LINE__);
3846 DH_free(dh);
3847 Py_RETURN_NONE;
3848}
3849
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003850/*[clinic input]
3851_ssl._SSLContext._wrap_socket
3852 sock: object(subclass_of="PySocketModule.Sock_Type")
3853 server_side: int
3854 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01003855 *
3856 owner: object = None
3857 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003858
3859[clinic start generated code]*/
3860
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003861static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003862_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01003863 int server_side, PyObject *hostname_obj,
3864 PyObject *owner, PyObject *session)
3865/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003866{
Antoine Pitroud5323212010-10-22 18:19:07 +00003867 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003868 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003869
Antoine Pitroud5323212010-10-22 18:19:07 +00003870 /* server_hostname is either None (or absent), or to be encoded
Christian Heimes11a14932018-02-24 02:35:08 +01003871 as IDN A-label (ASCII str). */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003872 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01003873 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003874 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003875 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003876
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003877 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3878 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01003879 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003880 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003881 if (hostname != NULL)
3882 PyMem_Free(hostname);
3883 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003884}
3885
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003886/*[clinic input]
3887_ssl._SSLContext._wrap_bio
3888 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3889 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3890 server_side: int
3891 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01003892 *
3893 owner: object = None
3894 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003895
3896[clinic start generated code]*/
3897
Antoine Pitroub0182c82010-10-12 20:09:02 +00003898static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003899_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3900 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01003901 PyObject *hostname_obj, PyObject *owner,
3902 PyObject *session)
3903/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003904{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003905 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003906 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003907
3908 /* server_hostname is either None (or absent), or to be encoded
Christian Heimes11a14932018-02-24 02:35:08 +01003909 as IDN A-label (ASCII str). */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003910 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01003911 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003912 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003913 }
3914
3915 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01003916 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003917 incoming, outgoing);
3918
3919 PyMem_Free(hostname);
3920 return res;
3921}
3922
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003923/*[clinic input]
3924_ssl._SSLContext.session_stats
3925[clinic start generated code]*/
3926
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003927static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003928_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3929/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003930{
3931 int r;
3932 PyObject *value, *stats = PyDict_New();
3933 if (!stats)
3934 return NULL;
3935
3936#define ADD_STATS(SSL_NAME, KEY_NAME) \
3937 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3938 if (value == NULL) \
3939 goto error; \
3940 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3941 Py_DECREF(value); \
3942 if (r < 0) \
3943 goto error;
3944
3945 ADD_STATS(number, "number");
3946 ADD_STATS(connect, "connect");
3947 ADD_STATS(connect_good, "connect_good");
3948 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3949 ADD_STATS(accept, "accept");
3950 ADD_STATS(accept_good, "accept_good");
3951 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3952 ADD_STATS(accept, "accept");
3953 ADD_STATS(hits, "hits");
3954 ADD_STATS(misses, "misses");
3955 ADD_STATS(timeouts, "timeouts");
3956 ADD_STATS(cache_full, "cache_full");
3957
3958#undef ADD_STATS
3959
3960 return stats;
3961
3962error:
3963 Py_DECREF(stats);
3964 return NULL;
3965}
3966
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003967/*[clinic input]
3968_ssl._SSLContext.set_default_verify_paths
3969[clinic start generated code]*/
3970
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003971static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003972_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3973/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003974{
3975 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3976 _setSSLError(NULL, 0, __FILE__, __LINE__);
3977 return NULL;
3978 }
3979 Py_RETURN_NONE;
3980}
3981
Antoine Pitrou501da612011-12-21 09:27:41 +01003982#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003983/*[clinic input]
3984_ssl._SSLContext.set_ecdh_curve
3985 name: object
3986 /
3987
3988[clinic start generated code]*/
3989
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003990static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003991_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3992/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003993{
3994 PyObject *name_bytes;
3995 int nid;
3996 EC_KEY *key;
3997
3998 if (!PyUnicode_FSConverter(name, &name_bytes))
3999 return NULL;
4000 assert(PyBytes_Check(name_bytes));
4001 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4002 Py_DECREF(name_bytes);
4003 if (nid == 0) {
4004 PyErr_Format(PyExc_ValueError,
4005 "unknown elliptic curve name %R", name);
4006 return NULL;
4007 }
4008 key = EC_KEY_new_by_curve_name(nid);
4009 if (key == NULL) {
4010 _setSSLError(NULL, 0, __FILE__, __LINE__);
4011 return NULL;
4012 }
4013 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4014 EC_KEY_free(key);
4015 Py_RETURN_NONE;
4016}
Antoine Pitrou501da612011-12-21 09:27:41 +01004017#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004018
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004019#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004020static int
4021_servername_callback(SSL *s, int *al, void *args)
4022{
4023 int ret;
4024 PySSLContext *ssl_ctx = (PySSLContext *) args;
4025 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004026 PyObject *result;
4027 /* The high-level ssl.SSLSocket object */
4028 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004029 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004030 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004031
Christian Heimes11a14932018-02-24 02:35:08 +01004032 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004033 /* remove race condition in this the call back while if removing the
4034 * callback is in progress */
4035 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004036 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004037 }
4038
4039 ssl = SSL_get_app_data(s);
4040 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004041
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004042 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004043 * SSL connection and that has a .context attribute that can be changed to
4044 * identify the requested hostname. Since the official API is the Python
4045 * level API we want to pass the callback a Python level object rather than
4046 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4047 * SSLObject) that will be passed. Otherwise if there's a socket then that
4048 * will be passed. If both do not exist only then the C-level object is
4049 * passed. */
4050 if (ssl->owner)
4051 ssl_socket = PyWeakref_GetObject(ssl->owner);
4052 else if (ssl->Socket)
4053 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4054 else
4055 ssl_socket = (PyObject *) ssl;
4056
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004057 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004058 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004059 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004060
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004061 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004062 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004063 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004064 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004065 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004066 PyObject *servername_bytes;
4067 PyObject *servername_str;
4068
4069 servername_bytes = PyBytes_FromString(servername);
4070 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004071 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4072 goto error;
4073 }
Christian Heimes11a14932018-02-24 02:35:08 +01004074 /* server_hostname was encoded to an A-label by our caller; put it
4075 * back into a str object, but still as an A-label (bpo-28414)
4076 */
4077 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4078 Py_DECREF(servername_bytes);
4079 if (servername_str == NULL) {
4080 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004081 goto error;
4082 }
Christian Heimes11a14932018-02-24 02:35:08 +01004083 result = PyObject_CallFunctionObjArgs(
4084 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4085 ssl_ctx, NULL);
4086 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004087 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004088 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004089
4090 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004091 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004092 *al = SSL_AD_HANDSHAKE_FAILURE;
4093 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4094 }
4095 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004096 /* Result may be None, a SSLContext or an integer
4097 * None and SSLContext are OK, integer or other values are an error.
4098 */
4099 if (result == Py_None) {
4100 ret = SSL_TLSEXT_ERR_OK;
4101 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004102 *al = (int) PyLong_AsLong(result);
4103 if (PyErr_Occurred()) {
4104 PyErr_WriteUnraisable(result);
4105 *al = SSL_AD_INTERNAL_ERROR;
4106 }
4107 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4108 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004109 Py_DECREF(result);
4110 }
4111
4112 PyGILState_Release(gstate);
4113 return ret;
4114
4115error:
4116 Py_DECREF(ssl_socket);
4117 *al = SSL_AD_INTERNAL_ERROR;
4118 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4119 PyGILState_Release(gstate);
4120 return ret;
4121}
Antoine Pitroua5963382013-03-30 16:39:00 +01004122#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004123
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004124static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004125get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004126{
Christian Heimes11a14932018-02-24 02:35:08 +01004127 PyObject *cb = self->set_sni_cb;
4128 if (cb == NULL) {
4129 Py_RETURN_NONE;
4130 }
4131 Py_INCREF(cb);
4132 return cb;
4133}
4134
4135static int
4136set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4137{
4138 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4139 PyErr_SetString(PyExc_ValueError,
4140 "sni_callback cannot be set on TLS_CLIENT context");
4141 return -1;
4142 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004143#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004144 Py_CLEAR(self->set_sni_cb);
4145 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004146 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4147 }
4148 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004149 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004150 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4151 PyErr_SetString(PyExc_TypeError,
4152 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004153 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004154 }
Christian Heimes11a14932018-02-24 02:35:08 +01004155 Py_INCREF(arg);
4156 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004157 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4158 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4159 }
Christian Heimes11a14932018-02-24 02:35:08 +01004160 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004161#else
4162 PyErr_SetString(PyExc_NotImplementedError,
4163 "The TLS extension servername callback, "
4164 "SSL_CTX_set_tlsext_servername_callback, "
4165 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004166 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004167#endif
4168}
4169
Christian Heimes11a14932018-02-24 02:35:08 +01004170PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4171"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4172\n\
4173If the argument is None then the callback is disabled. The method is called\n\
4174with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4175See RFC 6066 for details of the SNI extension.");
4176
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004177/*[clinic input]
4178_ssl._SSLContext.cert_store_stats
4179
4180Returns quantities of loaded X.509 certificates.
4181
4182X.509 certificates with a CA extension and certificate revocation lists
4183inside the context's cert store.
4184
4185NOTE: Certificates in a capath directory aren't loaded unless they have
4186been used at least once.
4187[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004188
4189static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004190_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4191/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004192{
4193 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004194 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004195 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004196 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004197
4198 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004199 objs = X509_STORE_get0_objects(store);
4200 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4201 obj = sk_X509_OBJECT_value(objs, i);
4202 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004203 case X509_LU_X509:
4204 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004205 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004206 ca++;
4207 }
4208 break;
4209 case X509_LU_CRL:
4210 crl++;
4211 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004212 default:
4213 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4214 * As far as I can tell they are internal states and never
4215 * stored in a cert store */
4216 break;
4217 }
4218 }
4219 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4220 "x509_ca", ca);
4221}
4222
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004223/*[clinic input]
4224_ssl._SSLContext.get_ca_certs
4225 binary_form: bool = False
4226
4227Returns a list of dicts with information of loaded CA certs.
4228
4229If the optional argument is True, returns a DER-encoded copy of the CA
4230certificate.
4231
4232NOTE: Certificates in a capath directory aren't loaded unless they have
4233been used at least once.
4234[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004235
4236static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004237_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4238/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004239{
4240 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004241 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004242 PyObject *ci = NULL, *rlist = NULL;
4243 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004244
4245 if ((rlist = PyList_New(0)) == NULL) {
4246 return NULL;
4247 }
4248
4249 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004250 objs = X509_STORE_get0_objects(store);
4251 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004252 X509_OBJECT *obj;
4253 X509 *cert;
4254
Christian Heimes598894f2016-09-05 23:19:05 +02004255 obj = sk_X509_OBJECT_value(objs, i);
4256 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004257 /* not a x509 cert */
4258 continue;
4259 }
4260 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004261 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004262 if (!X509_check_ca(cert)) {
4263 continue;
4264 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004265 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004266 ci = _certificate_to_der(cert);
4267 } else {
4268 ci = _decode_certificate(cert);
4269 }
4270 if (ci == NULL) {
4271 goto error;
4272 }
4273 if (PyList_Append(rlist, ci) == -1) {
4274 goto error;
4275 }
4276 Py_CLEAR(ci);
4277 }
4278 return rlist;
4279
4280 error:
4281 Py_XDECREF(ci);
4282 Py_XDECREF(rlist);
4283 return NULL;
4284}
4285
4286
Antoine Pitrou152efa22010-05-16 18:19:27 +00004287static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004288 {"check_hostname", (getter) get_check_hostname,
4289 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004290 {"_host_flags", (getter) get_host_flags,
4291 (setter) set_host_flags, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004292 {"sni_callback", (getter) get_sni_callback,
4293 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004294 {"options", (getter) get_options,
4295 (setter) set_options, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004296 {"protocol", (getter) get_protocol,
4297 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004298 {"verify_flags", (getter) get_verify_flags,
4299 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004300 {"verify_mode", (getter) get_verify_mode,
4301 (setter) set_verify_mode, NULL},
4302 {NULL}, /* sentinel */
4303};
4304
4305static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004306 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4307 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4308 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4309 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4310 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4311 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4312 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4313 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4314 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4315 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4316 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004317 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4318 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004319 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004320 {NULL, NULL} /* sentinel */
4321};
4322
4323static PyTypeObject PySSLContext_Type = {
4324 PyVarObject_HEAD_INIT(NULL, 0)
4325 "_ssl._SSLContext", /*tp_name*/
4326 sizeof(PySSLContext), /*tp_basicsize*/
4327 0, /*tp_itemsize*/
4328 (destructor)context_dealloc, /*tp_dealloc*/
4329 0, /*tp_print*/
4330 0, /*tp_getattr*/
4331 0, /*tp_setattr*/
4332 0, /*tp_reserved*/
4333 0, /*tp_repr*/
4334 0, /*tp_as_number*/
4335 0, /*tp_as_sequence*/
4336 0, /*tp_as_mapping*/
4337 0, /*tp_hash*/
4338 0, /*tp_call*/
4339 0, /*tp_str*/
4340 0, /*tp_getattro*/
4341 0, /*tp_setattro*/
4342 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004343 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004344 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004345 (traverseproc) context_traverse, /*tp_traverse*/
4346 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004347 0, /*tp_richcompare*/
4348 0, /*tp_weaklistoffset*/
4349 0, /*tp_iter*/
4350 0, /*tp_iternext*/
4351 context_methods, /*tp_methods*/
4352 0, /*tp_members*/
4353 context_getsetlist, /*tp_getset*/
4354 0, /*tp_base*/
4355 0, /*tp_dict*/
4356 0, /*tp_descr_get*/
4357 0, /*tp_descr_set*/
4358 0, /*tp_dictoffset*/
4359 0, /*tp_init*/
4360 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004361 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004362};
4363
4364
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004365/*
4366 * MemoryBIO objects
4367 */
4368
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004369/*[clinic input]
4370@classmethod
4371_ssl.MemoryBIO.__new__
4372
4373[clinic start generated code]*/
4374
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004375static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004376_ssl_MemoryBIO_impl(PyTypeObject *type)
4377/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004378{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004379 BIO *bio;
4380 PySSLMemoryBIO *self;
4381
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004382 bio = BIO_new(BIO_s_mem());
4383 if (bio == NULL) {
4384 PyErr_SetString(PySSLErrorObject,
4385 "failed to allocate BIO");
4386 return NULL;
4387 }
4388 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4389 * just that no data is currently available. The SSL routines should retry
4390 * the read, which we can achieve by calling BIO_set_retry_read(). */
4391 BIO_set_retry_read(bio);
4392 BIO_set_mem_eof_return(bio, -1);
4393
4394 assert(type != NULL && type->tp_alloc != NULL);
4395 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4396 if (self == NULL) {
4397 BIO_free(bio);
4398 return NULL;
4399 }
4400 self->bio = bio;
4401 self->eof_written = 0;
4402
4403 return (PyObject *) self;
4404}
4405
4406static void
4407memory_bio_dealloc(PySSLMemoryBIO *self)
4408{
4409 BIO_free(self->bio);
4410 Py_TYPE(self)->tp_free(self);
4411}
4412
4413static PyObject *
4414memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4415{
Segev Finer5cff6372017-07-27 01:19:17 +03004416 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004417}
4418
4419PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4420"The number of bytes pending in the memory BIO.");
4421
4422static PyObject *
4423memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4424{
4425 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4426 && self->eof_written);
4427}
4428
4429PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4430"Whether the memory BIO is at EOF.");
4431
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004432/*[clinic input]
4433_ssl.MemoryBIO.read
4434 size as len: int = -1
4435 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004436
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004437Read up to size bytes from the memory BIO.
4438
4439If size is not specified, read the entire buffer.
4440If the return value is an empty bytes instance, this means either
4441EOF or that no data is available. Use the "eof" property to
4442distinguish between the two.
4443[clinic start generated code]*/
4444
4445static PyObject *
4446_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4447/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4448{
4449 int avail, nbytes;
4450 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004451
Segev Finer5cff6372017-07-27 01:19:17 +03004452 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004453 if ((len < 0) || (len > avail))
4454 len = avail;
4455
4456 result = PyBytes_FromStringAndSize(NULL, len);
4457 if ((result == NULL) || (len == 0))
4458 return result;
4459
4460 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4461 /* There should never be any short reads but check anyway. */
4462 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4463 Py_DECREF(result);
4464 return NULL;
4465 }
4466
4467 return result;
4468}
4469
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004470/*[clinic input]
4471_ssl.MemoryBIO.write
4472 b: Py_buffer
4473 /
4474
4475Writes the bytes b into the memory BIO.
4476
4477Returns the number of bytes written.
4478[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004479
4480static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004481_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4482/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004483{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004484 int nbytes;
4485
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004486 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004487 PyErr_Format(PyExc_OverflowError,
4488 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004489 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004490 }
4491
4492 if (self->eof_written) {
4493 PyErr_SetString(PySSLErrorObject,
4494 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004495 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004496 }
4497
Segev Finer5cff6372017-07-27 01:19:17 +03004498 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004499 if (nbytes < 0) {
4500 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004501 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004502 }
4503
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004504 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004505}
4506
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004507/*[clinic input]
4508_ssl.MemoryBIO.write_eof
4509
4510Write an EOF marker to the memory BIO.
4511
4512When all data has been read, the "eof" property will be True.
4513[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004514
4515static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004516_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4517/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004518{
4519 self->eof_written = 1;
4520 /* After an EOF is written, a zero return from read() should be a real EOF
4521 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4522 BIO_clear_retry_flags(self->bio);
4523 BIO_set_mem_eof_return(self->bio, 0);
4524
4525 Py_RETURN_NONE;
4526}
4527
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004528static PyGetSetDef memory_bio_getsetlist[] = {
4529 {"pending", (getter) memory_bio_get_pending, NULL,
4530 PySSL_memory_bio_pending_doc},
4531 {"eof", (getter) memory_bio_get_eof, NULL,
4532 PySSL_memory_bio_eof_doc},
4533 {NULL}, /* sentinel */
4534};
4535
4536static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004537 _SSL_MEMORYBIO_READ_METHODDEF
4538 _SSL_MEMORYBIO_WRITE_METHODDEF
4539 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004540 {NULL, NULL} /* sentinel */
4541};
4542
4543static PyTypeObject PySSLMemoryBIO_Type = {
4544 PyVarObject_HEAD_INIT(NULL, 0)
4545 "_ssl.MemoryBIO", /*tp_name*/
4546 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4547 0, /*tp_itemsize*/
4548 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4549 0, /*tp_print*/
4550 0, /*tp_getattr*/
4551 0, /*tp_setattr*/
4552 0, /*tp_reserved*/
4553 0, /*tp_repr*/
4554 0, /*tp_as_number*/
4555 0, /*tp_as_sequence*/
4556 0, /*tp_as_mapping*/
4557 0, /*tp_hash*/
4558 0, /*tp_call*/
4559 0, /*tp_str*/
4560 0, /*tp_getattro*/
4561 0, /*tp_setattro*/
4562 0, /*tp_as_buffer*/
4563 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4564 0, /*tp_doc*/
4565 0, /*tp_traverse*/
4566 0, /*tp_clear*/
4567 0, /*tp_richcompare*/
4568 0, /*tp_weaklistoffset*/
4569 0, /*tp_iter*/
4570 0, /*tp_iternext*/
4571 memory_bio_methods, /*tp_methods*/
4572 0, /*tp_members*/
4573 memory_bio_getsetlist, /*tp_getset*/
4574 0, /*tp_base*/
4575 0, /*tp_dict*/
4576 0, /*tp_descr_get*/
4577 0, /*tp_descr_set*/
4578 0, /*tp_dictoffset*/
4579 0, /*tp_init*/
4580 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004581 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004582};
4583
Antoine Pitrou152efa22010-05-16 18:19:27 +00004584
Christian Heimes99a65702016-09-10 23:44:53 +02004585/*
4586 * SSL Session object
4587 */
4588
4589static void
4590PySSLSession_dealloc(PySSLSession *self)
4591{
INADA Naokia6296d32017-08-24 14:55:17 +09004592 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004593 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004594 Py_XDECREF(self->ctx);
4595 if (self->session != NULL) {
4596 SSL_SESSION_free(self->session);
4597 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004598 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004599}
4600
4601static PyObject *
4602PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4603{
4604 int result;
4605
4606 if (left == NULL || right == NULL) {
4607 PyErr_BadInternalCall();
4608 return NULL;
4609 }
4610
4611 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4612 Py_RETURN_NOTIMPLEMENTED;
4613 }
4614
4615 if (left == right) {
4616 result = 0;
4617 } else {
4618 const unsigned char *left_id, *right_id;
4619 unsigned int left_len, right_len;
4620 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4621 &left_len);
4622 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4623 &right_len);
4624 if (left_len == right_len) {
4625 result = memcmp(left_id, right_id, left_len);
4626 } else {
4627 result = 1;
4628 }
4629 }
4630
4631 switch (op) {
4632 case Py_EQ:
4633 if (result == 0) {
4634 Py_RETURN_TRUE;
4635 } else {
4636 Py_RETURN_FALSE;
4637 }
4638 break;
4639 case Py_NE:
4640 if (result != 0) {
4641 Py_RETURN_TRUE;
4642 } else {
4643 Py_RETURN_FALSE;
4644 }
4645 break;
4646 case Py_LT:
4647 case Py_LE:
4648 case Py_GT:
4649 case Py_GE:
4650 Py_RETURN_NOTIMPLEMENTED;
4651 break;
4652 default:
4653 PyErr_BadArgument();
4654 return NULL;
4655 }
4656}
4657
4658static int
4659PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4660{
4661 Py_VISIT(self->ctx);
4662 return 0;
4663}
4664
4665static int
4666PySSLSession_clear(PySSLSession *self)
4667{
4668 Py_CLEAR(self->ctx);
4669 return 0;
4670}
4671
4672
4673static PyObject *
4674PySSLSession_get_time(PySSLSession *self, void *closure) {
4675 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4676}
4677
4678PyDoc_STRVAR(PySSLSession_get_time_doc,
4679"Session creation time (seconds since epoch).");
4680
4681
4682static PyObject *
4683PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4684 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4685}
4686
4687PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4688"Session timeout (delta in seconds).");
4689
4690
4691static PyObject *
4692PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4693 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4694 return PyLong_FromUnsignedLong(hint);
4695}
4696
4697PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4698"Ticket life time hint.");
4699
4700
4701static PyObject *
4702PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4703 const unsigned char *id;
4704 unsigned int len;
4705 id = SSL_SESSION_get_id(self->session, &len);
4706 return PyBytes_FromStringAndSize((const char *)id, len);
4707}
4708
4709PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4710"Session id");
4711
4712
4713static PyObject *
4714PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4715 if (SSL_SESSION_has_ticket(self->session)) {
4716 Py_RETURN_TRUE;
4717 } else {
4718 Py_RETURN_FALSE;
4719 }
4720}
4721
4722PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4723"Does the session contain a ticket?");
4724
4725
4726static PyGetSetDef PySSLSession_getsetlist[] = {
4727 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4728 PySSLSession_get_has_ticket_doc},
4729 {"id", (getter) PySSLSession_get_session_id, NULL,
4730 PySSLSession_get_session_id_doc},
4731 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4732 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4733 {"time", (getter) PySSLSession_get_time, NULL,
4734 PySSLSession_get_time_doc},
4735 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4736 PySSLSession_get_timeout_doc},
4737 {NULL}, /* sentinel */
4738};
4739
4740static PyTypeObject PySSLSession_Type = {
4741 PyVarObject_HEAD_INIT(NULL, 0)
4742 "_ssl.Session", /*tp_name*/
4743 sizeof(PySSLSession), /*tp_basicsize*/
4744 0, /*tp_itemsize*/
4745 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4746 0, /*tp_print*/
4747 0, /*tp_getattr*/
4748 0, /*tp_setattr*/
4749 0, /*tp_reserved*/
4750 0, /*tp_repr*/
4751 0, /*tp_as_number*/
4752 0, /*tp_as_sequence*/
4753 0, /*tp_as_mapping*/
4754 0, /*tp_hash*/
4755 0, /*tp_call*/
4756 0, /*tp_str*/
4757 0, /*tp_getattro*/
4758 0, /*tp_setattro*/
4759 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004760 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004761 0, /*tp_doc*/
4762 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4763 (inquiry)PySSLSession_clear, /*tp_clear*/
4764 PySSLSession_richcompare, /*tp_richcompare*/
4765 0, /*tp_weaklistoffset*/
4766 0, /*tp_iter*/
4767 0, /*tp_iternext*/
4768 0, /*tp_methods*/
4769 0, /*tp_members*/
4770 PySSLSession_getsetlist, /*tp_getset*/
4771};
4772
4773
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004774/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004775/*[clinic input]
4776_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004777 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004778 entropy: double
4779 /
4780
4781Mix string into the OpenSSL PRNG state.
4782
4783entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304784string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004785[clinic start generated code]*/
4786
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004787static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004788_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004789/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004790{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004791 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004792 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004793
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004794 buf = (const char *)view->buf;
4795 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004796 do {
4797 written = Py_MIN(len, INT_MAX);
4798 RAND_add(buf, (int)written, entropy);
4799 buf += written;
4800 len -= written;
4801 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004802 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004803}
4804
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004805static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004806PySSL_RAND(int len, int pseudo)
4807{
4808 int ok;
4809 PyObject *bytes;
4810 unsigned long err;
4811 const char *errstr;
4812 PyObject *v;
4813
Victor Stinner1e81a392013-12-19 16:47:04 +01004814 if (len < 0) {
4815 PyErr_SetString(PyExc_ValueError, "num must be positive");
4816 return NULL;
4817 }
4818
Victor Stinner99c8b162011-05-24 12:05:19 +02004819 bytes = PyBytes_FromStringAndSize(NULL, len);
4820 if (bytes == NULL)
4821 return NULL;
4822 if (pseudo) {
4823 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4824 if (ok == 0 || ok == 1)
4825 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4826 }
4827 else {
4828 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4829 if (ok == 1)
4830 return bytes;
4831 }
4832 Py_DECREF(bytes);
4833
4834 err = ERR_get_error();
4835 errstr = ERR_reason_error_string(err);
4836 v = Py_BuildValue("(ks)", err, errstr);
4837 if (v != NULL) {
4838 PyErr_SetObject(PySSLErrorObject, v);
4839 Py_DECREF(v);
4840 }
4841 return NULL;
4842}
4843
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004844/*[clinic input]
4845_ssl.RAND_bytes
4846 n: int
4847 /
4848
4849Generate n cryptographically strong pseudo-random bytes.
4850[clinic start generated code]*/
4851
Victor Stinner99c8b162011-05-24 12:05:19 +02004852static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004853_ssl_RAND_bytes_impl(PyObject *module, int n)
4854/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004855{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004856 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004857}
4858
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004859/*[clinic input]
4860_ssl.RAND_pseudo_bytes
4861 n: int
4862 /
4863
4864Generate n pseudo-random bytes.
4865
4866Return a pair (bytes, is_cryptographic). is_cryptographic is True
4867if the bytes generated are cryptographically strong.
4868[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004869
4870static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004871_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4872/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004873{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004874 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004875}
4876
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004877/*[clinic input]
4878_ssl.RAND_status
4879
4880Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4881
4882It is necessary to seed the PRNG with RAND_add() on some platforms before
4883using the ssl() function.
4884[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004885
4886static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004887_ssl_RAND_status_impl(PyObject *module)
4888/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004889{
Christian Heimes217cfd12007-12-02 14:31:20 +00004890 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004891}
4892
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004893#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004894/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004895/*[clinic input]
4896_ssl.RAND_egd
4897 path: object(converter="PyUnicode_FSConverter")
4898 /
4899
4900Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4901
4902Returns number of bytes read. Raises SSLError if connection to EGD
4903fails or if it does not provide enough data to seed PRNG.
4904[clinic start generated code]*/
4905
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004906static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004907_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4908/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004909{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004910 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004911 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004912 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004913 PyErr_SetString(PySSLErrorObject,
4914 "EGD connection failed or EGD did not return "
4915 "enough data to seed the PRNG");
4916 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004917 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004918 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004919}
Christian Heimesa5d07652016-09-24 10:48:05 +02004920/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004921#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004922
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004923
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004924
4925/*[clinic input]
4926_ssl.get_default_verify_paths
4927
4928Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4929
4930The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4931[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004932
4933static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004934_ssl_get_default_verify_paths_impl(PyObject *module)
4935/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004936{
4937 PyObject *ofile_env = NULL;
4938 PyObject *ofile = NULL;
4939 PyObject *odir_env = NULL;
4940 PyObject *odir = NULL;
4941
Benjamin Petersond113c962015-07-18 10:59:13 -07004942#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004943 const char *tmp = (info); \
4944 target = NULL; \
4945 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4946 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4947 target = PyBytes_FromString(tmp); } \
4948 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004949 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004950
Benjamin Petersond113c962015-07-18 10:59:13 -07004951 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4952 CONVERT(X509_get_default_cert_file(), ofile);
4953 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4954 CONVERT(X509_get_default_cert_dir(), odir);
4955#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004956
Christian Heimes200bb1b2013-06-14 15:14:29 +02004957 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004958
4959 error:
4960 Py_XDECREF(ofile_env);
4961 Py_XDECREF(ofile);
4962 Py_XDECREF(odir_env);
4963 Py_XDECREF(odir);
4964 return NULL;
4965}
4966
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004967static PyObject*
4968asn1obj2py(ASN1_OBJECT *obj)
4969{
4970 int nid;
4971 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004972
4973 nid = OBJ_obj2nid(obj);
4974 if (nid == NID_undef) {
4975 PyErr_Format(PyExc_ValueError, "Unknown object");
4976 return NULL;
4977 }
4978 sn = OBJ_nid2sn(nid);
4979 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03004980 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004981}
4982
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004983/*[clinic input]
4984_ssl.txt2obj
4985 txt: str
4986 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004987
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004988Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4989
4990By default objects are looked up by OID. With name=True short and
4991long name are also matched.
4992[clinic start generated code]*/
4993
4994static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004995_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4996/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004997{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004998 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004999 ASN1_OBJECT *obj;
5000
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005001 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5002 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005003 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005004 return NULL;
5005 }
5006 result = asn1obj2py(obj);
5007 ASN1_OBJECT_free(obj);
5008 return result;
5009}
5010
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005011/*[clinic input]
5012_ssl.nid2obj
5013 nid: int
5014 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005015
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005016Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5017[clinic start generated code]*/
5018
5019static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005020_ssl_nid2obj_impl(PyObject *module, int nid)
5021/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005022{
5023 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005024 ASN1_OBJECT *obj;
5025
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005026 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005027 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005028 return NULL;
5029 }
5030 obj = OBJ_nid2obj(nid);
5031 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005032 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005033 return NULL;
5034 }
5035 result = asn1obj2py(obj);
5036 ASN1_OBJECT_free(obj);
5037 return result;
5038}
5039
Christian Heimes46bebee2013-06-09 19:03:31 +02005040#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005041
5042static PyObject*
5043certEncodingType(DWORD encodingType)
5044{
5045 static PyObject *x509_asn = NULL;
5046 static PyObject *pkcs_7_asn = NULL;
5047
5048 if (x509_asn == NULL) {
5049 x509_asn = PyUnicode_InternFromString("x509_asn");
5050 if (x509_asn == NULL)
5051 return NULL;
5052 }
5053 if (pkcs_7_asn == NULL) {
5054 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5055 if (pkcs_7_asn == NULL)
5056 return NULL;
5057 }
5058 switch(encodingType) {
5059 case X509_ASN_ENCODING:
5060 Py_INCREF(x509_asn);
5061 return x509_asn;
5062 case PKCS_7_ASN_ENCODING:
5063 Py_INCREF(pkcs_7_asn);
5064 return pkcs_7_asn;
5065 default:
5066 return PyLong_FromLong(encodingType);
5067 }
5068}
5069
5070static PyObject*
5071parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5072{
5073 CERT_ENHKEY_USAGE *usage;
5074 DWORD size, error, i;
5075 PyObject *retval;
5076
5077 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5078 error = GetLastError();
5079 if (error == CRYPT_E_NOT_FOUND) {
5080 Py_RETURN_TRUE;
5081 }
5082 return PyErr_SetFromWindowsErr(error);
5083 }
5084
5085 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5086 if (usage == NULL) {
5087 return PyErr_NoMemory();
5088 }
5089
5090 /* Now get the actual enhanced usage property */
5091 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5092 PyMem_Free(usage);
5093 error = GetLastError();
5094 if (error == CRYPT_E_NOT_FOUND) {
5095 Py_RETURN_TRUE;
5096 }
5097 return PyErr_SetFromWindowsErr(error);
5098 }
5099 retval = PySet_New(NULL);
5100 if (retval == NULL) {
5101 goto error;
5102 }
5103 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5104 if (usage->rgpszUsageIdentifier[i]) {
5105 PyObject *oid;
5106 int err;
5107 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5108 if (oid == NULL) {
5109 Py_CLEAR(retval);
5110 goto error;
5111 }
5112 err = PySet_Add(retval, oid);
5113 Py_DECREF(oid);
5114 if (err == -1) {
5115 Py_CLEAR(retval);
5116 goto error;
5117 }
5118 }
5119 }
5120 error:
5121 PyMem_Free(usage);
5122 return retval;
5123}
5124
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005125/*[clinic input]
5126_ssl.enum_certificates
5127 store_name: str
5128
5129Retrieve certificates from Windows' cert store.
5130
5131store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5132more cert storages, too. The function returns a list of (bytes,
5133encoding_type, trust) tuples. The encoding_type flag can be interpreted
5134with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5135a set of OIDs or the boolean True.
5136[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005137
Christian Heimes46bebee2013-06-09 19:03:31 +02005138static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005139_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5140/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005141{
Christian Heimes46bebee2013-06-09 19:03:31 +02005142 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005143 PCCERT_CONTEXT pCertCtx = NULL;
5144 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005145 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005146
Christian Heimes44109d72013-11-22 01:51:30 +01005147 result = PyList_New(0);
5148 if (result == NULL) {
5149 return NULL;
5150 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005151 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5152 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5153 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005154 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005155 Py_DECREF(result);
5156 return PyErr_SetFromWindowsErr(GetLastError());
5157 }
5158
Christian Heimes44109d72013-11-22 01:51:30 +01005159 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5160 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5161 pCertCtx->cbCertEncoded);
5162 if (!cert) {
5163 Py_CLEAR(result);
5164 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005165 }
Christian Heimes44109d72013-11-22 01:51:30 +01005166 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5167 Py_CLEAR(result);
5168 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005169 }
Christian Heimes44109d72013-11-22 01:51:30 +01005170 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5171 if (keyusage == Py_True) {
5172 Py_DECREF(keyusage);
5173 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005174 }
Christian Heimes44109d72013-11-22 01:51:30 +01005175 if (keyusage == NULL) {
5176 Py_CLEAR(result);
5177 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005178 }
Christian Heimes44109d72013-11-22 01:51:30 +01005179 if ((tup = PyTuple_New(3)) == NULL) {
5180 Py_CLEAR(result);
5181 break;
5182 }
5183 PyTuple_SET_ITEM(tup, 0, cert);
5184 cert = NULL;
5185 PyTuple_SET_ITEM(tup, 1, enc);
5186 enc = NULL;
5187 PyTuple_SET_ITEM(tup, 2, keyusage);
5188 keyusage = NULL;
5189 if (PyList_Append(result, tup) < 0) {
5190 Py_CLEAR(result);
5191 break;
5192 }
5193 Py_CLEAR(tup);
5194 }
5195 if (pCertCtx) {
5196 /* loop ended with an error, need to clean up context manually */
5197 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005198 }
5199
5200 /* In error cases cert, enc and tup may not be NULL */
5201 Py_XDECREF(cert);
5202 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005203 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005204 Py_XDECREF(tup);
5205
5206 if (!CertCloseStore(hStore, 0)) {
5207 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005208 Py_XDECREF(result);
5209 return PyErr_SetFromWindowsErr(GetLastError());
5210 }
5211 return result;
5212}
5213
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005214/*[clinic input]
5215_ssl.enum_crls
5216 store_name: str
5217
5218Retrieve CRLs from Windows' cert store.
5219
5220store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5221more cert storages, too. The function returns a list of (bytes,
5222encoding_type) tuples. The encoding_type flag can be interpreted with
5223X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5224[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005225
5226static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005227_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5228/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005229{
Christian Heimes44109d72013-11-22 01:51:30 +01005230 HCERTSTORE hStore = NULL;
5231 PCCRL_CONTEXT pCrlCtx = NULL;
5232 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5233 PyObject *result = NULL;
5234
Christian Heimes44109d72013-11-22 01:51:30 +01005235 result = PyList_New(0);
5236 if (result == NULL) {
5237 return NULL;
5238 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005239 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5240 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5241 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005242 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005243 Py_DECREF(result);
5244 return PyErr_SetFromWindowsErr(GetLastError());
5245 }
Christian Heimes44109d72013-11-22 01:51:30 +01005246
5247 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5248 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5249 pCrlCtx->cbCrlEncoded);
5250 if (!crl) {
5251 Py_CLEAR(result);
5252 break;
5253 }
5254 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5255 Py_CLEAR(result);
5256 break;
5257 }
5258 if ((tup = PyTuple_New(2)) == NULL) {
5259 Py_CLEAR(result);
5260 break;
5261 }
5262 PyTuple_SET_ITEM(tup, 0, crl);
5263 crl = NULL;
5264 PyTuple_SET_ITEM(tup, 1, enc);
5265 enc = NULL;
5266
5267 if (PyList_Append(result, tup) < 0) {
5268 Py_CLEAR(result);
5269 break;
5270 }
5271 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005272 }
Christian Heimes44109d72013-11-22 01:51:30 +01005273 if (pCrlCtx) {
5274 /* loop ended with an error, need to clean up context manually */
5275 CertFreeCRLContext(pCrlCtx);
5276 }
5277
5278 /* In error cases cert, enc and tup may not be NULL */
5279 Py_XDECREF(crl);
5280 Py_XDECREF(enc);
5281 Py_XDECREF(tup);
5282
5283 if (!CertCloseStore(hStore, 0)) {
5284 /* This error case might shadow another exception.*/
5285 Py_XDECREF(result);
5286 return PyErr_SetFromWindowsErr(GetLastError());
5287 }
5288 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005289}
Christian Heimes44109d72013-11-22 01:51:30 +01005290
5291#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005292
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005293/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005294static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005295 _SSL__TEST_DECODE_CERT_METHODDEF
5296 _SSL_RAND_ADD_METHODDEF
5297 _SSL_RAND_BYTES_METHODDEF
5298 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5299 _SSL_RAND_EGD_METHODDEF
5300 _SSL_RAND_STATUS_METHODDEF
5301 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5302 _SSL_ENUM_CERTIFICATES_METHODDEF
5303 _SSL_ENUM_CRLS_METHODDEF
5304 _SSL_TXT2OBJ_METHODDEF
5305 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005306 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005307};
5308
5309
Christian Heimes598894f2016-09-05 23:19:05 +02005310#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005311
5312/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005313 * of the Python C thread library
5314 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5315 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005316
5317static PyThread_type_lock *_ssl_locks = NULL;
5318
Christian Heimes4d98ca92013-08-19 17:36:29 +02005319#if OPENSSL_VERSION_NUMBER >= 0x10000000
5320/* use new CRYPTO_THREADID API. */
5321static void
5322_ssl_threadid_callback(CRYPTO_THREADID *id)
5323{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005324 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005325}
5326#else
5327/* deprecated CRYPTO_set_id_callback() API. */
5328static unsigned long
5329_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005330 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005331}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005332#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005333
Bill Janssen6e027db2007-11-15 22:23:56 +00005334static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005335 (int mode, int n, const char *file, int line) {
5336 /* this function is needed to perform locking on shared data
5337 structures. (Note that OpenSSL uses a number of global data
5338 structures that will be implicitly shared whenever multiple
5339 threads use OpenSSL.) Multi-threaded applications will
5340 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005341
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005342 locking_function() must be able to handle up to
5343 CRYPTO_num_locks() different mutex locks. It sets the n-th
5344 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005345
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005346 file and line are the file number of the function setting the
5347 lock. They can be useful for debugging.
5348 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005349
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005350 if ((_ssl_locks == NULL) ||
5351 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5352 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005353
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005354 if (mode & CRYPTO_LOCK) {
5355 PyThread_acquire_lock(_ssl_locks[n], 1);
5356 } else {
5357 PyThread_release_lock(_ssl_locks[n]);
5358 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005359}
5360
5361static int _setup_ssl_threads(void) {
5362
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005363 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005364
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005365 if (_ssl_locks == NULL) {
5366 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005367 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5368 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005369 if (_ssl_locks == NULL) {
5370 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005371 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005372 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005373 for (i = 0; i < _ssl_locks_count; i++) {
5374 _ssl_locks[i] = PyThread_allocate_lock();
5375 if (_ssl_locks[i] == NULL) {
5376 unsigned int j;
5377 for (j = 0; j < i; j++) {
5378 PyThread_free_lock(_ssl_locks[j]);
5379 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005380 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005381 return 0;
5382 }
5383 }
5384 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005385#if OPENSSL_VERSION_NUMBER >= 0x10000000
5386 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5387#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005388 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005389#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005390 }
5391 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005392}
5393
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005394#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005395
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005396PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005397"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005398for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005399
Martin v. Löwis1a214512008-06-11 05:26:20 +00005400
5401static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005402 PyModuleDef_HEAD_INIT,
5403 "_ssl",
5404 module_doc,
5405 -1,
5406 PySSL_methods,
5407 NULL,
5408 NULL,
5409 NULL,
5410 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005411};
5412
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005413
5414static void
5415parse_openssl_version(unsigned long libver,
5416 unsigned int *major, unsigned int *minor,
5417 unsigned int *fix, unsigned int *patch,
5418 unsigned int *status)
5419{
5420 *status = libver & 0xF;
5421 libver >>= 4;
5422 *patch = libver & 0xFF;
5423 libver >>= 8;
5424 *fix = libver & 0xFF;
5425 libver >>= 8;
5426 *minor = libver & 0xFF;
5427 libver >>= 8;
5428 *major = libver & 0xFF;
5429}
5430
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005431PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005432PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005433{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005434 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005435 unsigned long libver;
5436 unsigned int major, minor, fix, patch, status;
5437 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005438 struct py_ssl_error_code *errcode;
5439 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005440
Antoine Pitrou152efa22010-05-16 18:19:27 +00005441 if (PyType_Ready(&PySSLContext_Type) < 0)
5442 return NULL;
5443 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005444 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005445 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5446 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005447 if (PyType_Ready(&PySSLSession_Type) < 0)
5448 return NULL;
5449
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005450
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005451 m = PyModule_Create(&_sslmodule);
5452 if (m == NULL)
5453 return NULL;
5454 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005455
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005456 /* Load _socket module and its C API */
5457 socket_api = PySocketModule_ImportModuleAndAPI();
5458 if (!socket_api)
5459 return NULL;
5460 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005461
Christian Heimesc941e622017-09-05 15:47:11 +02005462#ifndef OPENSSL_VERSION_1_1
5463 /* Load all algorithms and initialize cpuid */
5464 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005465 /* Init OpenSSL */
5466 SSL_load_error_strings();
5467 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005468#endif
5469
Christian Heimes598894f2016-09-05 23:19:05 +02005470#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005471 /* note that this will start threading if not already started */
5472 if (!_setup_ssl_threads()) {
5473 return NULL;
5474 }
Christian Heimes598894f2016-09-05 23:19:05 +02005475#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5476 /* OpenSSL 1.1.0 builtin thread support is enabled */
5477 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005478#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005479
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005480 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005481 sslerror_type_slots[0].pfunc = PyExc_OSError;
5482 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005483 if (PySSLErrorObject == NULL)
5484 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005485
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005486 /* ssl.CertificateError used to be a subclass of ValueError */
5487 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5488 if (bases == NULL)
5489 return NULL;
5490 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5491 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5492 bases, NULL);
5493 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005494 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5495 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5496 PySSLErrorObject, NULL);
5497 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5498 "ssl.SSLWantReadError", SSLWantReadError_doc,
5499 PySSLErrorObject, NULL);
5500 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5501 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5502 PySSLErrorObject, NULL);
5503 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5504 "ssl.SSLSyscallError", SSLSyscallError_doc,
5505 PySSLErrorObject, NULL);
5506 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5507 "ssl.SSLEOFError", SSLEOFError_doc,
5508 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005509 if (PySSLCertVerificationErrorObject == NULL
5510 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005511 || PySSLWantReadErrorObject == NULL
5512 || PySSLWantWriteErrorObject == NULL
5513 || PySSLSyscallErrorObject == NULL
5514 || PySSLEOFErrorObject == NULL)
5515 return NULL;
5516 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005517 || PyDict_SetItemString(d, "SSLCertVerificationError",
5518 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005519 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5520 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5521 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5522 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5523 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005524 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005525 if (PyDict_SetItemString(d, "_SSLContext",
5526 (PyObject *)&PySSLContext_Type) != 0)
5527 return NULL;
5528 if (PyDict_SetItemString(d, "_SSLSocket",
5529 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005530 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005531 if (PyDict_SetItemString(d, "MemoryBIO",
5532 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5533 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005534 if (PyDict_SetItemString(d, "SSLSession",
5535 (PyObject *)&PySSLSession_Type) != 0)
5536 return NULL;
5537
Christian Heimes892d66e2018-01-29 14:10:18 +01005538 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5539 PY_SSL_DEFAULT_CIPHER_STRING);
5540
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005541 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5542 PY_SSL_ERROR_ZERO_RETURN);
5543 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5544 PY_SSL_ERROR_WANT_READ);
5545 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5546 PY_SSL_ERROR_WANT_WRITE);
5547 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5548 PY_SSL_ERROR_WANT_X509_LOOKUP);
5549 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5550 PY_SSL_ERROR_SYSCALL);
5551 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5552 PY_SSL_ERROR_SSL);
5553 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5554 PY_SSL_ERROR_WANT_CONNECT);
5555 /* non ssl.h errorcodes */
5556 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5557 PY_SSL_ERROR_EOF);
5558 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5559 PY_SSL_ERROR_INVALID_ERROR_CODE);
5560 /* cert requirements */
5561 PyModule_AddIntConstant(m, "CERT_NONE",
5562 PY_SSL_CERT_NONE);
5563 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5564 PY_SSL_CERT_OPTIONAL);
5565 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5566 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005567 /* CRL verification for verification_flags */
5568 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5569 0);
5570 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5571 X509_V_FLAG_CRL_CHECK);
5572 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5573 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5574 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5575 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005576#ifdef X509_V_FLAG_TRUSTED_FIRST
5577 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5578 X509_V_FLAG_TRUSTED_FIRST);
5579#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005580
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005581 /* Alert Descriptions from ssl.h */
5582 /* note RESERVED constants no longer intended for use have been removed */
5583 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5584
5585#define ADD_AD_CONSTANT(s) \
5586 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5587 SSL_AD_##s)
5588
5589 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5590 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5591 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5592 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5593 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5594 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5595 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5596 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5597 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5598 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5599 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5600 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5601 ADD_AD_CONSTANT(UNKNOWN_CA);
5602 ADD_AD_CONSTANT(ACCESS_DENIED);
5603 ADD_AD_CONSTANT(DECODE_ERROR);
5604 ADD_AD_CONSTANT(DECRYPT_ERROR);
5605 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5606 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5607 ADD_AD_CONSTANT(INTERNAL_ERROR);
5608 ADD_AD_CONSTANT(USER_CANCELLED);
5609 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005610 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005611#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5612 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5613#endif
5614#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5615 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5616#endif
5617#ifdef SSL_AD_UNRECOGNIZED_NAME
5618 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5619#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005620#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5621 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5622#endif
5623#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5624 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5625#endif
5626#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5627 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5628#endif
5629
5630#undef ADD_AD_CONSTANT
5631
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005632 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005633#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005634 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5635 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005636#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005637#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005638 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5639 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005640#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005641 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005642 PY_SSL_VERSION_TLS);
5643 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5644 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005645 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5646 PY_SSL_VERSION_TLS_CLIENT);
5647 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5648 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005649 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5650 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005651#if HAVE_TLSv1_2
5652 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5653 PY_SSL_VERSION_TLS1_1);
5654 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5655 PY_SSL_VERSION_TLS1_2);
5656#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005657
Antoine Pitroub5218772010-05-21 09:56:06 +00005658 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005659 PyModule_AddIntConstant(m, "OP_ALL",
5660 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005661 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5662 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5663 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005664#if HAVE_TLSv1_2
5665 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5666 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5667#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005668#ifdef SSL_OP_NO_TLSv1_3
5669 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5670#else
5671 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5672#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005673 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5674 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005675 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005676 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005677#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005678 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005679#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005680#ifdef SSL_OP_NO_COMPRESSION
5681 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5682 SSL_OP_NO_COMPRESSION);
5683#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005684
Christian Heimes61d478c2018-01-27 15:51:38 +01005685#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5686 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5687 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5688#endif
5689#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5690 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5691 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5692#endif
5693#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5694 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5695 X509_CHECK_FLAG_NO_WILDCARDS);
5696#endif
5697#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5698 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5699 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5700#endif
5701#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5702 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5703 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5704#endif
5705#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5706 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5707 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5708#endif
5709
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005710#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005711 r = Py_True;
5712#else
5713 r = Py_False;
5714#endif
5715 Py_INCREF(r);
5716 PyModule_AddObject(m, "HAS_SNI", r);
5717
Antoine Pitrou501da612011-12-21 09:27:41 +01005718#ifdef OPENSSL_NO_ECDH
5719 r = Py_False;
5720#else
5721 r = Py_True;
5722#endif
5723 Py_INCREF(r);
5724 PyModule_AddObject(m, "HAS_ECDH", r);
5725
Christian Heimes29eab552018-02-25 12:31:33 +01005726#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005727 r = Py_True;
5728#else
5729 r = Py_False;
5730#endif
5731 Py_INCREF(r);
5732 PyModule_AddObject(m, "HAS_NPN", r);
5733
Christian Heimes29eab552018-02-25 12:31:33 +01005734#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05005735 r = Py_True;
5736#else
5737 r = Py_False;
5738#endif
5739 Py_INCREF(r);
5740 PyModule_AddObject(m, "HAS_ALPN", r);
5741
Christian Heimescb5b68a2017-09-07 18:07:00 -07005742#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
5743 r = Py_True;
5744#else
5745 r = Py_False;
5746#endif
5747 Py_INCREF(r);
5748 PyModule_AddObject(m, "HAS_TLSv1_3", r);
5749
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005750 /* Mappings for error codes */
5751 err_codes_to_names = PyDict_New();
5752 err_names_to_codes = PyDict_New();
5753 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5754 return NULL;
5755 errcode = error_codes;
5756 while (errcode->mnemonic != NULL) {
5757 PyObject *mnemo, *key;
5758 mnemo = PyUnicode_FromString(errcode->mnemonic);
5759 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5760 if (mnemo == NULL || key == NULL)
5761 return NULL;
5762 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5763 return NULL;
5764 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5765 return NULL;
5766 Py_DECREF(key);
5767 Py_DECREF(mnemo);
5768 errcode++;
5769 }
5770 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5771 return NULL;
5772 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5773 return NULL;
5774
5775 lib_codes_to_names = PyDict_New();
5776 if (lib_codes_to_names == NULL)
5777 return NULL;
5778 libcode = library_codes;
5779 while (libcode->library != NULL) {
5780 PyObject *mnemo, *key;
5781 key = PyLong_FromLong(libcode->code);
5782 mnemo = PyUnicode_FromString(libcode->library);
5783 if (key == NULL || mnemo == NULL)
5784 return NULL;
5785 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5786 return NULL;
5787 Py_DECREF(key);
5788 Py_DECREF(mnemo);
5789 libcode++;
5790 }
5791 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5792 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005793
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005794 /* OpenSSL version */
5795 /* SSLeay() gives us the version of the library linked against,
5796 which could be different from the headers version.
5797 */
5798 libver = SSLeay();
5799 r = PyLong_FromUnsignedLong(libver);
5800 if (r == NULL)
5801 return NULL;
5802 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5803 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005804 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005805 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5806 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5807 return NULL;
5808 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5809 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5810 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005811
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005812 libver = OPENSSL_VERSION_NUMBER;
5813 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5814 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5815 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5816 return NULL;
5817
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005818 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005819}