blob: ed6b7a835a9432f1cc2ec98a2e7f3249aa0ad588 [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
Benjamin Petersoncca27322015-01-23 16:35:37 -0500160# define HAVE_ALPN
161#endif
162
Christian Heimes6cdb7952018-02-24 22:12:40 +0100163/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
164 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
165 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
166 * OpenSSL 1.0.1+ and LibreSSL.
167 */
168#ifdef OPENSSL_NO_NEXTPROTONEG
169# define HAVE_NPN 0
170#elif defined(TLSEXT_TYPE_next_proto_neg)
171# define HAVE_NPN 1
172#else
173# define HAVE_NPN 0
174# endif
175
Victor Stinner524714e2016-07-22 17:43:59 +0200176#ifndef INVALID_SOCKET /* MS defines this */
177#define INVALID_SOCKET (-1)
178#endif
179
Christian Heimes598894f2016-09-05 23:19:05 +0200180#ifdef OPENSSL_VERSION_1_1
181/* OpenSSL 1.1.0+ */
182#ifndef OPENSSL_NO_SSL2
183#define OPENSSL_NO_SSL2
184#endif
185#else /* OpenSSL < 1.1.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200186#define HAVE_OPENSSL_CRYPTO_LOCK
Christian Heimes598894f2016-09-05 23:19:05 +0200187
188#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200189#define TLS_client_method SSLv23_client_method
190#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200191
192static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
193{
194 return ne->set;
195}
196
197#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200198/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200199static int COMP_get_type(const COMP_METHOD *meth)
200{
201 return meth->type;
202}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200203/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200204#endif
205
206static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
207{
208 return ctx->default_passwd_callback;
209}
210
211static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
212{
213 return ctx->default_passwd_callback_userdata;
214}
215
216static int X509_OBJECT_get_type(X509_OBJECT *x)
217{
218 return x->type;
219}
220
221static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
222{
223 return x->data.x509;
224}
225
226static int BIO_up_ref(BIO *b)
227{
228 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
229 return 1;
230}
231
232static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
233 return store->objs;
234}
235
Christian Heimes99a65702016-09-10 23:44:53 +0200236static int
237SSL_SESSION_has_ticket(const SSL_SESSION *s)
238{
239 return (s->tlsext_ticklen > 0) ? 1 : 0;
240}
241
242static unsigned long
243SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
244{
245 return s->tlsext_tick_lifetime_hint;
246}
247
Christian Heimes598894f2016-09-05 23:19:05 +0200248#endif /* OpenSSL < 1.1.0 or LibreSSL */
249
Christian Heimes892d66e2018-01-29 14:10:18 +0100250/* Default cipher suites */
251#ifndef PY_SSL_DEFAULT_CIPHERS
252#define PY_SSL_DEFAULT_CIPHERS 1
253#endif
254
255#if PY_SSL_DEFAULT_CIPHERS == 0
256 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
257 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
258 #endif
259#elif PY_SSL_DEFAULT_CIPHERS == 1
260/* Python custom selection of sensible ciper suites
261 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
262 * !aNULL:!eNULL: really no NULL ciphers
263 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
264 * !aDSS: no authentication with discrete logarithm DSA algorithm
265 * !SRP:!PSK: no secure remote password or pre-shared key authentication
266 */
267 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
268#elif PY_SSL_DEFAULT_CIPHERS == 2
269/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
270 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
271#else
272 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
273#endif
274
Christian Heimes598894f2016-09-05 23:19:05 +0200275
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000276enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000277 /* these mirror ssl.h */
278 PY_SSL_ERROR_NONE,
279 PY_SSL_ERROR_SSL,
280 PY_SSL_ERROR_WANT_READ,
281 PY_SSL_ERROR_WANT_WRITE,
282 PY_SSL_ERROR_WANT_X509_LOOKUP,
283 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
284 PY_SSL_ERROR_ZERO_RETURN,
285 PY_SSL_ERROR_WANT_CONNECT,
286 /* start of non ssl.h errorcodes */
287 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
288 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
289 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000290};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000291
Thomas Woutersed03b412007-08-28 21:37:11 +0000292enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000293 PY_SSL_CLIENT,
294 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000295};
296
297enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000298 PY_SSL_CERT_NONE,
299 PY_SSL_CERT_OPTIONAL,
300 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000301};
302
303enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000304 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200305 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200306 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100307#if HAVE_TLSv1_2
308 PY_SSL_VERSION_TLS1,
309 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200310 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100311#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200312 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000313#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200314 PY_SSL_VERSION_TLS_CLIENT=0x10,
315 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100316};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200317
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000318/* serves as a flag to see whether we've initialized the SSL thread support. */
319/* 0 means no, greater than 0 means yes */
320
321static unsigned int _ssl_locks_count = 0;
322
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000323/* SSL socket object */
324
325#define X509_NAME_MAXLEN 256
326
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000327/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
328 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
329 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
330#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000331# define HAVE_SSL_CTX_CLEAR_OPTIONS
332#else
333# undef HAVE_SSL_CTX_CLEAR_OPTIONS
334#endif
335
Antoine Pitroud6494802011-07-21 01:11:30 +0200336/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
337 * older SSL, but let's be safe */
338#define PySSL_CB_MAXLEN 128
339
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100340
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000341typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000342 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000343 SSL_CTX *ctx;
Christian Heimes6cdb7952018-02-24 22:12:40 +0100344#ifdef HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500345 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100346 int npn_protocols_len;
347#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500348#ifdef HAVE_ALPN
349 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300350 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500351#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100352#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100353 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100354#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100355 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100356 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
357 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
358 */
359 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100360 int protocol;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000361} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000362
Antoine Pitrou152efa22010-05-16 18:19:27 +0000363typedef struct {
364 PyObject_HEAD
365 PyObject *Socket; /* weakref to socket on which we're layered */
366 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100367 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200368 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200369 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200370 PyObject *owner; /* Python level "owner" passed to servername callback */
371 PyObject *server_hostname;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700372 int ssl_errno; /* last seen error from SSL */
373 int c_errno; /* last seen error from libc */
374#ifdef MS_WINDOWS
375 int ws_errno; /* last seen error from winsock */
376#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000377} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000378
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200379typedef struct {
380 PyObject_HEAD
381 BIO *bio;
382 int eof_written;
383} PySSLMemoryBIO;
384
Christian Heimes99a65702016-09-10 23:44:53 +0200385typedef struct {
386 PyObject_HEAD
387 SSL_SESSION *session;
388 PySSLContext *ctx;
389} PySSLSession;
390
Antoine Pitrou152efa22010-05-16 18:19:27 +0000391static PyTypeObject PySSLContext_Type;
392static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200393static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200394static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000395
Steve Dowere6eb48c2017-09-08 15:16:15 -0700396#ifdef MS_WINDOWS
397#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
398 (sock)->ws_errno = WSAGetLastError(); \
399 _PySSL_FIX_ERRNO; \
400 (sock)->c_errno = errno; \
401 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
402 } else { sock->ws_errno = 0; sock->c_errno = 0; sock->ssl_errno = 0; }
403#else
404#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
405 (sock)->c_errno = errno; \
406 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
407 } else { (sock)->c_errno = 0; (sock)->ssl_errno = 0; }
408#endif
409#define _PySSL_UPDATE_ERRNO(sock, retcode) _PySSL_UPDATE_ERRNO_IF(1, (sock), (retcode))
410
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300411/*[clinic input]
412module _ssl
413class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
414class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
415class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200416class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300417[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200418/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300419
420#include "clinic/_ssl.c.h"
421
Victor Stinner14690702015-04-06 22:46:13 +0200422static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000423
Christian Heimes141c5e82018-02-24 21:10:57 +0100424static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
425static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000426#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200427#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200428#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000429
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000430typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000431 SOCKET_IS_NONBLOCKING,
432 SOCKET_IS_BLOCKING,
433 SOCKET_HAS_TIMED_OUT,
434 SOCKET_HAS_BEEN_CLOSED,
435 SOCKET_TOO_LARGE_FOR_SELECT,
436 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000437} timeout_state;
438
Thomas Woutersed03b412007-08-28 21:37:11 +0000439/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000440#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200441#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000442
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200443/* Get the socket from a PySSLSocket, if it has one */
444#define GET_SOCKET(obj) ((obj)->Socket ? \
445 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200446
Victor Stinner14690702015-04-06 22:46:13 +0200447/* If sock is NULL, use a timeout of 0 second */
448#define GET_SOCKET_TIMEOUT(sock) \
449 ((sock != NULL) ? (sock)->sock_timeout : 0)
450
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200451/*
452 * SSL errors.
453 */
454
455PyDoc_STRVAR(SSLError_doc,
456"An error occurred in the SSL implementation.");
457
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700458PyDoc_STRVAR(SSLCertVerificationError_doc,
459"A certificate could not be verified.");
460
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200461PyDoc_STRVAR(SSLZeroReturnError_doc,
462"SSL/TLS session closed cleanly.");
463
464PyDoc_STRVAR(SSLWantReadError_doc,
465"Non-blocking SSL socket needs to read more data\n"
466"before the requested operation can be completed.");
467
468PyDoc_STRVAR(SSLWantWriteError_doc,
469"Non-blocking SSL socket needs to write more data\n"
470"before the requested operation can be completed.");
471
472PyDoc_STRVAR(SSLSyscallError_doc,
473"System error when attempting SSL operation.");
474
475PyDoc_STRVAR(SSLEOFError_doc,
476"SSL/TLS connection terminated abruptly.");
477
478static PyObject *
479SSLError_str(PyOSErrorObject *self)
480{
481 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
482 Py_INCREF(self->strerror);
483 return self->strerror;
484 }
485 else
486 return PyObject_Str(self->args);
487}
488
489static PyType_Slot sslerror_type_slots[] = {
490 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
491 {Py_tp_doc, SSLError_doc},
492 {Py_tp_str, SSLError_str},
493 {0, 0},
494};
495
496static PyType_Spec sslerror_type_spec = {
497 "ssl.SSLError",
498 sizeof(PyOSErrorObject),
499 0,
500 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
501 sslerror_type_slots
502};
503
504static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700505fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
506 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200507{
508 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700509 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200510 PyObject *init_value, *msg, *key;
511 _Py_IDENTIFIER(reason);
512 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700513 _Py_IDENTIFIER(verify_message);
514 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200515
516 if (errcode != 0) {
517 int lib, reason;
518
519 lib = ERR_GET_LIB(errcode);
520 reason = ERR_GET_REASON(errcode);
521 key = Py_BuildValue("ii", lib, reason);
522 if (key == NULL)
523 goto fail;
524 reason_obj = PyDict_GetItem(err_codes_to_names, key);
525 Py_DECREF(key);
526 if (reason_obj == NULL) {
527 /* XXX if reason < 100, it might reflect a library number (!!) */
528 PyErr_Clear();
529 }
530 key = PyLong_FromLong(lib);
531 if (key == NULL)
532 goto fail;
533 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
534 Py_DECREF(key);
535 if (lib_obj == NULL) {
536 PyErr_Clear();
537 }
538 if (errstr == NULL)
539 errstr = ERR_reason_error_string(errcode);
540 }
541 if (errstr == NULL)
542 errstr = "unknown error";
543
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700544 /* verify code for cert validation error */
545 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
546 const char *verify_str = NULL;
547 long verify_code;
548
549 verify_code = SSL_get_verify_result(sslsock->ssl);
550 verify_code_obj = PyLong_FromLong(verify_code);
551 if (verify_code_obj == NULL) {
552 goto fail;
553 }
554
555 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700556#ifdef X509_V_ERR_HOSTNAME_MISMATCH
557 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700558 case X509_V_ERR_HOSTNAME_MISMATCH:
559 verify_obj = PyUnicode_FromFormat(
560 "Hostname mismatch, certificate is not valid for '%S'.",
561 sslsock->server_hostname
562 );
563 break;
Christian Heimes09153602017-09-08 14:47:58 -0700564#endif
565#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700566 case X509_V_ERR_IP_ADDRESS_MISMATCH:
567 verify_obj = PyUnicode_FromFormat(
568 "IP address mismatch, certificate is not valid for '%S'.",
569 sslsock->server_hostname
570 );
571 break;
Christian Heimes09153602017-09-08 14:47:58 -0700572#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700573 default:
574 verify_str = X509_verify_cert_error_string(verify_code);
575 if (verify_str != NULL) {
576 verify_obj = PyUnicode_FromString(verify_str);
577 } else {
578 verify_obj = Py_None;
579 Py_INCREF(verify_obj);
580 }
581 break;
582 }
583 if (verify_obj == NULL) {
584 goto fail;
585 }
586 }
587
588 if (verify_obj && reason_obj && lib_obj)
589 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
590 lib_obj, reason_obj, errstr, verify_obj,
591 lineno);
592 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200593 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
594 lib_obj, reason_obj, errstr, lineno);
595 else if (lib_obj)
596 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
597 lib_obj, errstr, lineno);
598 else
599 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200600 if (msg == NULL)
601 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100602
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200603 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100604 if (init_value == NULL)
605 goto fail;
606
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200607 err_value = PyObject_CallObject(type, init_value);
608 Py_DECREF(init_value);
609 if (err_value == NULL)
610 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100611
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200612 if (reason_obj == NULL)
613 reason_obj = Py_None;
614 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
615 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700616
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200617 if (lib_obj == NULL)
618 lib_obj = Py_None;
619 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
620 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700621
622 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
623 /* Only set verify code / message for SSLCertVerificationError */
624 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
625 verify_code_obj))
626 goto fail;
627 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
628 goto fail;
629 }
630
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200631 PyErr_SetObject(type, err_value);
632fail:
633 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700634 Py_XDECREF(verify_code_obj);
635 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200636}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000637
638static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700639PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000640{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200641 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200642 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000643 int err;
644 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200645 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000646
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000647 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200648 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000649
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700650 if (sslsock->ssl != NULL) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700651 err = sslsock->ssl_errno;
Thomas Woutersed03b412007-08-28 21:37:11 +0000652
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000653 switch (err) {
654 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200655 errstr = "TLS/SSL connection has been closed (EOF)";
656 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000657 p = PY_SSL_ERROR_ZERO_RETURN;
658 break;
659 case SSL_ERROR_WANT_READ:
660 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200661 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000662 p = PY_SSL_ERROR_WANT_READ;
663 break;
664 case SSL_ERROR_WANT_WRITE:
665 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200666 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000667 errstr = "The operation did not complete (write)";
668 break;
669 case SSL_ERROR_WANT_X509_LOOKUP:
670 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000671 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000672 break;
673 case SSL_ERROR_WANT_CONNECT:
674 p = PY_SSL_ERROR_WANT_CONNECT;
675 errstr = "The operation did not complete (connect)";
676 break;
677 case SSL_ERROR_SYSCALL:
678 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000679 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700680 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000681 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000682 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200683 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000684 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200685 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000686 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000687 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700688#ifdef MS_WINDOWS
689 if (sslsock->ws_errno)
690 return PyErr_SetFromWindowsErr(sslsock->ws_errno);
691#endif
692 if (sslsock->c_errno) {
693 errno = sslsock->c_errno;
694 return PyErr_SetFromErrno(PyExc_OSError);
695 }
696 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200697 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000698 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200699 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000700 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000701 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200702 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000703 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000704 }
705 } else {
706 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 }
708 break;
709 }
710 case SSL_ERROR_SSL:
711 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000712 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700713 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200714 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000715 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700716 }
717 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
718 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
719 type = PySSLCertVerificationErrorObject;
720 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000721 break;
722 }
723 default:
724 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
725 errstr = "Invalid error code";
726 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000727 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700728 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000729 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000730 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000731}
732
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000733static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200734_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000735
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200736 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000737 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200738 else
739 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700740 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000741 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000742 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000743}
744
Christian Heimes61d478c2018-01-27 15:51:38 +0100745/*
746 * SSL objects
747 */
748
749static int
750_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
751{
752 int retval = -1;
753 ASN1_OCTET_STRING *ip;
754 PyObject *hostname;
755 size_t len;
756
757 assert(server_hostname);
758
759 /* Disable OpenSSL's special mode with leading dot in hostname:
760 * When name starts with a dot (e.g ".example.com"), it will be
761 * matched by a certificate valid for any sub-domain of name.
762 */
763 len = strlen(server_hostname);
764 if (len == 0 || *server_hostname == '.') {
765 PyErr_SetString(
766 PyExc_ValueError,
767 "server_hostname cannot be an empty string or start with a "
768 "leading dot.");
769 return retval;
770 }
771
772 /* inet_pton is not available on all platforms. */
773 ip = a2i_IPADDRESS(server_hostname);
774 if (ip == NULL) {
775 ERR_clear_error();
776 }
777
Christian Heimes11a14932018-02-24 02:35:08 +0100778 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100779 if (hostname == NULL) {
780 goto error;
781 }
782 self->server_hostname = hostname;
783
784 /* Only send SNI extension for non-IP hostnames */
785 if (ip == NULL) {
786 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
787 _setSSLError(NULL, 0, __FILE__, __LINE__);
788 }
789 }
790 if (self->ctx->check_hostname) {
791 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
792 if (ip == NULL) {
793 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname, 0)) {
794 _setSSLError(NULL, 0, __FILE__, __LINE__);
795 goto error;
796 }
797 } else {
798 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
799 ASN1_STRING_length(ip))) {
800 _setSSLError(NULL, 0, __FILE__, __LINE__);
801 goto error;
802 }
803 }
804 }
805 retval = 0;
806 error:
807 if (ip != NULL) {
808 ASN1_OCTET_STRING_free(ip);
809 }
810 return retval;
811}
812
Antoine Pitrou152efa22010-05-16 18:19:27 +0000813static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100814newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000815 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200816 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100817 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200818 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000819{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000820 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100821 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200822 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000823
Antoine Pitrou152efa22010-05-16 18:19:27 +0000824 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 if (self == NULL)
826 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000827
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000828 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000829 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100830 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700831 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200832 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200833 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700834 self->server_hostname = NULL;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700835 self->ssl_errno = 0;
836 self->c_errno = 0;
837#ifdef MS_WINDOWS
838 self->ws_errno = 0;
839#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200840
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000841 /* Make sure the SSL error state is initialized */
842 (void) ERR_get_state();
843 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000844
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000845 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000846 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000847 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200848 SSL_set_app_data(self->ssl, self);
849 if (sock) {
850 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
851 } else {
852 /* BIOs are reference counted and SSL_set_bio borrows our reference.
853 * To prevent a double free in memory_bio_dealloc() we need to take an
854 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200855 BIO_up_ref(inbio->bio);
856 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200857 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
858 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200859 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000860#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200861 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000862#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200863 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000864
Christian Heimes61d478c2018-01-27 15:51:38 +0100865 if (server_hostname != NULL) {
866 if (_ssl_configure_hostname(self, server_hostname) < 0) {
867 Py_DECREF(self);
868 return NULL;
869 }
870 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000871 /* If the socket is in non-blocking mode or timeout mode, set the BIO
872 * to non-blocking mode (blocking is the default)
873 */
Victor Stinnere2452312015-03-28 03:00:46 +0100874 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000875 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
876 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
877 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000878
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000879 PySSL_BEGIN_ALLOW_THREADS
880 if (socket_type == PY_SSL_CLIENT)
881 SSL_set_connect_state(self->ssl);
882 else
883 SSL_set_accept_state(self->ssl);
884 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000885
Antoine Pitroud6494802011-07-21 01:11:30 +0200886 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200887 if (sock != NULL) {
888 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
889 if (self->Socket == NULL) {
890 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200891 return NULL;
892 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100893 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100894 if (owner && owner != Py_None) {
895 if (PySSL_set_owner(self, owner, NULL) == -1) {
896 Py_DECREF(self);
897 return NULL;
898 }
899 }
900 if (session && session != Py_None) {
901 if (PySSL_set_session(self, session, NULL) == -1) {
902 Py_DECREF(self);
903 return NULL;
904 }
905 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000906 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000907}
908
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000909/* SSL object methods */
910
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300911/*[clinic input]
912_ssl._SSLSocket.do_handshake
913[clinic start generated code]*/
914
915static PyObject *
916_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
917/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000918{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000919 int ret;
920 int err;
921 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200922 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200923 _PyTime_t timeout, deadline = 0;
924 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000925
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200926 if (sock) {
927 if (((PyObject*)sock) == Py_None) {
928 _setSSLError("Underlying socket connection gone",
929 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
930 return NULL;
931 }
932 Py_INCREF(sock);
933
934 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100935 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200936 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
937 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000939
Victor Stinner14690702015-04-06 22:46:13 +0200940 timeout = GET_SOCKET_TIMEOUT(sock);
941 has_timeout = (timeout > 0);
942 if (has_timeout)
943 deadline = _PyTime_GetMonotonicClock() + timeout;
944
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 /* Actually negotiate SSL connection */
946 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000947 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000948 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000949 ret = SSL_do_handshake(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -0700950 _PySSL_UPDATE_ERRNO_IF(ret < 1, self, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000951 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -0700952 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200953
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000954 if (PyErr_CheckSignals())
955 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200956
Victor Stinner14690702015-04-06 22:46:13 +0200957 if (has_timeout)
958 timeout = deadline - _PyTime_GetMonotonicClock();
959
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000960 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200961 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000962 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200963 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000964 } else {
965 sockstate = SOCKET_OPERATION_OK;
966 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200967
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000968 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000969 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000970 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000971 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000972 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
973 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000974 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000975 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000976 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
977 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000978 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000979 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000980 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
981 break;
982 }
983 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200984 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000985 if (ret < 1)
986 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000987
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200988 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000989
990error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200991 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000992 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000993}
994
Thomas Woutersed03b412007-08-28 21:37:11 +0000995static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300996_asn1obj2py(const ASN1_OBJECT *name, int no_name)
997{
998 char buf[X509_NAME_MAXLEN];
999 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001000 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001001 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001002
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001003 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001004 if (buflen < 0) {
1005 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001006 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001008 /* initial buffer is too small for oid + terminating null byte */
1009 if (buflen > X509_NAME_MAXLEN - 1) {
1010 /* make OBJ_obj2txt() calculate the required buflen */
1011 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1012 /* allocate len + 1 for terminating NULL byte */
1013 namebuf = PyMem_Malloc(buflen + 1);
1014 if (namebuf == NULL) {
1015 PyErr_NoMemory();
1016 return NULL;
1017 }
1018 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1019 if (buflen < 0) {
1020 _setSSLError(NULL, 0, __FILE__, __LINE__);
1021 goto done;
1022 }
1023 }
1024 if (!buflen && no_name) {
1025 Py_INCREF(Py_None);
1026 name_obj = Py_None;
1027 }
1028 else {
1029 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1030 }
1031
1032 done:
1033 if (buf != namebuf) {
1034 PyMem_Free(namebuf);
1035 }
1036 return name_obj;
1037}
1038
1039static PyObject *
1040_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1041{
1042 Py_ssize_t buflen;
1043 unsigned char *valuebuf = NULL;
1044 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001045
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001046 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1047 if (buflen < 0) {
1048 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001049 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001051 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001052 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001053 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001054}
1055
1056static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001057_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001058{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1060 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1061 PyObject *rdnt;
1062 PyObject *attr = NULL; /* tuple to hold an attribute */
1063 int entry_count = X509_NAME_entry_count(xname);
1064 X509_NAME_ENTRY *entry;
1065 ASN1_OBJECT *name;
1066 ASN1_STRING *value;
1067 int index_counter;
1068 int rdn_level = -1;
1069 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001070
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001071 dn = PyList_New(0);
1072 if (dn == NULL)
1073 return NULL;
1074 /* now create another tuple to hold the top-level RDN */
1075 rdn = PyList_New(0);
1076 if (rdn == NULL)
1077 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001078
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001079 for (index_counter = 0;
1080 index_counter < entry_count;
1081 index_counter++)
1082 {
1083 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001084
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001085 /* check to see if we've gotten to a new RDN */
1086 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001087 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001088 /* yes, new RDN */
1089 /* add old RDN to DN */
1090 rdnt = PyList_AsTuple(rdn);
1091 Py_DECREF(rdn);
1092 if (rdnt == NULL)
1093 goto fail0;
1094 retcode = PyList_Append(dn, rdnt);
1095 Py_DECREF(rdnt);
1096 if (retcode < 0)
1097 goto fail0;
1098 /* create new RDN */
1099 rdn = PyList_New(0);
1100 if (rdn == NULL)
1101 goto fail0;
1102 }
1103 }
Christian Heimes598894f2016-09-05 23:19:05 +02001104 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001105
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001106 /* now add this attribute to the current RDN */
1107 name = X509_NAME_ENTRY_get_object(entry);
1108 value = X509_NAME_ENTRY_get_data(entry);
1109 attr = _create_tuple_for_attribute(name, value);
1110 /*
1111 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1112 entry->set,
1113 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1114 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1115 */
1116 if (attr == NULL)
1117 goto fail1;
1118 retcode = PyList_Append(rdn, attr);
1119 Py_DECREF(attr);
1120 if (retcode < 0)
1121 goto fail1;
1122 }
1123 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001124 if (rdn != NULL) {
1125 if (PyList_GET_SIZE(rdn) > 0) {
1126 rdnt = PyList_AsTuple(rdn);
1127 Py_DECREF(rdn);
1128 if (rdnt == NULL)
1129 goto fail0;
1130 retcode = PyList_Append(dn, rdnt);
1131 Py_DECREF(rdnt);
1132 if (retcode < 0)
1133 goto fail0;
1134 }
1135 else {
1136 Py_DECREF(rdn);
1137 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001138 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001139
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 /* convert list to tuple */
1141 rdnt = PyList_AsTuple(dn);
1142 Py_DECREF(dn);
1143 if (rdnt == NULL)
1144 return NULL;
1145 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001146
1147 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001149
1150 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001151 Py_XDECREF(dn);
1152 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001153}
1154
1155static PyObject *
1156_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001157
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001158 /* this code follows the procedure outlined in
1159 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1160 function to extract the STACK_OF(GENERAL_NAME),
1161 then iterates through the stack to add the
1162 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001163
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001164 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001165 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001166 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001167 GENERAL_NAMES *names = NULL;
1168 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001169 BIO *biobuf = NULL;
1170 char buf[2048];
1171 char *vptr;
1172 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001173
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 if (certificate == NULL)
1175 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001176
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001177 /* get a memory buffer */
1178 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001179
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001180 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1181 certificate, NID_subject_alt_name, NULL, NULL);
1182 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001183 if (peer_alt_names == Py_None) {
1184 peer_alt_names = PyList_New(0);
1185 if (peer_alt_names == NULL)
1186 goto fail;
1187 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001188
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001189 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001190 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001191 int gntype;
1192 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001193
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001194 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001195 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001196 switch (gntype) {
1197 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001198 /* we special-case DirName as a tuple of
1199 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001200
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001201 t = PyTuple_New(2);
1202 if (t == NULL) {
1203 goto fail;
1204 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001205
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001206 v = PyUnicode_FromString("DirName");
1207 if (v == NULL) {
1208 Py_DECREF(t);
1209 goto fail;
1210 }
1211 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001212
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001213 v = _create_tuple_for_X509_NAME (name->d.dirn);
1214 if (v == NULL) {
1215 Py_DECREF(t);
1216 goto fail;
1217 }
1218 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001219 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001220
Christian Heimes824f7f32013-08-17 00:54:47 +02001221 case GEN_EMAIL:
1222 case GEN_DNS:
1223 case GEN_URI:
1224 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1225 correctly, CVE-2013-4238 */
1226 t = PyTuple_New(2);
1227 if (t == NULL)
1228 goto fail;
1229 switch (gntype) {
1230 case GEN_EMAIL:
1231 v = PyUnicode_FromString("email");
1232 as = name->d.rfc822Name;
1233 break;
1234 case GEN_DNS:
1235 v = PyUnicode_FromString("DNS");
1236 as = name->d.dNSName;
1237 break;
1238 case GEN_URI:
1239 v = PyUnicode_FromString("URI");
1240 as = name->d.uniformResourceIdentifier;
1241 break;
1242 }
1243 if (v == NULL) {
1244 Py_DECREF(t);
1245 goto fail;
1246 }
1247 PyTuple_SET_ITEM(t, 0, v);
1248 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1249 ASN1_STRING_length(as));
1250 if (v == NULL) {
1251 Py_DECREF(t);
1252 goto fail;
1253 }
1254 PyTuple_SET_ITEM(t, 1, v);
1255 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001256
Christian Heimes1c03abd2016-09-06 23:25:35 +02001257 case GEN_RID:
1258 t = PyTuple_New(2);
1259 if (t == NULL)
1260 goto fail;
1261
1262 v = PyUnicode_FromString("Registered ID");
1263 if (v == NULL) {
1264 Py_DECREF(t);
1265 goto fail;
1266 }
1267 PyTuple_SET_ITEM(t, 0, v);
1268
1269 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1270 if (len < 0) {
1271 Py_DECREF(t);
1272 _setSSLError(NULL, 0, __FILE__, __LINE__);
1273 goto fail;
1274 } else if (len >= (int)sizeof(buf)) {
1275 v = PyUnicode_FromString("<INVALID>");
1276 } else {
1277 v = PyUnicode_FromStringAndSize(buf, len);
1278 }
1279 if (v == NULL) {
1280 Py_DECREF(t);
1281 goto fail;
1282 }
1283 PyTuple_SET_ITEM(t, 1, v);
1284 break;
1285
Christian Heimes824f7f32013-08-17 00:54:47 +02001286 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001288 switch (gntype) {
1289 /* check for new general name type */
1290 case GEN_OTHERNAME:
1291 case GEN_X400:
1292 case GEN_EDIPARTY:
1293 case GEN_IPADD:
1294 case GEN_RID:
1295 break;
1296 default:
1297 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1298 "Unknown general name type %d",
1299 gntype) == -1) {
1300 goto fail;
1301 }
1302 break;
1303 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001304 (void) BIO_reset(biobuf);
1305 GENERAL_NAME_print(biobuf, name);
1306 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1307 if (len < 0) {
1308 _setSSLError(NULL, 0, __FILE__, __LINE__);
1309 goto fail;
1310 }
1311 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001312 if (vptr == NULL) {
1313 PyErr_Format(PyExc_ValueError,
1314 "Invalid value %.200s",
1315 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001316 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001317 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001318 t = PyTuple_New(2);
1319 if (t == NULL)
1320 goto fail;
1321 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1322 if (v == NULL) {
1323 Py_DECREF(t);
1324 goto fail;
1325 }
1326 PyTuple_SET_ITEM(t, 0, v);
1327 v = PyUnicode_FromStringAndSize((vptr + 1),
1328 (len - (vptr - buf + 1)));
1329 if (v == NULL) {
1330 Py_DECREF(t);
1331 goto fail;
1332 }
1333 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001334 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001335 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001336
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001337 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001338
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001339 if (PyList_Append(peer_alt_names, t) < 0) {
1340 Py_DECREF(t);
1341 goto fail;
1342 }
1343 Py_DECREF(t);
1344 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001345 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001346 }
1347 BIO_free(biobuf);
1348 if (peer_alt_names != Py_None) {
1349 v = PyList_AsTuple(peer_alt_names);
1350 Py_DECREF(peer_alt_names);
1351 return v;
1352 } else {
1353 return peer_alt_names;
1354 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001355
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001356
1357 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001358 if (biobuf != NULL)
1359 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001360
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 if (peer_alt_names != Py_None) {
1362 Py_XDECREF(peer_alt_names);
1363 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001364
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001365 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001366}
1367
1368static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001369_get_aia_uri(X509 *certificate, int nid) {
1370 PyObject *lst = NULL, *ostr = NULL;
1371 int i, result;
1372 AUTHORITY_INFO_ACCESS *info;
1373
1374 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001375 if (info == NULL)
1376 return Py_None;
1377 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1378 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001379 return Py_None;
1380 }
1381
1382 if ((lst = PyList_New(0)) == NULL) {
1383 goto fail;
1384 }
1385
1386 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1387 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1388 ASN1_IA5STRING *uri;
1389
1390 if ((OBJ_obj2nid(ad->method) != nid) ||
1391 (ad->location->type != GEN_URI)) {
1392 continue;
1393 }
1394 uri = ad->location->d.uniformResourceIdentifier;
1395 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1396 uri->length);
1397 if (ostr == NULL) {
1398 goto fail;
1399 }
1400 result = PyList_Append(lst, ostr);
1401 Py_DECREF(ostr);
1402 if (result < 0) {
1403 goto fail;
1404 }
1405 }
1406 AUTHORITY_INFO_ACCESS_free(info);
1407
1408 /* convert to tuple or None */
1409 if (PyList_Size(lst) == 0) {
1410 Py_DECREF(lst);
1411 return Py_None;
1412 } else {
1413 PyObject *tup;
1414 tup = PyList_AsTuple(lst);
1415 Py_DECREF(lst);
1416 return tup;
1417 }
1418
1419 fail:
1420 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001421 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001422 return NULL;
1423}
1424
1425static PyObject *
1426_get_crl_dp(X509 *certificate) {
1427 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001428 int i, j;
1429 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001430
Christian Heimes598894f2016-09-05 23:19:05 +02001431 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001432
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001433 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001434 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001435
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001436 lst = PyList_New(0);
1437 if (lst == NULL)
1438 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001439
1440 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1441 DIST_POINT *dp;
1442 STACK_OF(GENERAL_NAME) *gns;
1443
1444 dp = sk_DIST_POINT_value(dps, i);
1445 gns = dp->distpoint->name.fullname;
1446
1447 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1448 GENERAL_NAME *gn;
1449 ASN1_IA5STRING *uri;
1450 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001451 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001452
1453 gn = sk_GENERAL_NAME_value(gns, j);
1454 if (gn->type != GEN_URI) {
1455 continue;
1456 }
1457 uri = gn->d.uniformResourceIdentifier;
1458 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1459 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001460 if (ouri == NULL)
1461 goto done;
1462
1463 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001464 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001465 if (err < 0)
1466 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001467 }
1468 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001469
1470 /* Convert to tuple. */
1471 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1472
1473 done:
1474 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001475 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001476 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001477}
1478
1479static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001480_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001481
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001482 PyObject *retval = NULL;
1483 BIO *biobuf = NULL;
1484 PyObject *peer;
1485 PyObject *peer_alt_names = NULL;
1486 PyObject *issuer;
1487 PyObject *version;
1488 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001489 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001490 ASN1_INTEGER *serialNumber;
1491 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001492 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001493 ASN1_TIME *notBefore, *notAfter;
1494 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001495
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001496 retval = PyDict_New();
1497 if (retval == NULL)
1498 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001499
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001500 peer = _create_tuple_for_X509_NAME(
1501 X509_get_subject_name(certificate));
1502 if (peer == NULL)
1503 goto fail0;
1504 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1505 Py_DECREF(peer);
1506 goto fail0;
1507 }
1508 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001509
Antoine Pitroufb046912010-11-09 20:21:19 +00001510 issuer = _create_tuple_for_X509_NAME(
1511 X509_get_issuer_name(certificate));
1512 if (issuer == NULL)
1513 goto fail0;
1514 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001515 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001516 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001517 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001518 Py_DECREF(issuer);
1519
1520 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001521 if (version == NULL)
1522 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001523 if (PyDict_SetItemString(retval, "version", version) < 0) {
1524 Py_DECREF(version);
1525 goto fail0;
1526 }
1527 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001528
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001529 /* get a memory buffer */
1530 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001531
Antoine Pitroufb046912010-11-09 20:21:19 +00001532 (void) BIO_reset(biobuf);
1533 serialNumber = X509_get_serialNumber(certificate);
1534 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1535 i2a_ASN1_INTEGER(biobuf, serialNumber);
1536 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1537 if (len < 0) {
1538 _setSSLError(NULL, 0, __FILE__, __LINE__);
1539 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001540 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001541 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1542 if (sn_obj == NULL)
1543 goto fail1;
1544 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1545 Py_DECREF(sn_obj);
1546 goto fail1;
1547 }
1548 Py_DECREF(sn_obj);
1549
1550 (void) BIO_reset(biobuf);
1551 notBefore = X509_get_notBefore(certificate);
1552 ASN1_TIME_print(biobuf, notBefore);
1553 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1554 if (len < 0) {
1555 _setSSLError(NULL, 0, __FILE__, __LINE__);
1556 goto fail1;
1557 }
1558 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1559 if (pnotBefore == NULL)
1560 goto fail1;
1561 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1562 Py_DECREF(pnotBefore);
1563 goto fail1;
1564 }
1565 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001566
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001567 (void) BIO_reset(biobuf);
1568 notAfter = X509_get_notAfter(certificate);
1569 ASN1_TIME_print(biobuf, notAfter);
1570 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1571 if (len < 0) {
1572 _setSSLError(NULL, 0, __FILE__, __LINE__);
1573 goto fail1;
1574 }
1575 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1576 if (pnotAfter == NULL)
1577 goto fail1;
1578 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1579 Py_DECREF(pnotAfter);
1580 goto fail1;
1581 }
1582 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001583
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001584 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001585
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001586 peer_alt_names = _get_peer_alt_names(certificate);
1587 if (peer_alt_names == NULL)
1588 goto fail1;
1589 else if (peer_alt_names != Py_None) {
1590 if (PyDict_SetItemString(retval, "subjectAltName",
1591 peer_alt_names) < 0) {
1592 Py_DECREF(peer_alt_names);
1593 goto fail1;
1594 }
1595 Py_DECREF(peer_alt_names);
1596 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001597
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001598 /* Authority Information Access: OCSP URIs */
1599 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1600 if (obj == NULL) {
1601 goto fail1;
1602 } else if (obj != Py_None) {
1603 result = PyDict_SetItemString(retval, "OCSP", obj);
1604 Py_DECREF(obj);
1605 if (result < 0) {
1606 goto fail1;
1607 }
1608 }
1609
1610 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1611 if (obj == NULL) {
1612 goto fail1;
1613 } else if (obj != Py_None) {
1614 result = PyDict_SetItemString(retval, "caIssuers", obj);
1615 Py_DECREF(obj);
1616 if (result < 0) {
1617 goto fail1;
1618 }
1619 }
1620
1621 /* CDP (CRL distribution points) */
1622 obj = _get_crl_dp(certificate);
1623 if (obj == NULL) {
1624 goto fail1;
1625 } else if (obj != Py_None) {
1626 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1627 Py_DECREF(obj);
1628 if (result < 0) {
1629 goto fail1;
1630 }
1631 }
1632
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001633 BIO_free(biobuf);
1634 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001635
1636 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001637 if (biobuf != NULL)
1638 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001639 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001640 Py_XDECREF(retval);
1641 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001642}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001643
Christian Heimes9a5395a2013-06-17 15:44:12 +02001644static PyObject *
1645_certificate_to_der(X509 *certificate)
1646{
1647 unsigned char *bytes_buf = NULL;
1648 int len;
1649 PyObject *retval;
1650
1651 bytes_buf = NULL;
1652 len = i2d_X509(certificate, &bytes_buf);
1653 if (len < 0) {
1654 _setSSLError(NULL, 0, __FILE__, __LINE__);
1655 return NULL;
1656 }
1657 /* this is actually an immutable bytes sequence */
1658 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1659 OPENSSL_free(bytes_buf);
1660 return retval;
1661}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001662
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001663/*[clinic input]
1664_ssl._test_decode_cert
1665 path: object(converter="PyUnicode_FSConverter")
1666 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001667
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001668[clinic start generated code]*/
1669
1670static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001671_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1672/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001673{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001674 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001675 X509 *x=NULL;
1676 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001677
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001678 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1679 PyErr_SetString(PySSLErrorObject,
1680 "Can't malloc memory to read file");
1681 goto fail0;
1682 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001683
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001684 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001685 PyErr_SetString(PySSLErrorObject,
1686 "Can't open file");
1687 goto fail0;
1688 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001689
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001690 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1691 if (x == NULL) {
1692 PyErr_SetString(PySSLErrorObject,
1693 "Error decoding PEM-encoded file");
1694 goto fail0;
1695 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001696
Antoine Pitroufb046912010-11-09 20:21:19 +00001697 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001698 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001699
1700 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001701 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001702 if (cert != NULL) BIO_free(cert);
1703 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001704}
1705
1706
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001707/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001708_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001709 der as binary_mode: bool = False
1710 /
1711
1712Returns the certificate for the peer.
1713
1714If no certificate was provided, returns None. If a certificate was
1715provided, but not validated, returns an empty dictionary. Otherwise
1716returns a dict containing information about the peer certificate.
1717
1718If the optional argument is True, returns a DER-encoded copy of the
1719peer certificate, or None if no certificate was provided. This will
1720return the certificate even if it wasn't validated.
1721[clinic start generated code]*/
1722
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001723static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001724_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1725/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001726{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001727 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001728 X509 *peer_cert;
1729 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001730
Christian Heimes66dc33b2017-05-23 16:02:02 -07001731 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001732 PyErr_SetString(PyExc_ValueError,
1733 "handshake not done yet");
1734 return NULL;
1735 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001736 peer_cert = SSL_get_peer_certificate(self->ssl);
1737 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001738 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001739
Antoine Pitrou721738f2012-08-15 23:20:39 +02001740 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001741 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001742 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001743 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001744 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001745 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001746 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001747 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001748 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001749 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001750 X509_free(peer_cert);
1751 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001752}
1753
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001754static PyObject *
1755cipher_to_tuple(const SSL_CIPHER *cipher)
1756{
1757 const char *cipher_name, *cipher_protocol;
1758 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001759 if (retval == NULL)
1760 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001761
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001762 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001763 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001764 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001765 PyTuple_SET_ITEM(retval, 0, Py_None);
1766 } else {
1767 v = PyUnicode_FromString(cipher_name);
1768 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001769 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001770 PyTuple_SET_ITEM(retval, 0, v);
1771 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001772
1773 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001774 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001775 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001776 PyTuple_SET_ITEM(retval, 1, Py_None);
1777 } else {
1778 v = PyUnicode_FromString(cipher_protocol);
1779 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001780 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001781 PyTuple_SET_ITEM(retval, 1, v);
1782 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001783
1784 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001785 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001786 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001787 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001788
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001789 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001790
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001791 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001792 Py_DECREF(retval);
1793 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001794}
1795
Christian Heimes25bfcd52016-09-06 00:04:45 +02001796#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1797static PyObject *
1798cipher_to_dict(const SSL_CIPHER *cipher)
1799{
1800 const char *cipher_name, *cipher_protocol;
1801
1802 unsigned long cipher_id;
1803 int alg_bits, strength_bits, len;
1804 char buf[512] = {0};
1805#if OPENSSL_VERSION_1_1
1806 int aead, nid;
1807 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1808#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001809
1810 /* can be NULL */
1811 cipher_name = SSL_CIPHER_get_name(cipher);
1812 cipher_protocol = SSL_CIPHER_get_version(cipher);
1813 cipher_id = SSL_CIPHER_get_id(cipher);
1814 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001815 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1816 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001817 if (len > 1 && buf[len-1] == '\n')
1818 buf[len-1] = '\0';
1819 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1820
1821#if OPENSSL_VERSION_1_1
1822 aead = SSL_CIPHER_is_aead(cipher);
1823 nid = SSL_CIPHER_get_cipher_nid(cipher);
1824 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1825 nid = SSL_CIPHER_get_digest_nid(cipher);
1826 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1827 nid = SSL_CIPHER_get_kx_nid(cipher);
1828 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1829 nid = SSL_CIPHER_get_auth_nid(cipher);
1830 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1831#endif
1832
Victor Stinner410b9882016-09-12 12:00:23 +02001833 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001834 "{sksssssssisi"
1835#if OPENSSL_VERSION_1_1
1836 "sOssssssss"
1837#endif
1838 "}",
1839 "id", cipher_id,
1840 "name", cipher_name,
1841 "protocol", cipher_protocol,
1842 "description", buf,
1843 "strength_bits", strength_bits,
1844 "alg_bits", alg_bits
1845#if OPENSSL_VERSION_1_1
1846 ,"aead", aead ? Py_True : Py_False,
1847 "symmetric", skcipher,
1848 "digest", digest,
1849 "kea", kx,
1850 "auth", auth
1851#endif
1852 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001853}
1854#endif
1855
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001856/*[clinic input]
1857_ssl._SSLSocket.shared_ciphers
1858[clinic start generated code]*/
1859
1860static PyObject *
1861_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1862/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001863{
1864 STACK_OF(SSL_CIPHER) *ciphers;
1865 int i;
1866 PyObject *res;
1867
Christian Heimes598894f2016-09-05 23:19:05 +02001868 ciphers = SSL_get_ciphers(self->ssl);
1869 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001870 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001871 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1872 if (!res)
1873 return NULL;
1874 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1875 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1876 if (!tup) {
1877 Py_DECREF(res);
1878 return NULL;
1879 }
1880 PyList_SET_ITEM(res, i, tup);
1881 }
1882 return res;
1883}
1884
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001885/*[clinic input]
1886_ssl._SSLSocket.cipher
1887[clinic start generated code]*/
1888
1889static PyObject *
1890_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1891/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001892{
1893 const SSL_CIPHER *current;
1894
1895 if (self->ssl == NULL)
1896 Py_RETURN_NONE;
1897 current = SSL_get_current_cipher(self->ssl);
1898 if (current == NULL)
1899 Py_RETURN_NONE;
1900 return cipher_to_tuple(current);
1901}
1902
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001903/*[clinic input]
1904_ssl._SSLSocket.version
1905[clinic start generated code]*/
1906
1907static PyObject *
1908_ssl__SSLSocket_version_impl(PySSLSocket *self)
1909/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001910{
1911 const char *version;
1912
1913 if (self->ssl == NULL)
1914 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001915 if (!SSL_is_init_finished(self->ssl)) {
1916 /* handshake not finished */
1917 Py_RETURN_NONE;
1918 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001919 version = SSL_get_version(self->ssl);
1920 if (!strcmp(version, "unknown"))
1921 Py_RETURN_NONE;
1922 return PyUnicode_FromString(version);
1923}
1924
Christian Heimes6cdb7952018-02-24 22:12:40 +01001925#ifdef HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001926/*[clinic input]
1927_ssl._SSLSocket.selected_npn_protocol
1928[clinic start generated code]*/
1929
1930static PyObject *
1931_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1932/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1933{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001934 const unsigned char *out;
1935 unsigned int outlen;
1936
Victor Stinner4569cd52013-06-23 14:58:43 +02001937 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001938 &out, &outlen);
1939
1940 if (out == NULL)
1941 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001942 return PyUnicode_FromStringAndSize((char *)out, outlen);
1943}
1944#endif
1945
1946#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001947/*[clinic input]
1948_ssl._SSLSocket.selected_alpn_protocol
1949[clinic start generated code]*/
1950
1951static PyObject *
1952_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1953/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1954{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001955 const unsigned char *out;
1956 unsigned int outlen;
1957
1958 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1959
1960 if (out == NULL)
1961 Py_RETURN_NONE;
1962 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001963}
1964#endif
1965
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001966/*[clinic input]
1967_ssl._SSLSocket.compression
1968[clinic start generated code]*/
1969
1970static PyObject *
1971_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1972/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1973{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001974#ifdef OPENSSL_NO_COMP
1975 Py_RETURN_NONE;
1976#else
1977 const COMP_METHOD *comp_method;
1978 const char *short_name;
1979
1980 if (self->ssl == NULL)
1981 Py_RETURN_NONE;
1982 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001983 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001984 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001985 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001986 if (short_name == NULL)
1987 Py_RETURN_NONE;
1988 return PyUnicode_DecodeFSDefault(short_name);
1989#endif
1990}
1991
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001992static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1993 Py_INCREF(self->ctx);
1994 return self->ctx;
1995}
1996
1997static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1998 void *closure) {
1999
2000 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002001#if !HAVE_SNI
2002 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2003 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002004 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002005#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002006 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002007 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002008 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002009#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002010 } else {
2011 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
2012 return -1;
2013 }
2014
2015 return 0;
2016}
2017
2018PyDoc_STRVAR(PySSL_set_context_doc,
2019"_setter_context(ctx)\n\
2020\
2021This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002022used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002023on the SSLContext to change the certificate information associated with the\n\
2024SSLSocket before the cryptographic exchange handshake messages\n");
2025
2026
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002027static PyObject *
2028PySSL_get_server_side(PySSLSocket *self, void *c)
2029{
2030 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2031}
2032
2033PyDoc_STRVAR(PySSL_get_server_side_doc,
2034"Whether this is a server-side socket.");
2035
2036static PyObject *
2037PySSL_get_server_hostname(PySSLSocket *self, void *c)
2038{
2039 if (self->server_hostname == NULL)
2040 Py_RETURN_NONE;
2041 Py_INCREF(self->server_hostname);
2042 return self->server_hostname;
2043}
2044
2045PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2046"The currently set server hostname (for SNI).");
2047
2048static PyObject *
2049PySSL_get_owner(PySSLSocket *self, void *c)
2050{
2051 PyObject *owner;
2052
2053 if (self->owner == NULL)
2054 Py_RETURN_NONE;
2055
2056 owner = PyWeakref_GetObject(self->owner);
2057 Py_INCREF(owner);
2058 return owner;
2059}
2060
2061static int
2062PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2063{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002064 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002065 if (self->owner == NULL)
2066 return -1;
2067 return 0;
2068}
2069
2070PyDoc_STRVAR(PySSL_get_owner_doc,
2071"The Python-level owner of this object.\
2072Passed as \"self\" in servername callback.");
2073
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002074
Antoine Pitrou152efa22010-05-16 18:19:27 +00002075static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002076{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002077 if (self->ssl)
2078 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002079 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002080 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002081 Py_XDECREF(self->server_hostname);
2082 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002083 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002084}
2085
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002086/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002087 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002088 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002089 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002090
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002091static int
Victor Stinner14690702015-04-06 22:46:13 +02002092PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002093{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002094 int rc;
2095#ifdef HAVE_POLL
2096 struct pollfd pollfd;
2097 _PyTime_t ms;
2098#else
2099 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002100 fd_set fds;
2101 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002102#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002103
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002104 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002105 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002106 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002107 else if (timeout < 0) {
2108 if (s->sock_timeout > 0)
2109 return SOCKET_HAS_TIMED_OUT;
2110 else
2111 return SOCKET_IS_BLOCKING;
2112 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002113
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002114 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002115 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002116 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002117
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002118 /* Prefer poll, if available, since you can poll() any fd
2119 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002120#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002121 pollfd.fd = s->sock_fd;
2122 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002123
Victor Stinner14690702015-04-06 22:46:13 +02002124 /* timeout is in seconds, poll() uses milliseconds */
2125 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002126 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002127
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002128 PySSL_BEGIN_ALLOW_THREADS
2129 rc = poll(&pollfd, 1, (int)ms);
2130 PySSL_END_ALLOW_THREADS
2131#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002132 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002133 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002134 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002135
Victor Stinner14690702015-04-06 22:46:13 +02002136 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002137
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002138 FD_ZERO(&fds);
2139 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002140
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002141 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002142 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002143 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002144 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002145 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002146 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002147 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002148 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002149#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002150
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002151 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2152 (when we are able to write or when there's something to read) */
2153 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002154}
2155
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002156/*[clinic input]
2157_ssl._SSLSocket.write
2158 b: Py_buffer
2159 /
2160
2161Writes the bytes-like object b into the SSL object.
2162
2163Returns the number of bytes written.
2164[clinic start generated code]*/
2165
2166static PyObject *
2167_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2168/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002169{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002170 int len;
2171 int sockstate;
2172 int err;
2173 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002174 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002175 _PyTime_t timeout, deadline = 0;
2176 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002177
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002178 if (sock != NULL) {
2179 if (((PyObject*)sock) == Py_None) {
2180 _setSSLError("Underlying socket connection gone",
2181 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2182 return NULL;
2183 }
2184 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002185 }
2186
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002187 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002188 PyErr_Format(PyExc_OverflowError,
2189 "string longer than %d bytes", INT_MAX);
2190 goto error;
2191 }
2192
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002193 if (sock != NULL) {
2194 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002195 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002196 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2197 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2198 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002199
Victor Stinner14690702015-04-06 22:46:13 +02002200 timeout = GET_SOCKET_TIMEOUT(sock);
2201 has_timeout = (timeout > 0);
2202 if (has_timeout)
2203 deadline = _PyTime_GetMonotonicClock() + timeout;
2204
2205 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002206 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002207 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002208 "The write operation timed out");
2209 goto error;
2210 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2211 PyErr_SetString(PySSLErrorObject,
2212 "Underlying socket has been closed.");
2213 goto error;
2214 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2215 PyErr_SetString(PySSLErrorObject,
2216 "Underlying socket too large for select().");
2217 goto error;
2218 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002219
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002220 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002221 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002222 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002223 _PySSL_UPDATE_ERRNO_IF(len <= 0, self, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002224 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07002225 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002226
2227 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002228 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002229
Victor Stinner14690702015-04-06 22:46:13 +02002230 if (has_timeout)
2231 timeout = deadline - _PyTime_GetMonotonicClock();
2232
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002233 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002234 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002235 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002236 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002237 } else {
2238 sockstate = SOCKET_OPERATION_OK;
2239 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002240
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002241 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002242 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002243 "The write operation timed out");
2244 goto error;
2245 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2246 PyErr_SetString(PySSLErrorObject,
2247 "Underlying socket has been closed.");
2248 goto error;
2249 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2250 break;
2251 }
2252 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002253
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002254 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002255 if (len > 0)
2256 return PyLong_FromLong(len);
2257 else
2258 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002259
2260error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002261 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002262 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002263}
2264
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002265/*[clinic input]
2266_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002267
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002268Returns the number of already decrypted bytes available for read, pending on the connection.
2269[clinic start generated code]*/
2270
2271static PyObject *
2272_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2273/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002274{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002275 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002276
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002277 PySSL_BEGIN_ALLOW_THREADS
2278 count = SSL_pending(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002279 _PySSL_UPDATE_ERRNO_IF(count < 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002280 PySSL_END_ALLOW_THREADS
2281 if (count < 0)
2282 return PySSL_SetError(self, count, __FILE__, __LINE__);
2283 else
2284 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002285}
2286
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002287/*[clinic input]
2288_ssl._SSLSocket.read
2289 size as len: int
2290 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002291 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002292 ]
2293 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002294
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002295Read up to size bytes from the SSL socket.
2296[clinic start generated code]*/
2297
2298static PyObject *
2299_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2300 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002301/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002302{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002303 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002304 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002305 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002306 int sockstate;
2307 int err;
2308 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002309 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002310 _PyTime_t timeout, deadline = 0;
2311 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002312
Martin Panter5503d472016-03-27 05:35:19 +00002313 if (!group_right_1 && len < 0) {
2314 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2315 return NULL;
2316 }
2317
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002318 if (sock != NULL) {
2319 if (((PyObject*)sock) == Py_None) {
2320 _setSSLError("Underlying socket connection gone",
2321 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2322 return NULL;
2323 }
2324 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002325 }
2326
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002327 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002328 dest = PyBytes_FromStringAndSize(NULL, len);
2329 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002330 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002331 if (len == 0) {
2332 Py_XDECREF(sock);
2333 return dest;
2334 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002335 mem = PyBytes_AS_STRING(dest);
2336 }
2337 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002338 mem = buffer->buf;
2339 if (len <= 0 || len > buffer->len) {
2340 len = (int) buffer->len;
2341 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002342 PyErr_SetString(PyExc_OverflowError,
2343 "maximum length can't fit in a C 'int'");
2344 goto error;
2345 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002346 if (len == 0) {
2347 count = 0;
2348 goto done;
2349 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002350 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002351 }
2352
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002353 if (sock != NULL) {
2354 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002355 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002356 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2357 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2358 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002359
Victor Stinner14690702015-04-06 22:46:13 +02002360 timeout = GET_SOCKET_TIMEOUT(sock);
2361 has_timeout = (timeout > 0);
2362 if (has_timeout)
2363 deadline = _PyTime_GetMonotonicClock() + timeout;
2364
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002365 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002366 PySSL_BEGIN_ALLOW_THREADS
2367 count = SSL_read(self->ssl, mem, len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002368 _PySSL_UPDATE_ERRNO_IF(count <= 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002369 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002370
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002371 if (PyErr_CheckSignals())
2372 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002373
Victor Stinner14690702015-04-06 22:46:13 +02002374 if (has_timeout)
2375 timeout = deadline - _PyTime_GetMonotonicClock();
2376
Steve Dowere6eb48c2017-09-08 15:16:15 -07002377 err = self->ssl_errno;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002378 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002379 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002380 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002381 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002382 } else if (err == SSL_ERROR_ZERO_RETURN &&
2383 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002384 {
2385 count = 0;
2386 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002387 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002388 else
2389 sockstate = SOCKET_OPERATION_OK;
2390
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002391 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002392 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002393 "The read operation timed out");
2394 goto error;
2395 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2396 break;
2397 }
2398 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002399
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002400 if (count <= 0) {
2401 PySSL_SetError(self, count, __FILE__, __LINE__);
2402 goto error;
2403 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002404
2405done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002406 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002407 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002408 _PyBytes_Resize(&dest, count);
2409 return dest;
2410 }
2411 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002412 return PyLong_FromLong(count);
2413 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002414
2415error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002416 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002417 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002418 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002419 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002420}
2421
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002422/*[clinic input]
2423_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002424
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002425Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002426[clinic start generated code]*/
2427
2428static PyObject *
2429_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002430/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002431{
Steve Dowere6eb48c2017-09-08 15:16:15 -07002432 int err, sockstate, nonblocking;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002433 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002434 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002435 _PyTime_t timeout, deadline = 0;
2436 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002437
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002438 if (sock != NULL) {
2439 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002440 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002441 _setSSLError("Underlying socket connection gone",
2442 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2443 return NULL;
2444 }
2445 Py_INCREF(sock);
2446
2447 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002448 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002449 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2450 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002451 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002452
Victor Stinner14690702015-04-06 22:46:13 +02002453 timeout = GET_SOCKET_TIMEOUT(sock);
2454 has_timeout = (timeout > 0);
2455 if (has_timeout)
2456 deadline = _PyTime_GetMonotonicClock() + timeout;
2457
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002458 while (1) {
2459 PySSL_BEGIN_ALLOW_THREADS
2460 /* Disable read-ahead so that unwrap can work correctly.
2461 * Otherwise OpenSSL might read in too much data,
2462 * eating clear text data that happens to be
2463 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002464 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002465 * function is used and the shutdown_seen_zero != 0
2466 * condition is met.
2467 */
2468 if (self->shutdown_seen_zero)
2469 SSL_set_read_ahead(self->ssl, 0);
2470 err = SSL_shutdown(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002471 _PySSL_UPDATE_ERRNO_IF(err < 0, self, err);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002472 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002473
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002474 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2475 if (err > 0)
2476 break;
2477 if (err == 0) {
2478 /* Don't loop endlessly; instead preserve legacy
2479 behaviour of trying SSL_shutdown() only twice.
2480 This looks necessary for OpenSSL < 0.9.8m */
2481 if (++zeros > 1)
2482 break;
2483 /* Shutdown was sent, now try receiving */
2484 self->shutdown_seen_zero = 1;
2485 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002486 }
2487
Victor Stinner14690702015-04-06 22:46:13 +02002488 if (has_timeout)
2489 timeout = deadline - _PyTime_GetMonotonicClock();
2490
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002491 /* Possibly retry shutdown until timeout or failure */
Steve Dowere6eb48c2017-09-08 15:16:15 -07002492 _PySSL_UPDATE_ERRNO(self, err);
2493 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002494 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002495 else if (self->ssl_errno == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002496 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002497 else
2498 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002499
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002500 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowere6eb48c2017-09-08 15:16:15 -07002501 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002502 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002503 "The read operation timed out");
2504 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002505 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002506 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002507 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002508 }
2509 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2510 PyErr_SetString(PySSLErrorObject,
2511 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002512 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002513 }
2514 else if (sockstate != SOCKET_OPERATION_OK)
2515 /* Retain the SSL error code */
2516 break;
2517 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002518
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002519 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002520 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002521 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002522 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002523 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002524 /* It's already INCREF'ed */
2525 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002526 else
2527 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002528
2529error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002530 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002531 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002532}
2533
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002534/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002535_ssl._SSLSocket.get_channel_binding
2536 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002537
Christian Heimes141c5e82018-02-24 21:10:57 +01002538Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002539
Christian Heimes141c5e82018-02-24 21:10:57 +01002540Raise ValueError if the requested `cb_type` is not supported. Return bytes
2541of the data or None if the data is not available (e.g. before the handshake).
2542Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002543[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002544
Antoine Pitroud6494802011-07-21 01:11:30 +02002545static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002546_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2547 const char *cb_type)
2548/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002549{
Antoine Pitroud6494802011-07-21 01:11:30 +02002550 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002551 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002552
Christian Heimes141c5e82018-02-24 21:10:57 +01002553 if (strcmp(cb_type, "tls-unique") == 0) {
2554 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2555 /* if session is resumed XOR we are the client */
2556 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2557 }
2558 else {
2559 /* if a new session XOR we are the server */
2560 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2561 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002562 }
2563 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002564 PyErr_Format(
2565 PyExc_ValueError,
2566 "'%s' channel binding type not implemented",
2567 cb_type
2568 );
2569 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002570 }
2571
2572 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002573 if (len == 0)
2574 Py_RETURN_NONE;
2575
Christian Heimes141c5e82018-02-24 21:10:57 +01002576 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002577}
2578
Christian Heimes99a65702016-09-10 23:44:53 +02002579#ifdef OPENSSL_VERSION_1_1
2580
2581static SSL_SESSION*
2582_ssl_session_dup(SSL_SESSION *session) {
2583 SSL_SESSION *newsession = NULL;
2584 int slen;
2585 unsigned char *senc = NULL, *p;
2586 const unsigned char *const_p;
2587
2588 if (session == NULL) {
2589 PyErr_SetString(PyExc_ValueError, "Invalid session");
2590 goto error;
2591 }
2592
2593 /* get length */
2594 slen = i2d_SSL_SESSION(session, NULL);
2595 if (slen == 0 || slen > 0xFF00) {
2596 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2597 goto error;
2598 }
2599 if ((senc = PyMem_Malloc(slen)) == NULL) {
2600 PyErr_NoMemory();
2601 goto error;
2602 }
2603 p = senc;
2604 if (!i2d_SSL_SESSION(session, &p)) {
2605 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2606 goto error;
2607 }
2608 const_p = senc;
2609 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2610 if (session == NULL) {
2611 goto error;
2612 }
2613 PyMem_Free(senc);
2614 return newsession;
2615 error:
2616 if (senc != NULL) {
2617 PyMem_Free(senc);
2618 }
2619 return NULL;
2620}
2621#endif
2622
2623static PyObject *
2624PySSL_get_session(PySSLSocket *self, void *closure) {
2625 /* get_session can return sessions from a server-side connection,
2626 * it does not check for handshake done or client socket. */
2627 PySSLSession *pysess;
2628 SSL_SESSION *session;
2629
2630#ifdef OPENSSL_VERSION_1_1
2631 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2632 * https://github.com/openssl/openssl/issues/1550 */
2633 session = SSL_get0_session(self->ssl); /* borrowed reference */
2634 if (session == NULL) {
2635 Py_RETURN_NONE;
2636 }
2637 if ((session = _ssl_session_dup(session)) == NULL) {
2638 return NULL;
2639 }
2640#else
2641 session = SSL_get1_session(self->ssl);
2642 if (session == NULL) {
2643 Py_RETURN_NONE;
2644 }
2645#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002646 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002647 if (pysess == NULL) {
2648 SSL_SESSION_free(session);
2649 return NULL;
2650 }
2651
2652 assert(self->ctx);
2653 pysess->ctx = self->ctx;
2654 Py_INCREF(pysess->ctx);
2655 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002656 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002657 return (PyObject *)pysess;
2658}
2659
2660static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2661 void *closure)
2662 {
2663 PySSLSession *pysess;
2664#ifdef OPENSSL_VERSION_1_1
2665 SSL_SESSION *session;
2666#endif
2667 int result;
2668
2669 if (!PySSLSession_Check(value)) {
2670 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2671 return -1;
2672 }
2673 pysess = (PySSLSession *)value;
2674
2675 if (self->ctx->ctx != pysess->ctx->ctx) {
2676 PyErr_SetString(PyExc_ValueError,
2677 "Session refers to a different SSLContext.");
2678 return -1;
2679 }
2680 if (self->socket_type != PY_SSL_CLIENT) {
2681 PyErr_SetString(PyExc_ValueError,
2682 "Cannot set session for server-side SSLSocket.");
2683 return -1;
2684 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002685 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002686 PyErr_SetString(PyExc_ValueError,
2687 "Cannot set session after handshake.");
2688 return -1;
2689 }
2690#ifdef OPENSSL_VERSION_1_1
2691 /* duplicate session */
2692 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2693 return -1;
2694 }
2695 result = SSL_set_session(self->ssl, session);
2696 /* free duplicate, SSL_set_session() bumps ref count */
2697 SSL_SESSION_free(session);
2698#else
2699 result = SSL_set_session(self->ssl, pysess->session);
2700#endif
2701 if (result == 0) {
2702 _setSSLError(NULL, 0, __FILE__, __LINE__);
2703 return -1;
2704 }
2705 return 0;
2706}
2707
2708PyDoc_STRVAR(PySSL_set_session_doc,
2709"_setter_session(session)\n\
2710\
2711Get / set SSLSession.");
2712
2713static PyObject *
2714PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2715 if (SSL_session_reused(self->ssl)) {
2716 Py_RETURN_TRUE;
2717 } else {
2718 Py_RETURN_FALSE;
2719 }
2720}
2721
2722PyDoc_STRVAR(PySSL_get_session_reused_doc,
2723"Was the client session reused during handshake?");
2724
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002725static PyGetSetDef ssl_getsetlist[] = {
2726 {"context", (getter) PySSL_get_context,
2727 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002728 {"server_side", (getter) PySSL_get_server_side, NULL,
2729 PySSL_get_server_side_doc},
2730 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2731 PySSL_get_server_hostname_doc},
2732 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2733 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002734 {"session", (getter) PySSL_get_session,
2735 (setter) PySSL_set_session, PySSL_set_session_doc},
2736 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2737 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002738 {NULL}, /* sentinel */
2739};
2740
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002741static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002742 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2743 _SSL__SSLSOCKET_WRITE_METHODDEF
2744 _SSL__SSLSOCKET_READ_METHODDEF
2745 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002746 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2747 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002748 _SSL__SSLSOCKET_CIPHER_METHODDEF
2749 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2750 _SSL__SSLSOCKET_VERSION_METHODDEF
2751 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2752 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2753 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2754 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002755 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002756};
2757
Antoine Pitrou152efa22010-05-16 18:19:27 +00002758static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002759 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002760 "_ssl._SSLSocket", /*tp_name*/
2761 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002762 0, /*tp_itemsize*/
2763 /* methods */
2764 (destructor)PySSL_dealloc, /*tp_dealloc*/
2765 0, /*tp_print*/
2766 0, /*tp_getattr*/
2767 0, /*tp_setattr*/
2768 0, /*tp_reserved*/
2769 0, /*tp_repr*/
2770 0, /*tp_as_number*/
2771 0, /*tp_as_sequence*/
2772 0, /*tp_as_mapping*/
2773 0, /*tp_hash*/
2774 0, /*tp_call*/
2775 0, /*tp_str*/
2776 0, /*tp_getattro*/
2777 0, /*tp_setattro*/
2778 0, /*tp_as_buffer*/
2779 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2780 0, /*tp_doc*/
2781 0, /*tp_traverse*/
2782 0, /*tp_clear*/
2783 0, /*tp_richcompare*/
2784 0, /*tp_weaklistoffset*/
2785 0, /*tp_iter*/
2786 0, /*tp_iternext*/
2787 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002788 0, /*tp_members*/
2789 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002790};
2791
Antoine Pitrou152efa22010-05-16 18:19:27 +00002792
2793/*
2794 * _SSLContext objects
2795 */
2796
Christian Heimes5fe668c2016-09-12 00:01:11 +02002797static int
2798_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2799{
2800 int mode;
2801 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2802
2803 switch(n) {
2804 case PY_SSL_CERT_NONE:
2805 mode = SSL_VERIFY_NONE;
2806 break;
2807 case PY_SSL_CERT_OPTIONAL:
2808 mode = SSL_VERIFY_PEER;
2809 break;
2810 case PY_SSL_CERT_REQUIRED:
2811 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2812 break;
2813 default:
2814 PyErr_SetString(PyExc_ValueError,
2815 "invalid value for verify_mode");
2816 return -1;
2817 }
2818 /* keep current verify cb */
2819 verify_cb = SSL_CTX_get_verify_callback(ctx);
2820 SSL_CTX_set_verify(ctx, mode, verify_cb);
2821 return 0;
2822}
2823
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002824/*[clinic input]
2825@classmethod
2826_ssl._SSLContext.__new__
2827 protocol as proto_version: int
2828 /
2829[clinic start generated code]*/
2830
Antoine Pitrou152efa22010-05-16 18:19:27 +00002831static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002832_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2833/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002834{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002835 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002836 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002837 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002838 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002839 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002840#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002841 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002842#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002843
Antoine Pitrou152efa22010-05-16 18:19:27 +00002844 PySSL_BEGIN_ALLOW_THREADS
2845 if (proto_version == PY_SSL_VERSION_TLS1)
2846 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002847#if HAVE_TLSv1_2
2848 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2849 ctx = SSL_CTX_new(TLSv1_1_method());
2850 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2851 ctx = SSL_CTX_new(TLSv1_2_method());
2852#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002853#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002854 else if (proto_version == PY_SSL_VERSION_SSL3)
2855 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002856#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002857#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002858 else if (proto_version == PY_SSL_VERSION_SSL2)
2859 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002860#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002861 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002862 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002863 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2864 ctx = SSL_CTX_new(TLS_client_method());
2865 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2866 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002867 else
2868 proto_version = -1;
2869 PySSL_END_ALLOW_THREADS
2870
2871 if (proto_version == -1) {
2872 PyErr_SetString(PyExc_ValueError,
2873 "invalid protocol version");
2874 return NULL;
2875 }
2876 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002877 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002878 return NULL;
2879 }
2880
2881 assert(type != NULL && type->tp_alloc != NULL);
2882 self = (PySSLContext *) type->tp_alloc(type, 0);
2883 if (self == NULL) {
2884 SSL_CTX_free(ctx);
2885 return NULL;
2886 }
2887 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002888 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01002889 self->protocol = proto_version;
Christian Heimes6cdb7952018-02-24 22:12:40 +01002890#ifdef HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02002891 self->npn_protocols = NULL;
2892#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002893#ifdef HAVE_ALPN
2894 self->alpn_protocols = NULL;
2895#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002896#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01002897 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002898#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002899 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002900 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2901 self->check_hostname = 1;
2902 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2903 Py_DECREF(self);
2904 return NULL;
2905 }
2906 } else {
2907 self->check_hostname = 0;
2908 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2909 Py_DECREF(self);
2910 return NULL;
2911 }
2912 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002913 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002914 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2915 if (proto_version != PY_SSL_VERSION_SSL2)
2916 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002917 if (proto_version != PY_SSL_VERSION_SSL3)
2918 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002919 /* Minimal security flags for server and client side context.
2920 * Client sockets ignore server-side parameters. */
2921#ifdef SSL_OP_NO_COMPRESSION
2922 options |= SSL_OP_NO_COMPRESSION;
2923#endif
2924#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2925 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2926#endif
2927#ifdef SSL_OP_SINGLE_DH_USE
2928 options |= SSL_OP_SINGLE_DH_USE;
2929#endif
2930#ifdef SSL_OP_SINGLE_ECDH_USE
2931 options |= SSL_OP_SINGLE_ECDH_USE;
2932#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002933 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002934
Semen Zhydenko1295e112017-10-15 21:28:31 +02002935 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02002936 * It's far from perfect but gives users a better head start. */
2937 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01002938#if PY_SSL_DEFAULT_CIPHERS == 2
2939 /* stick to OpenSSL's default settings */
2940 result = 1;
2941#else
2942 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
2943#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02002944 } else {
2945 /* SSLv2 needs MD5 */
2946 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2947 }
2948 if (result == 0) {
2949 Py_DECREF(self);
2950 ERR_clear_error();
2951 PyErr_SetString(PySSLErrorObject,
2952 "No cipher can be selected.");
2953 return NULL;
2954 }
2955
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002956#if defined(SSL_MODE_RELEASE_BUFFERS)
2957 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2958 usage for no cost at all. However, don't do this for OpenSSL versions
2959 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2960 2014-0198. I can't find exactly which beta fixed this CVE, so be
2961 conservative and assume it wasn't fixed until release. We do this check
2962 at runtime to avoid problems from the dynamic linker.
2963 See #25672 for more on this. */
2964 libver = SSLeay();
2965 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2966 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2967 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2968 }
2969#endif
2970
2971
Donald Stufft8ae264c2017-03-02 11:45:29 -05002972#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002973 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2974 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002975 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2976 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002977#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002978 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2979#else
2980 {
2981 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2982 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2983 EC_KEY_free(key);
2984 }
2985#endif
2986#endif
2987
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002988#define SID_CTX "Python"
2989 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2990 sizeof(SID_CTX));
2991#undef SID_CTX
2992
Christian Heimes61d478c2018-01-27 15:51:38 +01002993 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002994#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01002995 /* Improve trust chain building when cross-signed intermediate
2996 certificates are present. See https://bugs.python.org/issue23476. */
2997 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002998#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01002999 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003000
Antoine Pitrou152efa22010-05-16 18:19:27 +00003001 return (PyObject *)self;
3002}
3003
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003004static int
3005context_traverse(PySSLContext *self, visitproc visit, void *arg)
3006{
3007#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003008 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003009#endif
3010 return 0;
3011}
3012
3013static int
3014context_clear(PySSLContext *self)
3015{
3016#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003017 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003018#endif
3019 return 0;
3020}
3021
Antoine Pitrou152efa22010-05-16 18:19:27 +00003022static void
3023context_dealloc(PySSLContext *self)
3024{
INADA Naokia6296d32017-08-24 14:55:17 +09003025 /* bpo-31095: UnTrack is needed before calling any callbacks */
3026 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003027 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003028 SSL_CTX_free(self->ctx);
Christian Heimes6cdb7952018-02-24 22:12:40 +01003029#ifdef HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003030 PyMem_FREE(self->npn_protocols);
3031#endif
3032#ifdef HAVE_ALPN
3033 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003034#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003035 Py_TYPE(self)->tp_free(self);
3036}
3037
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003038/*[clinic input]
3039_ssl._SSLContext.set_ciphers
3040 cipherlist: str
3041 /
3042[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003043
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003044static PyObject *
3045_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3046/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3047{
3048 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003049 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003050 /* Clearing the error queue is necessary on some OpenSSL versions,
3051 otherwise the error will be reported again when another SSL call
3052 is done. */
3053 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003054 PyErr_SetString(PySSLErrorObject,
3055 "No cipher can be selected.");
3056 return NULL;
3057 }
3058 Py_RETURN_NONE;
3059}
3060
Christian Heimes25bfcd52016-09-06 00:04:45 +02003061#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3062/*[clinic input]
3063_ssl._SSLContext.get_ciphers
3064[clinic start generated code]*/
3065
3066static PyObject *
3067_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3068/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3069{
3070 SSL *ssl = NULL;
3071 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003072 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003073 int i=0;
3074 PyObject *result = NULL, *dct;
3075
3076 ssl = SSL_new(self->ctx);
3077 if (ssl == NULL) {
3078 _setSSLError(NULL, 0, __FILE__, __LINE__);
3079 goto exit;
3080 }
3081 sk = SSL_get_ciphers(ssl);
3082
3083 result = PyList_New(sk_SSL_CIPHER_num(sk));
3084 if (result == NULL) {
3085 goto exit;
3086 }
3087
3088 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3089 cipher = sk_SSL_CIPHER_value(sk, i);
3090 dct = cipher_to_dict(cipher);
3091 if (dct == NULL) {
3092 Py_CLEAR(result);
3093 goto exit;
3094 }
3095 PyList_SET_ITEM(result, i, dct);
3096 }
3097
3098 exit:
3099 if (ssl != NULL)
3100 SSL_free(ssl);
3101 return result;
3102
3103}
3104#endif
3105
3106
Christian Heimes6cdb7952018-02-24 22:12:40 +01003107#if defined(HAVE_NPN) || defined(HAVE_ALPN)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003108static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003109do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3110 const unsigned char *server_protocols, unsigned int server_protocols_len,
3111 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003112{
Benjamin Peterson88615022015-01-23 17:30:26 -05003113 int ret;
3114 if (client_protocols == NULL) {
3115 client_protocols = (unsigned char *)"";
3116 client_protocols_len = 0;
3117 }
3118 if (server_protocols == NULL) {
3119 server_protocols = (unsigned char *)"";
3120 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003121 }
3122
Benjamin Peterson88615022015-01-23 17:30:26 -05003123 ret = SSL_select_next_proto(out, outlen,
3124 server_protocols, server_protocols_len,
3125 client_protocols, client_protocols_len);
3126 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3127 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003128
3129 return SSL_TLSEXT_ERR_OK;
3130}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003131#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003132
Christian Heimes6cdb7952018-02-24 22:12:40 +01003133#ifdef HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003134/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3135static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003136_advertiseNPN_cb(SSL *s,
3137 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003138 void *args)
3139{
3140 PySSLContext *ssl_ctx = (PySSLContext *) args;
3141
3142 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003143 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003144 *len = 0;
3145 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003146 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003147 *len = ssl_ctx->npn_protocols_len;
3148 }
3149
3150 return SSL_TLSEXT_ERR_OK;
3151}
3152/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3153static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003154_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003155 unsigned char **out, unsigned char *outlen,
3156 const unsigned char *server, unsigned int server_len,
3157 void *args)
3158{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003159 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003160 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003161 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003162}
3163#endif
3164
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003165/*[clinic input]
3166_ssl._SSLContext._set_npn_protocols
3167 protos: Py_buffer
3168 /
3169[clinic start generated code]*/
3170
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003171static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003172_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3173 Py_buffer *protos)
3174/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003175{
Christian Heimes6cdb7952018-02-24 22:12:40 +01003176#ifdef HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003177 PyMem_Free(self->npn_protocols);
3178 self->npn_protocols = PyMem_Malloc(protos->len);
3179 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003180 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003181 memcpy(self->npn_protocols, protos->buf, protos->len);
3182 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003183
3184 /* set both server and client callbacks, because the context can
3185 * be used to create both types of sockets */
3186 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3187 _advertiseNPN_cb,
3188 self);
3189 SSL_CTX_set_next_proto_select_cb(self->ctx,
3190 _selectNPN_cb,
3191 self);
3192
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003193 Py_RETURN_NONE;
3194#else
3195 PyErr_SetString(PyExc_NotImplementedError,
3196 "The NPN extension requires OpenSSL 1.0.1 or later.");
3197 return NULL;
3198#endif
3199}
3200
Benjamin Petersoncca27322015-01-23 16:35:37 -05003201#ifdef HAVE_ALPN
3202static int
3203_selectALPN_cb(SSL *s,
3204 const unsigned char **out, unsigned char *outlen,
3205 const unsigned char *client_protocols, unsigned int client_protocols_len,
3206 void *args)
3207{
3208 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003209 return do_protocol_selection(1, (unsigned char **)out, outlen,
3210 ctx->alpn_protocols, ctx->alpn_protocols_len,
3211 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003212}
3213#endif
3214
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003215/*[clinic input]
3216_ssl._SSLContext._set_alpn_protocols
3217 protos: Py_buffer
3218 /
3219[clinic start generated code]*/
3220
Benjamin Petersoncca27322015-01-23 16:35:37 -05003221static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003222_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3223 Py_buffer *protos)
3224/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003225{
3226#ifdef HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003227 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003228 PyErr_Format(PyExc_OverflowError,
3229 "protocols longer than %d bytes", UINT_MAX);
3230 return NULL;
3231 }
3232
Benjamin Petersoncca27322015-01-23 16:35:37 -05003233 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003234 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003235 if (!self->alpn_protocols)
3236 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003237 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003238 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003239
3240 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3241 return PyErr_NoMemory();
3242 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3243
Benjamin Petersoncca27322015-01-23 16:35:37 -05003244 Py_RETURN_NONE;
3245#else
3246 PyErr_SetString(PyExc_NotImplementedError,
3247 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3248 return NULL;
3249#endif
3250}
3251
Antoine Pitrou152efa22010-05-16 18:19:27 +00003252static PyObject *
3253get_verify_mode(PySSLContext *self, void *c)
3254{
3255 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3256 case SSL_VERIFY_NONE:
3257 return PyLong_FromLong(PY_SSL_CERT_NONE);
3258 case SSL_VERIFY_PEER:
3259 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3260 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3261 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3262 }
3263 PyErr_SetString(PySSLErrorObject,
3264 "invalid return value from SSL_CTX_get_verify_mode");
3265 return NULL;
3266}
3267
3268static int
3269set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3270{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003271 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003272 if (!PyArg_Parse(arg, "i", &n))
3273 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003274 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003275 PyErr_SetString(PyExc_ValueError,
3276 "Cannot set verify_mode to CERT_NONE when "
3277 "check_hostname is enabled.");
3278 return -1;
3279 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003280 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003281}
3282
3283static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003284get_verify_flags(PySSLContext *self, void *c)
3285{
Christian Heimes598894f2016-09-05 23:19:05 +02003286 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003287 unsigned long flags;
3288
Christian Heimes61d478c2018-01-27 15:51:38 +01003289 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003290 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003291 return PyLong_FromUnsignedLong(flags);
3292}
3293
3294static int
3295set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3296{
Christian Heimes598894f2016-09-05 23:19:05 +02003297 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003298 unsigned long new_flags, flags, set, clear;
3299
3300 if (!PyArg_Parse(arg, "k", &new_flags))
3301 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003302 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003303 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003304 clear = flags & ~new_flags;
3305 set = ~flags & new_flags;
3306 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003307 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003308 _setSSLError(NULL, 0, __FILE__, __LINE__);
3309 return -1;
3310 }
3311 }
3312 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003313 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003314 _setSSLError(NULL, 0, __FILE__, __LINE__);
3315 return -1;
3316 }
3317 }
3318 return 0;
3319}
3320
3321static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003322get_options(PySSLContext *self, void *c)
3323{
3324 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3325}
3326
3327static int
3328set_options(PySSLContext *self, PyObject *arg, void *c)
3329{
3330 long new_opts, opts, set, clear;
3331 if (!PyArg_Parse(arg, "l", &new_opts))
3332 return -1;
3333 opts = SSL_CTX_get_options(self->ctx);
3334 clear = opts & ~new_opts;
3335 set = ~opts & new_opts;
3336 if (clear) {
3337#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3338 SSL_CTX_clear_options(self->ctx, clear);
3339#else
3340 PyErr_SetString(PyExc_ValueError,
3341 "can't clear options before OpenSSL 0.9.8m");
3342 return -1;
3343#endif
3344 }
3345 if (set)
3346 SSL_CTX_set_options(self->ctx, set);
3347 return 0;
3348}
3349
Christian Heimes1aa9a752013-12-02 02:41:19 +01003350static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003351get_host_flags(PySSLContext *self, void *c)
3352{
3353 return PyLong_FromUnsignedLong(self->hostflags);
3354}
3355
3356static int
3357set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3358{
3359 X509_VERIFY_PARAM *param;
3360 unsigned int new_flags = 0;
3361
3362 if (!PyArg_Parse(arg, "I", &new_flags))
3363 return -1;
3364
3365 param = SSL_CTX_get0_param(self->ctx);
3366 self->hostflags = new_flags;
3367 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3368 return 0;
3369}
3370
3371static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003372get_check_hostname(PySSLContext *self, void *c)
3373{
3374 return PyBool_FromLong(self->check_hostname);
3375}
3376
3377static int
3378set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3379{
3380 int check_hostname;
3381 if (!PyArg_Parse(arg, "p", &check_hostname))
3382 return -1;
3383 if (check_hostname &&
3384 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003385 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
3386 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
3387 return -1;
3388 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003389 }
3390 self->check_hostname = check_hostname;
3391 return 0;
3392}
3393
Christian Heimes11a14932018-02-24 02:35:08 +01003394static PyObject *
3395get_protocol(PySSLContext *self, void *c) {
3396 return PyLong_FromLong(self->protocol);
3397}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003398
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003399typedef struct {
3400 PyThreadState *thread_state;
3401 PyObject *callable;
3402 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003403 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003404 int error;
3405} _PySSLPasswordInfo;
3406
3407static int
3408_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3409 const char *bad_type_error)
3410{
3411 /* Set the password and size fields of a _PySSLPasswordInfo struct
3412 from a unicode, bytes, or byte array object.
3413 The password field will be dynamically allocated and must be freed
3414 by the caller */
3415 PyObject *password_bytes = NULL;
3416 const char *data = NULL;
3417 Py_ssize_t size;
3418
3419 if (PyUnicode_Check(password)) {
3420 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3421 if (!password_bytes) {
3422 goto error;
3423 }
3424 data = PyBytes_AS_STRING(password_bytes);
3425 size = PyBytes_GET_SIZE(password_bytes);
3426 } else if (PyBytes_Check(password)) {
3427 data = PyBytes_AS_STRING(password);
3428 size = PyBytes_GET_SIZE(password);
3429 } else if (PyByteArray_Check(password)) {
3430 data = PyByteArray_AS_STRING(password);
3431 size = PyByteArray_GET_SIZE(password);
3432 } else {
3433 PyErr_SetString(PyExc_TypeError, bad_type_error);
3434 goto error;
3435 }
3436
Victor Stinner9ee02032013-06-23 15:08:23 +02003437 if (size > (Py_ssize_t)INT_MAX) {
3438 PyErr_Format(PyExc_ValueError,
3439 "password cannot be longer than %d bytes", INT_MAX);
3440 goto error;
3441 }
3442
Victor Stinner11ebff22013-07-07 17:07:52 +02003443 PyMem_Free(pw_info->password);
3444 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003445 if (!pw_info->password) {
3446 PyErr_SetString(PyExc_MemoryError,
3447 "unable to allocate password buffer");
3448 goto error;
3449 }
3450 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003451 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003452
3453 Py_XDECREF(password_bytes);
3454 return 1;
3455
3456error:
3457 Py_XDECREF(password_bytes);
3458 return 0;
3459}
3460
3461static int
3462_password_callback(char *buf, int size, int rwflag, void *userdata)
3463{
3464 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3465 PyObject *fn_ret = NULL;
3466
3467 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3468
3469 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003470 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003471 if (!fn_ret) {
3472 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3473 core python API, so we could use it to add a frame here */
3474 goto error;
3475 }
3476
3477 if (!_pwinfo_set(pw_info, fn_ret,
3478 "password callback must return a string")) {
3479 goto error;
3480 }
3481 Py_CLEAR(fn_ret);
3482 }
3483
3484 if (pw_info->size > size) {
3485 PyErr_Format(PyExc_ValueError,
3486 "password cannot be longer than %d bytes", size);
3487 goto error;
3488 }
3489
3490 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3491 memcpy(buf, pw_info->password, pw_info->size);
3492 return pw_info->size;
3493
3494error:
3495 Py_XDECREF(fn_ret);
3496 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3497 pw_info->error = 1;
3498 return -1;
3499}
3500
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003501/*[clinic input]
3502_ssl._SSLContext.load_cert_chain
3503 certfile: object
3504 keyfile: object = NULL
3505 password: object = NULL
3506
3507[clinic start generated code]*/
3508
Antoine Pitroub5218772010-05-21 09:56:06 +00003509static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003510_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3511 PyObject *keyfile, PyObject *password)
3512/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003513{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003514 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003515 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3516 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003517 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003518 int r;
3519
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003520 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003521 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003522 if (keyfile == Py_None)
3523 keyfile = NULL;
3524 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3525 PyErr_SetString(PyExc_TypeError,
3526 "certfile should be a valid filesystem path");
3527 return NULL;
3528 }
3529 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3530 PyErr_SetString(PyExc_TypeError,
3531 "keyfile should be a valid filesystem path");
3532 goto error;
3533 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003534 if (password && password != Py_None) {
3535 if (PyCallable_Check(password)) {
3536 pw_info.callable = password;
3537 } else if (!_pwinfo_set(&pw_info, password,
3538 "password should be a string or callable")) {
3539 goto error;
3540 }
3541 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3542 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3543 }
3544 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003545 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3546 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003547 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003548 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003549 if (pw_info.error) {
3550 ERR_clear_error();
3551 /* the password callback has already set the error information */
3552 }
3553 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003554 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003555 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003556 }
3557 else {
3558 _setSSLError(NULL, 0, __FILE__, __LINE__);
3559 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003560 goto error;
3561 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003562 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003563 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003564 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3565 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003566 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3567 Py_CLEAR(keyfile_bytes);
3568 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003569 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003570 if (pw_info.error) {
3571 ERR_clear_error();
3572 /* the password callback has already set the error information */
3573 }
3574 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003575 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003576 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003577 }
3578 else {
3579 _setSSLError(NULL, 0, __FILE__, __LINE__);
3580 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003581 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003582 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003583 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003584 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003585 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003586 if (r != 1) {
3587 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003588 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003589 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003590 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3591 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003592 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003593 Py_RETURN_NONE;
3594
3595error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003596 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3597 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003598 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003599 Py_XDECREF(keyfile_bytes);
3600 Py_XDECREF(certfile_bytes);
3601 return NULL;
3602}
3603
Christian Heimesefff7062013-11-21 03:35:02 +01003604/* internal helper function, returns -1 on error
3605 */
3606static int
3607_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3608 int filetype)
3609{
3610 BIO *biobuf = NULL;
3611 X509_STORE *store;
3612 int retval = 0, err, loaded = 0;
3613
3614 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3615
3616 if (len <= 0) {
3617 PyErr_SetString(PyExc_ValueError,
3618 "Empty certificate data");
3619 return -1;
3620 } else if (len > INT_MAX) {
3621 PyErr_SetString(PyExc_OverflowError,
3622 "Certificate data is too long.");
3623 return -1;
3624 }
3625
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003626 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003627 if (biobuf == NULL) {
3628 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3629 return -1;
3630 }
3631
3632 store = SSL_CTX_get_cert_store(self->ctx);
3633 assert(store != NULL);
3634
3635 while (1) {
3636 X509 *cert = NULL;
3637 int r;
3638
3639 if (filetype == SSL_FILETYPE_ASN1) {
3640 cert = d2i_X509_bio(biobuf, NULL);
3641 } else {
3642 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003643 SSL_CTX_get_default_passwd_cb(self->ctx),
3644 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3645 );
Christian Heimesefff7062013-11-21 03:35:02 +01003646 }
3647 if (cert == NULL) {
3648 break;
3649 }
3650 r = X509_STORE_add_cert(store, cert);
3651 X509_free(cert);
3652 if (!r) {
3653 err = ERR_peek_last_error();
3654 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3655 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3656 /* cert already in hash table, not an error */
3657 ERR_clear_error();
3658 } else {
3659 break;
3660 }
3661 }
3662 loaded++;
3663 }
3664
3665 err = ERR_peek_last_error();
3666 if ((filetype == SSL_FILETYPE_ASN1) &&
3667 (loaded > 0) &&
3668 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3669 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3670 /* EOF ASN1 file, not an error */
3671 ERR_clear_error();
3672 retval = 0;
3673 } else if ((filetype == SSL_FILETYPE_PEM) &&
3674 (loaded > 0) &&
3675 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3676 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3677 /* EOF PEM file, not an error */
3678 ERR_clear_error();
3679 retval = 0;
3680 } else {
3681 _setSSLError(NULL, 0, __FILE__, __LINE__);
3682 retval = -1;
3683 }
3684
3685 BIO_free(biobuf);
3686 return retval;
3687}
3688
3689
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003690/*[clinic input]
3691_ssl._SSLContext.load_verify_locations
3692 cafile: object = NULL
3693 capath: object = NULL
3694 cadata: object = NULL
3695
3696[clinic start generated code]*/
3697
Antoine Pitrou152efa22010-05-16 18:19:27 +00003698static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003699_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3700 PyObject *cafile,
3701 PyObject *capath,
3702 PyObject *cadata)
3703/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003704{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003705 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3706 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003707 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003708
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003709 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003710 if (cafile == Py_None)
3711 cafile = NULL;
3712 if (capath == Py_None)
3713 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003714 if (cadata == Py_None)
3715 cadata = NULL;
3716
3717 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003718 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003719 "cafile, capath and cadata cannot be all omitted");
3720 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003721 }
3722 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3723 PyErr_SetString(PyExc_TypeError,
3724 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003725 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003726 }
3727 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003728 PyErr_SetString(PyExc_TypeError,
3729 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003730 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003731 }
Christian Heimesefff7062013-11-21 03:35:02 +01003732
3733 /* validata cadata type and load cadata */
3734 if (cadata) {
3735 Py_buffer buf;
3736 PyObject *cadata_ascii = NULL;
3737
3738 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3739 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3740 PyBuffer_Release(&buf);
3741 PyErr_SetString(PyExc_TypeError,
3742 "cadata should be a contiguous buffer with "
3743 "a single dimension");
3744 goto error;
3745 }
3746 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3747 PyBuffer_Release(&buf);
3748 if (r == -1) {
3749 goto error;
3750 }
3751 } else {
3752 PyErr_Clear();
3753 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3754 if (cadata_ascii == NULL) {
3755 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003756 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003757 "bytes-like object");
3758 goto error;
3759 }
3760 r = _add_ca_certs(self,
3761 PyBytes_AS_STRING(cadata_ascii),
3762 PyBytes_GET_SIZE(cadata_ascii),
3763 SSL_FILETYPE_PEM);
3764 Py_DECREF(cadata_ascii);
3765 if (r == -1) {
3766 goto error;
3767 }
3768 }
3769 }
3770
3771 /* load cafile or capath */
3772 if (cafile || capath) {
3773 if (cafile)
3774 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3775 if (capath)
3776 capath_buf = PyBytes_AS_STRING(capath_bytes);
3777 PySSL_BEGIN_ALLOW_THREADS
3778 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3779 PySSL_END_ALLOW_THREADS
3780 if (r != 1) {
3781 ok = 0;
3782 if (errno != 0) {
3783 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003784 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003785 }
3786 else {
3787 _setSSLError(NULL, 0, __FILE__, __LINE__);
3788 }
3789 goto error;
3790 }
3791 }
3792 goto end;
3793
3794 error:
3795 ok = 0;
3796 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003797 Py_XDECREF(cafile_bytes);
3798 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003799 if (ok) {
3800 Py_RETURN_NONE;
3801 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003802 return NULL;
3803 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003804}
3805
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003806/*[clinic input]
3807_ssl._SSLContext.load_dh_params
3808 path as filepath: object
3809 /
3810
3811[clinic start generated code]*/
3812
Antoine Pitrou152efa22010-05-16 18:19:27 +00003813static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003814_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3815/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003816{
3817 FILE *f;
3818 DH *dh;
3819
Victor Stinnerdaf45552013-08-28 00:53:59 +02003820 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003821 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003822 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003823
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003824 errno = 0;
3825 PySSL_BEGIN_ALLOW_THREADS
3826 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003827 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003828 PySSL_END_ALLOW_THREADS
3829 if (dh == NULL) {
3830 if (errno != 0) {
3831 ERR_clear_error();
3832 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3833 }
3834 else {
3835 _setSSLError(NULL, 0, __FILE__, __LINE__);
3836 }
3837 return NULL;
3838 }
3839 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3840 _setSSLError(NULL, 0, __FILE__, __LINE__);
3841 DH_free(dh);
3842 Py_RETURN_NONE;
3843}
3844
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003845/*[clinic input]
3846_ssl._SSLContext._wrap_socket
3847 sock: object(subclass_of="PySocketModule.Sock_Type")
3848 server_side: int
3849 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01003850 *
3851 owner: object = None
3852 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003853
3854[clinic start generated code]*/
3855
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003856static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003857_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01003858 int server_side, PyObject *hostname_obj,
3859 PyObject *owner, PyObject *session)
3860/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003861{
Antoine Pitroud5323212010-10-22 18:19:07 +00003862 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003863 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003864
Antoine Pitroud5323212010-10-22 18:19:07 +00003865 /* server_hostname is either None (or absent), or to be encoded
Christian Heimes11a14932018-02-24 02:35:08 +01003866 as IDN A-label (ASCII str). */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003867 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01003868 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003869 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003870 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003871
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003872 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3873 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01003874 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003875 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003876 if (hostname != NULL)
3877 PyMem_Free(hostname);
3878 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003879}
3880
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003881/*[clinic input]
3882_ssl._SSLContext._wrap_bio
3883 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3884 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3885 server_side: int
3886 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01003887 *
3888 owner: object = None
3889 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003890
3891[clinic start generated code]*/
3892
Antoine Pitroub0182c82010-10-12 20:09:02 +00003893static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003894_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3895 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01003896 PyObject *hostname_obj, PyObject *owner,
3897 PyObject *session)
3898/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003899{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003900 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003901 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003902
3903 /* server_hostname is either None (or absent), or to be encoded
Christian Heimes11a14932018-02-24 02:35:08 +01003904 as IDN A-label (ASCII str). */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003905 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01003906 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003907 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003908 }
3909
3910 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01003911 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003912 incoming, outgoing);
3913
3914 PyMem_Free(hostname);
3915 return res;
3916}
3917
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003918/*[clinic input]
3919_ssl._SSLContext.session_stats
3920[clinic start generated code]*/
3921
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003922static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003923_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3924/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003925{
3926 int r;
3927 PyObject *value, *stats = PyDict_New();
3928 if (!stats)
3929 return NULL;
3930
3931#define ADD_STATS(SSL_NAME, KEY_NAME) \
3932 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3933 if (value == NULL) \
3934 goto error; \
3935 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3936 Py_DECREF(value); \
3937 if (r < 0) \
3938 goto error;
3939
3940 ADD_STATS(number, "number");
3941 ADD_STATS(connect, "connect");
3942 ADD_STATS(connect_good, "connect_good");
3943 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3944 ADD_STATS(accept, "accept");
3945 ADD_STATS(accept_good, "accept_good");
3946 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3947 ADD_STATS(accept, "accept");
3948 ADD_STATS(hits, "hits");
3949 ADD_STATS(misses, "misses");
3950 ADD_STATS(timeouts, "timeouts");
3951 ADD_STATS(cache_full, "cache_full");
3952
3953#undef ADD_STATS
3954
3955 return stats;
3956
3957error:
3958 Py_DECREF(stats);
3959 return NULL;
3960}
3961
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003962/*[clinic input]
3963_ssl._SSLContext.set_default_verify_paths
3964[clinic start generated code]*/
3965
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003966static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003967_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3968/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003969{
3970 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3971 _setSSLError(NULL, 0, __FILE__, __LINE__);
3972 return NULL;
3973 }
3974 Py_RETURN_NONE;
3975}
3976
Antoine Pitrou501da612011-12-21 09:27:41 +01003977#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003978/*[clinic input]
3979_ssl._SSLContext.set_ecdh_curve
3980 name: object
3981 /
3982
3983[clinic start generated code]*/
3984
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003985static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003986_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3987/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003988{
3989 PyObject *name_bytes;
3990 int nid;
3991 EC_KEY *key;
3992
3993 if (!PyUnicode_FSConverter(name, &name_bytes))
3994 return NULL;
3995 assert(PyBytes_Check(name_bytes));
3996 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3997 Py_DECREF(name_bytes);
3998 if (nid == 0) {
3999 PyErr_Format(PyExc_ValueError,
4000 "unknown elliptic curve name %R", name);
4001 return NULL;
4002 }
4003 key = EC_KEY_new_by_curve_name(nid);
4004 if (key == NULL) {
4005 _setSSLError(NULL, 0, __FILE__, __LINE__);
4006 return NULL;
4007 }
4008 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4009 EC_KEY_free(key);
4010 Py_RETURN_NONE;
4011}
Antoine Pitrou501da612011-12-21 09:27:41 +01004012#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004013
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004014#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004015static int
4016_servername_callback(SSL *s, int *al, void *args)
4017{
4018 int ret;
4019 PySSLContext *ssl_ctx = (PySSLContext *) args;
4020 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004021 PyObject *result;
4022 /* The high-level ssl.SSLSocket object */
4023 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004024 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004025 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004026
Christian Heimes11a14932018-02-24 02:35:08 +01004027 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004028 /* remove race condition in this the call back while if removing the
4029 * callback is in progress */
4030 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004031 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004032 }
4033
4034 ssl = SSL_get_app_data(s);
4035 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004036
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004037 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004038 * SSL connection and that has a .context attribute that can be changed to
4039 * identify the requested hostname. Since the official API is the Python
4040 * level API we want to pass the callback a Python level object rather than
4041 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4042 * SSLObject) that will be passed. Otherwise if there's a socket then that
4043 * will be passed. If both do not exist only then the C-level object is
4044 * passed. */
4045 if (ssl->owner)
4046 ssl_socket = PyWeakref_GetObject(ssl->owner);
4047 else if (ssl->Socket)
4048 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4049 else
4050 ssl_socket = (PyObject *) ssl;
4051
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004052 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004053 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004054 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004055
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004056 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004057 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004058 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004059 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004060 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004061 PyObject *servername_bytes;
4062 PyObject *servername_str;
4063
4064 servername_bytes = PyBytes_FromString(servername);
4065 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004066 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4067 goto error;
4068 }
Christian Heimes11a14932018-02-24 02:35:08 +01004069 /* server_hostname was encoded to an A-label by our caller; put it
4070 * back into a str object, but still as an A-label (bpo-28414)
4071 */
4072 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4073 Py_DECREF(servername_bytes);
4074 if (servername_str == NULL) {
4075 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004076 goto error;
4077 }
Christian Heimes11a14932018-02-24 02:35:08 +01004078 result = PyObject_CallFunctionObjArgs(
4079 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4080 ssl_ctx, NULL);
4081 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004082 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004083 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004084
4085 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004086 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004087 *al = SSL_AD_HANDSHAKE_FAILURE;
4088 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4089 }
4090 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004091 /* Result may be None, a SSLContext or an integer
4092 * None and SSLContext are OK, integer or other values are an error.
4093 */
4094 if (result == Py_None) {
4095 ret = SSL_TLSEXT_ERR_OK;
4096 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004097 *al = (int) PyLong_AsLong(result);
4098 if (PyErr_Occurred()) {
4099 PyErr_WriteUnraisable(result);
4100 *al = SSL_AD_INTERNAL_ERROR;
4101 }
4102 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4103 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004104 Py_DECREF(result);
4105 }
4106
4107 PyGILState_Release(gstate);
4108 return ret;
4109
4110error:
4111 Py_DECREF(ssl_socket);
4112 *al = SSL_AD_INTERNAL_ERROR;
4113 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4114 PyGILState_Release(gstate);
4115 return ret;
4116}
Antoine Pitroua5963382013-03-30 16:39:00 +01004117#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004118
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004119static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004120get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004121{
Christian Heimes11a14932018-02-24 02:35:08 +01004122 PyObject *cb = self->set_sni_cb;
4123 if (cb == NULL) {
4124 Py_RETURN_NONE;
4125 }
4126 Py_INCREF(cb);
4127 return cb;
4128}
4129
4130static int
4131set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4132{
4133 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4134 PyErr_SetString(PyExc_ValueError,
4135 "sni_callback cannot be set on TLS_CLIENT context");
4136 return -1;
4137 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004138#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004139 Py_CLEAR(self->set_sni_cb);
4140 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004141 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4142 }
4143 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004144 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004145 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4146 PyErr_SetString(PyExc_TypeError,
4147 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004148 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004149 }
Christian Heimes11a14932018-02-24 02:35:08 +01004150 Py_INCREF(arg);
4151 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004152 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4153 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4154 }
Christian Heimes11a14932018-02-24 02:35:08 +01004155 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004156#else
4157 PyErr_SetString(PyExc_NotImplementedError,
4158 "The TLS extension servername callback, "
4159 "SSL_CTX_set_tlsext_servername_callback, "
4160 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004161 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004162#endif
4163}
4164
Christian Heimes11a14932018-02-24 02:35:08 +01004165PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4166"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4167\n\
4168If the argument is None then the callback is disabled. The method is called\n\
4169with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4170See RFC 6066 for details of the SNI extension.");
4171
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004172/*[clinic input]
4173_ssl._SSLContext.cert_store_stats
4174
4175Returns quantities of loaded X.509 certificates.
4176
4177X.509 certificates with a CA extension and certificate revocation lists
4178inside the context's cert store.
4179
4180NOTE: Certificates in a capath directory aren't loaded unless they have
4181been used at least once.
4182[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004183
4184static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004185_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4186/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004187{
4188 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004189 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004190 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004191 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004192
4193 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004194 objs = X509_STORE_get0_objects(store);
4195 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4196 obj = sk_X509_OBJECT_value(objs, i);
4197 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004198 case X509_LU_X509:
4199 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004200 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004201 ca++;
4202 }
4203 break;
4204 case X509_LU_CRL:
4205 crl++;
4206 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004207 default:
4208 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4209 * As far as I can tell they are internal states and never
4210 * stored in a cert store */
4211 break;
4212 }
4213 }
4214 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4215 "x509_ca", ca);
4216}
4217
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004218/*[clinic input]
4219_ssl._SSLContext.get_ca_certs
4220 binary_form: bool = False
4221
4222Returns a list of dicts with information of loaded CA certs.
4223
4224If the optional argument is True, returns a DER-encoded copy of the CA
4225certificate.
4226
4227NOTE: Certificates in a capath directory aren't loaded unless they have
4228been used at least once.
4229[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004230
4231static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004232_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4233/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004234{
4235 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004236 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004237 PyObject *ci = NULL, *rlist = NULL;
4238 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004239
4240 if ((rlist = PyList_New(0)) == NULL) {
4241 return NULL;
4242 }
4243
4244 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004245 objs = X509_STORE_get0_objects(store);
4246 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004247 X509_OBJECT *obj;
4248 X509 *cert;
4249
Christian Heimes598894f2016-09-05 23:19:05 +02004250 obj = sk_X509_OBJECT_value(objs, i);
4251 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004252 /* not a x509 cert */
4253 continue;
4254 }
4255 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004256 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004257 if (!X509_check_ca(cert)) {
4258 continue;
4259 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004260 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004261 ci = _certificate_to_der(cert);
4262 } else {
4263 ci = _decode_certificate(cert);
4264 }
4265 if (ci == NULL) {
4266 goto error;
4267 }
4268 if (PyList_Append(rlist, ci) == -1) {
4269 goto error;
4270 }
4271 Py_CLEAR(ci);
4272 }
4273 return rlist;
4274
4275 error:
4276 Py_XDECREF(ci);
4277 Py_XDECREF(rlist);
4278 return NULL;
4279}
4280
4281
Antoine Pitrou152efa22010-05-16 18:19:27 +00004282static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004283 {"check_hostname", (getter) get_check_hostname,
4284 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004285 {"_host_flags", (getter) get_host_flags,
4286 (setter) set_host_flags, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004287 {"sni_callback", (getter) get_sni_callback,
4288 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004289 {"options", (getter) get_options,
4290 (setter) set_options, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004291 {"protocol", (getter) get_protocol,
4292 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004293 {"verify_flags", (getter) get_verify_flags,
4294 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004295 {"verify_mode", (getter) get_verify_mode,
4296 (setter) set_verify_mode, NULL},
4297 {NULL}, /* sentinel */
4298};
4299
4300static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004301 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4302 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4303 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4304 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4305 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4306 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4307 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4308 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4309 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4310 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4311 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004312 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4313 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004314 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004315 {NULL, NULL} /* sentinel */
4316};
4317
4318static PyTypeObject PySSLContext_Type = {
4319 PyVarObject_HEAD_INIT(NULL, 0)
4320 "_ssl._SSLContext", /*tp_name*/
4321 sizeof(PySSLContext), /*tp_basicsize*/
4322 0, /*tp_itemsize*/
4323 (destructor)context_dealloc, /*tp_dealloc*/
4324 0, /*tp_print*/
4325 0, /*tp_getattr*/
4326 0, /*tp_setattr*/
4327 0, /*tp_reserved*/
4328 0, /*tp_repr*/
4329 0, /*tp_as_number*/
4330 0, /*tp_as_sequence*/
4331 0, /*tp_as_mapping*/
4332 0, /*tp_hash*/
4333 0, /*tp_call*/
4334 0, /*tp_str*/
4335 0, /*tp_getattro*/
4336 0, /*tp_setattro*/
4337 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004338 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004339 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004340 (traverseproc) context_traverse, /*tp_traverse*/
4341 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004342 0, /*tp_richcompare*/
4343 0, /*tp_weaklistoffset*/
4344 0, /*tp_iter*/
4345 0, /*tp_iternext*/
4346 context_methods, /*tp_methods*/
4347 0, /*tp_members*/
4348 context_getsetlist, /*tp_getset*/
4349 0, /*tp_base*/
4350 0, /*tp_dict*/
4351 0, /*tp_descr_get*/
4352 0, /*tp_descr_set*/
4353 0, /*tp_dictoffset*/
4354 0, /*tp_init*/
4355 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004356 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004357};
4358
4359
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004360/*
4361 * MemoryBIO objects
4362 */
4363
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004364/*[clinic input]
4365@classmethod
4366_ssl.MemoryBIO.__new__
4367
4368[clinic start generated code]*/
4369
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004370static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004371_ssl_MemoryBIO_impl(PyTypeObject *type)
4372/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004373{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004374 BIO *bio;
4375 PySSLMemoryBIO *self;
4376
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004377 bio = BIO_new(BIO_s_mem());
4378 if (bio == NULL) {
4379 PyErr_SetString(PySSLErrorObject,
4380 "failed to allocate BIO");
4381 return NULL;
4382 }
4383 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4384 * just that no data is currently available. The SSL routines should retry
4385 * the read, which we can achieve by calling BIO_set_retry_read(). */
4386 BIO_set_retry_read(bio);
4387 BIO_set_mem_eof_return(bio, -1);
4388
4389 assert(type != NULL && type->tp_alloc != NULL);
4390 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4391 if (self == NULL) {
4392 BIO_free(bio);
4393 return NULL;
4394 }
4395 self->bio = bio;
4396 self->eof_written = 0;
4397
4398 return (PyObject *) self;
4399}
4400
4401static void
4402memory_bio_dealloc(PySSLMemoryBIO *self)
4403{
4404 BIO_free(self->bio);
4405 Py_TYPE(self)->tp_free(self);
4406}
4407
4408static PyObject *
4409memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4410{
Segev Finer5cff6372017-07-27 01:19:17 +03004411 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004412}
4413
4414PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4415"The number of bytes pending in the memory BIO.");
4416
4417static PyObject *
4418memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4419{
4420 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4421 && self->eof_written);
4422}
4423
4424PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4425"Whether the memory BIO is at EOF.");
4426
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004427/*[clinic input]
4428_ssl.MemoryBIO.read
4429 size as len: int = -1
4430 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004431
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004432Read up to size bytes from the memory BIO.
4433
4434If size is not specified, read the entire buffer.
4435If the return value is an empty bytes instance, this means either
4436EOF or that no data is available. Use the "eof" property to
4437distinguish between the two.
4438[clinic start generated code]*/
4439
4440static PyObject *
4441_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4442/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4443{
4444 int avail, nbytes;
4445 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004446
Segev Finer5cff6372017-07-27 01:19:17 +03004447 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004448 if ((len < 0) || (len > avail))
4449 len = avail;
4450
4451 result = PyBytes_FromStringAndSize(NULL, len);
4452 if ((result == NULL) || (len == 0))
4453 return result;
4454
4455 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4456 /* There should never be any short reads but check anyway. */
4457 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4458 Py_DECREF(result);
4459 return NULL;
4460 }
4461
4462 return result;
4463}
4464
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004465/*[clinic input]
4466_ssl.MemoryBIO.write
4467 b: Py_buffer
4468 /
4469
4470Writes the bytes b into the memory BIO.
4471
4472Returns the number of bytes written.
4473[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004474
4475static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004476_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4477/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004478{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004479 int nbytes;
4480
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004481 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004482 PyErr_Format(PyExc_OverflowError,
4483 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004484 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004485 }
4486
4487 if (self->eof_written) {
4488 PyErr_SetString(PySSLErrorObject,
4489 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004490 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004491 }
4492
Segev Finer5cff6372017-07-27 01:19:17 +03004493 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004494 if (nbytes < 0) {
4495 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004496 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004497 }
4498
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004499 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004500}
4501
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004502/*[clinic input]
4503_ssl.MemoryBIO.write_eof
4504
4505Write an EOF marker to the memory BIO.
4506
4507When all data has been read, the "eof" property will be True.
4508[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004509
4510static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004511_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4512/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004513{
4514 self->eof_written = 1;
4515 /* After an EOF is written, a zero return from read() should be a real EOF
4516 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4517 BIO_clear_retry_flags(self->bio);
4518 BIO_set_mem_eof_return(self->bio, 0);
4519
4520 Py_RETURN_NONE;
4521}
4522
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004523static PyGetSetDef memory_bio_getsetlist[] = {
4524 {"pending", (getter) memory_bio_get_pending, NULL,
4525 PySSL_memory_bio_pending_doc},
4526 {"eof", (getter) memory_bio_get_eof, NULL,
4527 PySSL_memory_bio_eof_doc},
4528 {NULL}, /* sentinel */
4529};
4530
4531static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004532 _SSL_MEMORYBIO_READ_METHODDEF
4533 _SSL_MEMORYBIO_WRITE_METHODDEF
4534 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004535 {NULL, NULL} /* sentinel */
4536};
4537
4538static PyTypeObject PySSLMemoryBIO_Type = {
4539 PyVarObject_HEAD_INIT(NULL, 0)
4540 "_ssl.MemoryBIO", /*tp_name*/
4541 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4542 0, /*tp_itemsize*/
4543 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4544 0, /*tp_print*/
4545 0, /*tp_getattr*/
4546 0, /*tp_setattr*/
4547 0, /*tp_reserved*/
4548 0, /*tp_repr*/
4549 0, /*tp_as_number*/
4550 0, /*tp_as_sequence*/
4551 0, /*tp_as_mapping*/
4552 0, /*tp_hash*/
4553 0, /*tp_call*/
4554 0, /*tp_str*/
4555 0, /*tp_getattro*/
4556 0, /*tp_setattro*/
4557 0, /*tp_as_buffer*/
4558 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4559 0, /*tp_doc*/
4560 0, /*tp_traverse*/
4561 0, /*tp_clear*/
4562 0, /*tp_richcompare*/
4563 0, /*tp_weaklistoffset*/
4564 0, /*tp_iter*/
4565 0, /*tp_iternext*/
4566 memory_bio_methods, /*tp_methods*/
4567 0, /*tp_members*/
4568 memory_bio_getsetlist, /*tp_getset*/
4569 0, /*tp_base*/
4570 0, /*tp_dict*/
4571 0, /*tp_descr_get*/
4572 0, /*tp_descr_set*/
4573 0, /*tp_dictoffset*/
4574 0, /*tp_init*/
4575 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004576 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004577};
4578
Antoine Pitrou152efa22010-05-16 18:19:27 +00004579
Christian Heimes99a65702016-09-10 23:44:53 +02004580/*
4581 * SSL Session object
4582 */
4583
4584static void
4585PySSLSession_dealloc(PySSLSession *self)
4586{
INADA Naokia6296d32017-08-24 14:55:17 +09004587 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004588 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004589 Py_XDECREF(self->ctx);
4590 if (self->session != NULL) {
4591 SSL_SESSION_free(self->session);
4592 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004593 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004594}
4595
4596static PyObject *
4597PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4598{
4599 int result;
4600
4601 if (left == NULL || right == NULL) {
4602 PyErr_BadInternalCall();
4603 return NULL;
4604 }
4605
4606 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4607 Py_RETURN_NOTIMPLEMENTED;
4608 }
4609
4610 if (left == right) {
4611 result = 0;
4612 } else {
4613 const unsigned char *left_id, *right_id;
4614 unsigned int left_len, right_len;
4615 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4616 &left_len);
4617 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4618 &right_len);
4619 if (left_len == right_len) {
4620 result = memcmp(left_id, right_id, left_len);
4621 } else {
4622 result = 1;
4623 }
4624 }
4625
4626 switch (op) {
4627 case Py_EQ:
4628 if (result == 0) {
4629 Py_RETURN_TRUE;
4630 } else {
4631 Py_RETURN_FALSE;
4632 }
4633 break;
4634 case Py_NE:
4635 if (result != 0) {
4636 Py_RETURN_TRUE;
4637 } else {
4638 Py_RETURN_FALSE;
4639 }
4640 break;
4641 case Py_LT:
4642 case Py_LE:
4643 case Py_GT:
4644 case Py_GE:
4645 Py_RETURN_NOTIMPLEMENTED;
4646 break;
4647 default:
4648 PyErr_BadArgument();
4649 return NULL;
4650 }
4651}
4652
4653static int
4654PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4655{
4656 Py_VISIT(self->ctx);
4657 return 0;
4658}
4659
4660static int
4661PySSLSession_clear(PySSLSession *self)
4662{
4663 Py_CLEAR(self->ctx);
4664 return 0;
4665}
4666
4667
4668static PyObject *
4669PySSLSession_get_time(PySSLSession *self, void *closure) {
4670 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4671}
4672
4673PyDoc_STRVAR(PySSLSession_get_time_doc,
4674"Session creation time (seconds since epoch).");
4675
4676
4677static PyObject *
4678PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4679 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4680}
4681
4682PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4683"Session timeout (delta in seconds).");
4684
4685
4686static PyObject *
4687PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4688 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4689 return PyLong_FromUnsignedLong(hint);
4690}
4691
4692PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4693"Ticket life time hint.");
4694
4695
4696static PyObject *
4697PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4698 const unsigned char *id;
4699 unsigned int len;
4700 id = SSL_SESSION_get_id(self->session, &len);
4701 return PyBytes_FromStringAndSize((const char *)id, len);
4702}
4703
4704PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4705"Session id");
4706
4707
4708static PyObject *
4709PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4710 if (SSL_SESSION_has_ticket(self->session)) {
4711 Py_RETURN_TRUE;
4712 } else {
4713 Py_RETURN_FALSE;
4714 }
4715}
4716
4717PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4718"Does the session contain a ticket?");
4719
4720
4721static PyGetSetDef PySSLSession_getsetlist[] = {
4722 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4723 PySSLSession_get_has_ticket_doc},
4724 {"id", (getter) PySSLSession_get_session_id, NULL,
4725 PySSLSession_get_session_id_doc},
4726 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4727 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4728 {"time", (getter) PySSLSession_get_time, NULL,
4729 PySSLSession_get_time_doc},
4730 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4731 PySSLSession_get_timeout_doc},
4732 {NULL}, /* sentinel */
4733};
4734
4735static PyTypeObject PySSLSession_Type = {
4736 PyVarObject_HEAD_INIT(NULL, 0)
4737 "_ssl.Session", /*tp_name*/
4738 sizeof(PySSLSession), /*tp_basicsize*/
4739 0, /*tp_itemsize*/
4740 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4741 0, /*tp_print*/
4742 0, /*tp_getattr*/
4743 0, /*tp_setattr*/
4744 0, /*tp_reserved*/
4745 0, /*tp_repr*/
4746 0, /*tp_as_number*/
4747 0, /*tp_as_sequence*/
4748 0, /*tp_as_mapping*/
4749 0, /*tp_hash*/
4750 0, /*tp_call*/
4751 0, /*tp_str*/
4752 0, /*tp_getattro*/
4753 0, /*tp_setattro*/
4754 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004755 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004756 0, /*tp_doc*/
4757 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4758 (inquiry)PySSLSession_clear, /*tp_clear*/
4759 PySSLSession_richcompare, /*tp_richcompare*/
4760 0, /*tp_weaklistoffset*/
4761 0, /*tp_iter*/
4762 0, /*tp_iternext*/
4763 0, /*tp_methods*/
4764 0, /*tp_members*/
4765 PySSLSession_getsetlist, /*tp_getset*/
4766};
4767
4768
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004769/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004770/*[clinic input]
4771_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004772 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004773 entropy: double
4774 /
4775
4776Mix string into the OpenSSL PRNG state.
4777
4778entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304779string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004780[clinic start generated code]*/
4781
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004782static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004783_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004784/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004785{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004786 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004787 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004788
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004789 buf = (const char *)view->buf;
4790 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004791 do {
4792 written = Py_MIN(len, INT_MAX);
4793 RAND_add(buf, (int)written, entropy);
4794 buf += written;
4795 len -= written;
4796 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004797 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004798}
4799
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004800static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004801PySSL_RAND(int len, int pseudo)
4802{
4803 int ok;
4804 PyObject *bytes;
4805 unsigned long err;
4806 const char *errstr;
4807 PyObject *v;
4808
Victor Stinner1e81a392013-12-19 16:47:04 +01004809 if (len < 0) {
4810 PyErr_SetString(PyExc_ValueError, "num must be positive");
4811 return NULL;
4812 }
4813
Victor Stinner99c8b162011-05-24 12:05:19 +02004814 bytes = PyBytes_FromStringAndSize(NULL, len);
4815 if (bytes == NULL)
4816 return NULL;
4817 if (pseudo) {
4818 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4819 if (ok == 0 || ok == 1)
4820 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4821 }
4822 else {
4823 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4824 if (ok == 1)
4825 return bytes;
4826 }
4827 Py_DECREF(bytes);
4828
4829 err = ERR_get_error();
4830 errstr = ERR_reason_error_string(err);
4831 v = Py_BuildValue("(ks)", err, errstr);
4832 if (v != NULL) {
4833 PyErr_SetObject(PySSLErrorObject, v);
4834 Py_DECREF(v);
4835 }
4836 return NULL;
4837}
4838
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004839/*[clinic input]
4840_ssl.RAND_bytes
4841 n: int
4842 /
4843
4844Generate n cryptographically strong pseudo-random bytes.
4845[clinic start generated code]*/
4846
Victor Stinner99c8b162011-05-24 12:05:19 +02004847static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004848_ssl_RAND_bytes_impl(PyObject *module, int n)
4849/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004850{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004851 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004852}
4853
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004854/*[clinic input]
4855_ssl.RAND_pseudo_bytes
4856 n: int
4857 /
4858
4859Generate n pseudo-random bytes.
4860
4861Return a pair (bytes, is_cryptographic). is_cryptographic is True
4862if the bytes generated are cryptographically strong.
4863[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004864
4865static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004866_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4867/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004868{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004869 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004870}
4871
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004872/*[clinic input]
4873_ssl.RAND_status
4874
4875Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4876
4877It is necessary to seed the PRNG with RAND_add() on some platforms before
4878using the ssl() function.
4879[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004880
4881static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004882_ssl_RAND_status_impl(PyObject *module)
4883/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004884{
Christian Heimes217cfd12007-12-02 14:31:20 +00004885 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004886}
4887
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004888#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004889/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004890/*[clinic input]
4891_ssl.RAND_egd
4892 path: object(converter="PyUnicode_FSConverter")
4893 /
4894
4895Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4896
4897Returns number of bytes read. Raises SSLError if connection to EGD
4898fails or if it does not provide enough data to seed PRNG.
4899[clinic start generated code]*/
4900
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004901static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004902_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4903/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004904{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004905 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004906 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004907 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004908 PyErr_SetString(PySSLErrorObject,
4909 "EGD connection failed or EGD did not return "
4910 "enough data to seed the PRNG");
4911 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004912 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004913 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004914}
Christian Heimesa5d07652016-09-24 10:48:05 +02004915/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004916#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004917
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004918
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004919
4920/*[clinic input]
4921_ssl.get_default_verify_paths
4922
4923Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4924
4925The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4926[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004927
4928static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004929_ssl_get_default_verify_paths_impl(PyObject *module)
4930/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004931{
4932 PyObject *ofile_env = NULL;
4933 PyObject *ofile = NULL;
4934 PyObject *odir_env = NULL;
4935 PyObject *odir = NULL;
4936
Benjamin Petersond113c962015-07-18 10:59:13 -07004937#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004938 const char *tmp = (info); \
4939 target = NULL; \
4940 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4941 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4942 target = PyBytes_FromString(tmp); } \
4943 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004944 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004945
Benjamin Petersond113c962015-07-18 10:59:13 -07004946 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4947 CONVERT(X509_get_default_cert_file(), ofile);
4948 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4949 CONVERT(X509_get_default_cert_dir(), odir);
4950#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004951
Christian Heimes200bb1b2013-06-14 15:14:29 +02004952 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004953
4954 error:
4955 Py_XDECREF(ofile_env);
4956 Py_XDECREF(ofile);
4957 Py_XDECREF(odir_env);
4958 Py_XDECREF(odir);
4959 return NULL;
4960}
4961
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004962static PyObject*
4963asn1obj2py(ASN1_OBJECT *obj)
4964{
4965 int nid;
4966 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004967
4968 nid = OBJ_obj2nid(obj);
4969 if (nid == NID_undef) {
4970 PyErr_Format(PyExc_ValueError, "Unknown object");
4971 return NULL;
4972 }
4973 sn = OBJ_nid2sn(nid);
4974 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03004975 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004976}
4977
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004978/*[clinic input]
4979_ssl.txt2obj
4980 txt: str
4981 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004982
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004983Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4984
4985By default objects are looked up by OID. With name=True short and
4986long name are also matched.
4987[clinic start generated code]*/
4988
4989static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004990_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4991/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004992{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004993 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004994 ASN1_OBJECT *obj;
4995
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004996 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4997 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004998 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004999 return NULL;
5000 }
5001 result = asn1obj2py(obj);
5002 ASN1_OBJECT_free(obj);
5003 return result;
5004}
5005
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005006/*[clinic input]
5007_ssl.nid2obj
5008 nid: int
5009 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005010
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005011Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5012[clinic start generated code]*/
5013
5014static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005015_ssl_nid2obj_impl(PyObject *module, int nid)
5016/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005017{
5018 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005019 ASN1_OBJECT *obj;
5020
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005021 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005022 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005023 return NULL;
5024 }
5025 obj = OBJ_nid2obj(nid);
5026 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005027 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005028 return NULL;
5029 }
5030 result = asn1obj2py(obj);
5031 ASN1_OBJECT_free(obj);
5032 return result;
5033}
5034
Christian Heimes46bebee2013-06-09 19:03:31 +02005035#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005036
5037static PyObject*
5038certEncodingType(DWORD encodingType)
5039{
5040 static PyObject *x509_asn = NULL;
5041 static PyObject *pkcs_7_asn = NULL;
5042
5043 if (x509_asn == NULL) {
5044 x509_asn = PyUnicode_InternFromString("x509_asn");
5045 if (x509_asn == NULL)
5046 return NULL;
5047 }
5048 if (pkcs_7_asn == NULL) {
5049 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5050 if (pkcs_7_asn == NULL)
5051 return NULL;
5052 }
5053 switch(encodingType) {
5054 case X509_ASN_ENCODING:
5055 Py_INCREF(x509_asn);
5056 return x509_asn;
5057 case PKCS_7_ASN_ENCODING:
5058 Py_INCREF(pkcs_7_asn);
5059 return pkcs_7_asn;
5060 default:
5061 return PyLong_FromLong(encodingType);
5062 }
5063}
5064
5065static PyObject*
5066parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5067{
5068 CERT_ENHKEY_USAGE *usage;
5069 DWORD size, error, i;
5070 PyObject *retval;
5071
5072 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5073 error = GetLastError();
5074 if (error == CRYPT_E_NOT_FOUND) {
5075 Py_RETURN_TRUE;
5076 }
5077 return PyErr_SetFromWindowsErr(error);
5078 }
5079
5080 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5081 if (usage == NULL) {
5082 return PyErr_NoMemory();
5083 }
5084
5085 /* Now get the actual enhanced usage property */
5086 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5087 PyMem_Free(usage);
5088 error = GetLastError();
5089 if (error == CRYPT_E_NOT_FOUND) {
5090 Py_RETURN_TRUE;
5091 }
5092 return PyErr_SetFromWindowsErr(error);
5093 }
5094 retval = PySet_New(NULL);
5095 if (retval == NULL) {
5096 goto error;
5097 }
5098 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5099 if (usage->rgpszUsageIdentifier[i]) {
5100 PyObject *oid;
5101 int err;
5102 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5103 if (oid == NULL) {
5104 Py_CLEAR(retval);
5105 goto error;
5106 }
5107 err = PySet_Add(retval, oid);
5108 Py_DECREF(oid);
5109 if (err == -1) {
5110 Py_CLEAR(retval);
5111 goto error;
5112 }
5113 }
5114 }
5115 error:
5116 PyMem_Free(usage);
5117 return retval;
5118}
5119
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005120/*[clinic input]
5121_ssl.enum_certificates
5122 store_name: str
5123
5124Retrieve certificates from Windows' cert store.
5125
5126store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5127more cert storages, too. The function returns a list of (bytes,
5128encoding_type, trust) tuples. The encoding_type flag can be interpreted
5129with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5130a set of OIDs or the boolean True.
5131[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005132
Christian Heimes46bebee2013-06-09 19:03:31 +02005133static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005134_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5135/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005136{
Christian Heimes46bebee2013-06-09 19:03:31 +02005137 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005138 PCCERT_CONTEXT pCertCtx = NULL;
5139 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005140 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005141
Christian Heimes44109d72013-11-22 01:51:30 +01005142 result = PyList_New(0);
5143 if (result == NULL) {
5144 return NULL;
5145 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005146 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5147 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5148 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005149 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005150 Py_DECREF(result);
5151 return PyErr_SetFromWindowsErr(GetLastError());
5152 }
5153
Christian Heimes44109d72013-11-22 01:51:30 +01005154 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5155 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5156 pCertCtx->cbCertEncoded);
5157 if (!cert) {
5158 Py_CLEAR(result);
5159 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005160 }
Christian Heimes44109d72013-11-22 01:51:30 +01005161 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5162 Py_CLEAR(result);
5163 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005164 }
Christian Heimes44109d72013-11-22 01:51:30 +01005165 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5166 if (keyusage == Py_True) {
5167 Py_DECREF(keyusage);
5168 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005169 }
Christian Heimes44109d72013-11-22 01:51:30 +01005170 if (keyusage == NULL) {
5171 Py_CLEAR(result);
5172 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005173 }
Christian Heimes44109d72013-11-22 01:51:30 +01005174 if ((tup = PyTuple_New(3)) == NULL) {
5175 Py_CLEAR(result);
5176 break;
5177 }
5178 PyTuple_SET_ITEM(tup, 0, cert);
5179 cert = NULL;
5180 PyTuple_SET_ITEM(tup, 1, enc);
5181 enc = NULL;
5182 PyTuple_SET_ITEM(tup, 2, keyusage);
5183 keyusage = NULL;
5184 if (PyList_Append(result, tup) < 0) {
5185 Py_CLEAR(result);
5186 break;
5187 }
5188 Py_CLEAR(tup);
5189 }
5190 if (pCertCtx) {
5191 /* loop ended with an error, need to clean up context manually */
5192 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005193 }
5194
5195 /* In error cases cert, enc and tup may not be NULL */
5196 Py_XDECREF(cert);
5197 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005198 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005199 Py_XDECREF(tup);
5200
5201 if (!CertCloseStore(hStore, 0)) {
5202 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005203 Py_XDECREF(result);
5204 return PyErr_SetFromWindowsErr(GetLastError());
5205 }
5206 return result;
5207}
5208
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005209/*[clinic input]
5210_ssl.enum_crls
5211 store_name: str
5212
5213Retrieve CRLs from Windows' cert store.
5214
5215store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5216more cert storages, too. The function returns a list of (bytes,
5217encoding_type) tuples. The encoding_type flag can be interpreted with
5218X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5219[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005220
5221static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005222_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5223/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005224{
Christian Heimes44109d72013-11-22 01:51:30 +01005225 HCERTSTORE hStore = NULL;
5226 PCCRL_CONTEXT pCrlCtx = NULL;
5227 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5228 PyObject *result = NULL;
5229
Christian Heimes44109d72013-11-22 01:51:30 +01005230 result = PyList_New(0);
5231 if (result == NULL) {
5232 return NULL;
5233 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005234 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5235 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5236 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005237 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005238 Py_DECREF(result);
5239 return PyErr_SetFromWindowsErr(GetLastError());
5240 }
Christian Heimes44109d72013-11-22 01:51:30 +01005241
5242 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5243 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5244 pCrlCtx->cbCrlEncoded);
5245 if (!crl) {
5246 Py_CLEAR(result);
5247 break;
5248 }
5249 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5250 Py_CLEAR(result);
5251 break;
5252 }
5253 if ((tup = PyTuple_New(2)) == NULL) {
5254 Py_CLEAR(result);
5255 break;
5256 }
5257 PyTuple_SET_ITEM(tup, 0, crl);
5258 crl = NULL;
5259 PyTuple_SET_ITEM(tup, 1, enc);
5260 enc = NULL;
5261
5262 if (PyList_Append(result, tup) < 0) {
5263 Py_CLEAR(result);
5264 break;
5265 }
5266 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005267 }
Christian Heimes44109d72013-11-22 01:51:30 +01005268 if (pCrlCtx) {
5269 /* loop ended with an error, need to clean up context manually */
5270 CertFreeCRLContext(pCrlCtx);
5271 }
5272
5273 /* In error cases cert, enc and tup may not be NULL */
5274 Py_XDECREF(crl);
5275 Py_XDECREF(enc);
5276 Py_XDECREF(tup);
5277
5278 if (!CertCloseStore(hStore, 0)) {
5279 /* This error case might shadow another exception.*/
5280 Py_XDECREF(result);
5281 return PyErr_SetFromWindowsErr(GetLastError());
5282 }
5283 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005284}
Christian Heimes44109d72013-11-22 01:51:30 +01005285
5286#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005287
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005288/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005289static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005290 _SSL__TEST_DECODE_CERT_METHODDEF
5291 _SSL_RAND_ADD_METHODDEF
5292 _SSL_RAND_BYTES_METHODDEF
5293 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5294 _SSL_RAND_EGD_METHODDEF
5295 _SSL_RAND_STATUS_METHODDEF
5296 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5297 _SSL_ENUM_CERTIFICATES_METHODDEF
5298 _SSL_ENUM_CRLS_METHODDEF
5299 _SSL_TXT2OBJ_METHODDEF
5300 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005301 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005302};
5303
5304
Christian Heimes598894f2016-09-05 23:19:05 +02005305#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005306
5307/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005308 * of the Python C thread library
5309 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5310 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005311
5312static PyThread_type_lock *_ssl_locks = NULL;
5313
Christian Heimes4d98ca92013-08-19 17:36:29 +02005314#if OPENSSL_VERSION_NUMBER >= 0x10000000
5315/* use new CRYPTO_THREADID API. */
5316static void
5317_ssl_threadid_callback(CRYPTO_THREADID *id)
5318{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005319 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005320}
5321#else
5322/* deprecated CRYPTO_set_id_callback() API. */
5323static unsigned long
5324_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005325 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005326}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005327#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005328
Bill Janssen6e027db2007-11-15 22:23:56 +00005329static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005330 (int mode, int n, const char *file, int line) {
5331 /* this function is needed to perform locking on shared data
5332 structures. (Note that OpenSSL uses a number of global data
5333 structures that will be implicitly shared whenever multiple
5334 threads use OpenSSL.) Multi-threaded applications will
5335 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005336
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005337 locking_function() must be able to handle up to
5338 CRYPTO_num_locks() different mutex locks. It sets the n-th
5339 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005340
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005341 file and line are the file number of the function setting the
5342 lock. They can be useful for debugging.
5343 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005344
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005345 if ((_ssl_locks == NULL) ||
5346 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5347 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005348
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005349 if (mode & CRYPTO_LOCK) {
5350 PyThread_acquire_lock(_ssl_locks[n], 1);
5351 } else {
5352 PyThread_release_lock(_ssl_locks[n]);
5353 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005354}
5355
5356static int _setup_ssl_threads(void) {
5357
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005358 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005359
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005360 if (_ssl_locks == NULL) {
5361 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005362 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5363 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005364 if (_ssl_locks == NULL) {
5365 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005366 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005367 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005368 for (i = 0; i < _ssl_locks_count; i++) {
5369 _ssl_locks[i] = PyThread_allocate_lock();
5370 if (_ssl_locks[i] == NULL) {
5371 unsigned int j;
5372 for (j = 0; j < i; j++) {
5373 PyThread_free_lock(_ssl_locks[j]);
5374 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005375 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005376 return 0;
5377 }
5378 }
5379 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005380#if OPENSSL_VERSION_NUMBER >= 0x10000000
5381 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5382#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005383 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005384#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005385 }
5386 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005387}
5388
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005389#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005390
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005391PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005392"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005393for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005394
Martin v. Löwis1a214512008-06-11 05:26:20 +00005395
5396static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005397 PyModuleDef_HEAD_INIT,
5398 "_ssl",
5399 module_doc,
5400 -1,
5401 PySSL_methods,
5402 NULL,
5403 NULL,
5404 NULL,
5405 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005406};
5407
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005408
5409static void
5410parse_openssl_version(unsigned long libver,
5411 unsigned int *major, unsigned int *minor,
5412 unsigned int *fix, unsigned int *patch,
5413 unsigned int *status)
5414{
5415 *status = libver & 0xF;
5416 libver >>= 4;
5417 *patch = libver & 0xFF;
5418 libver >>= 8;
5419 *fix = libver & 0xFF;
5420 libver >>= 8;
5421 *minor = libver & 0xFF;
5422 libver >>= 8;
5423 *major = libver & 0xFF;
5424}
5425
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005426PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005427PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005428{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005429 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005430 unsigned long libver;
5431 unsigned int major, minor, fix, patch, status;
5432 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005433 struct py_ssl_error_code *errcode;
5434 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005435
Antoine Pitrou152efa22010-05-16 18:19:27 +00005436 if (PyType_Ready(&PySSLContext_Type) < 0)
5437 return NULL;
5438 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005439 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005440 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5441 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005442 if (PyType_Ready(&PySSLSession_Type) < 0)
5443 return NULL;
5444
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005445
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005446 m = PyModule_Create(&_sslmodule);
5447 if (m == NULL)
5448 return NULL;
5449 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005450
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005451 /* Load _socket module and its C API */
5452 socket_api = PySocketModule_ImportModuleAndAPI();
5453 if (!socket_api)
5454 return NULL;
5455 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005456
Christian Heimesc941e622017-09-05 15:47:11 +02005457#ifndef OPENSSL_VERSION_1_1
5458 /* Load all algorithms and initialize cpuid */
5459 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005460 /* Init OpenSSL */
5461 SSL_load_error_strings();
5462 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005463#endif
5464
Christian Heimes598894f2016-09-05 23:19:05 +02005465#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005466 /* note that this will start threading if not already started */
5467 if (!_setup_ssl_threads()) {
5468 return NULL;
5469 }
Christian Heimes598894f2016-09-05 23:19:05 +02005470#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5471 /* OpenSSL 1.1.0 builtin thread support is enabled */
5472 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005473#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005474
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005475 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005476 sslerror_type_slots[0].pfunc = PyExc_OSError;
5477 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005478 if (PySSLErrorObject == NULL)
5479 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005480
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005481 /* ssl.CertificateError used to be a subclass of ValueError */
5482 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5483 if (bases == NULL)
5484 return NULL;
5485 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5486 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5487 bases, NULL);
5488 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005489 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5490 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5491 PySSLErrorObject, NULL);
5492 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5493 "ssl.SSLWantReadError", SSLWantReadError_doc,
5494 PySSLErrorObject, NULL);
5495 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5496 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5497 PySSLErrorObject, NULL);
5498 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5499 "ssl.SSLSyscallError", SSLSyscallError_doc,
5500 PySSLErrorObject, NULL);
5501 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5502 "ssl.SSLEOFError", SSLEOFError_doc,
5503 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005504 if (PySSLCertVerificationErrorObject == NULL
5505 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005506 || PySSLWantReadErrorObject == NULL
5507 || PySSLWantWriteErrorObject == NULL
5508 || PySSLSyscallErrorObject == NULL
5509 || PySSLEOFErrorObject == NULL)
5510 return NULL;
5511 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005512 || PyDict_SetItemString(d, "SSLCertVerificationError",
5513 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005514 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5515 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5516 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5517 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5518 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005519 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005520 if (PyDict_SetItemString(d, "_SSLContext",
5521 (PyObject *)&PySSLContext_Type) != 0)
5522 return NULL;
5523 if (PyDict_SetItemString(d, "_SSLSocket",
5524 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005525 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005526 if (PyDict_SetItemString(d, "MemoryBIO",
5527 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5528 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005529 if (PyDict_SetItemString(d, "SSLSession",
5530 (PyObject *)&PySSLSession_Type) != 0)
5531 return NULL;
5532
Christian Heimes892d66e2018-01-29 14:10:18 +01005533 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5534 PY_SSL_DEFAULT_CIPHER_STRING);
5535
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005536 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5537 PY_SSL_ERROR_ZERO_RETURN);
5538 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5539 PY_SSL_ERROR_WANT_READ);
5540 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5541 PY_SSL_ERROR_WANT_WRITE);
5542 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5543 PY_SSL_ERROR_WANT_X509_LOOKUP);
5544 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5545 PY_SSL_ERROR_SYSCALL);
5546 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5547 PY_SSL_ERROR_SSL);
5548 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5549 PY_SSL_ERROR_WANT_CONNECT);
5550 /* non ssl.h errorcodes */
5551 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5552 PY_SSL_ERROR_EOF);
5553 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5554 PY_SSL_ERROR_INVALID_ERROR_CODE);
5555 /* cert requirements */
5556 PyModule_AddIntConstant(m, "CERT_NONE",
5557 PY_SSL_CERT_NONE);
5558 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5559 PY_SSL_CERT_OPTIONAL);
5560 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5561 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005562 /* CRL verification for verification_flags */
5563 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5564 0);
5565 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5566 X509_V_FLAG_CRL_CHECK);
5567 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5568 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5569 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5570 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005571#ifdef X509_V_FLAG_TRUSTED_FIRST
5572 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5573 X509_V_FLAG_TRUSTED_FIRST);
5574#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005575
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005576 /* Alert Descriptions from ssl.h */
5577 /* note RESERVED constants no longer intended for use have been removed */
5578 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5579
5580#define ADD_AD_CONSTANT(s) \
5581 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5582 SSL_AD_##s)
5583
5584 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5585 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5586 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5587 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5588 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5589 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5590 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5591 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5592 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5593 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5594 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5595 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5596 ADD_AD_CONSTANT(UNKNOWN_CA);
5597 ADD_AD_CONSTANT(ACCESS_DENIED);
5598 ADD_AD_CONSTANT(DECODE_ERROR);
5599 ADD_AD_CONSTANT(DECRYPT_ERROR);
5600 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5601 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5602 ADD_AD_CONSTANT(INTERNAL_ERROR);
5603 ADD_AD_CONSTANT(USER_CANCELLED);
5604 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005605 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005606#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5607 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5608#endif
5609#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5610 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5611#endif
5612#ifdef SSL_AD_UNRECOGNIZED_NAME
5613 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5614#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005615#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5616 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5617#endif
5618#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5619 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5620#endif
5621#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5622 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5623#endif
5624
5625#undef ADD_AD_CONSTANT
5626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005627 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005628#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005629 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5630 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005631#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005632#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005633 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5634 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005635#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005636 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005637 PY_SSL_VERSION_TLS);
5638 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5639 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005640 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5641 PY_SSL_VERSION_TLS_CLIENT);
5642 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5643 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005644 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5645 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005646#if HAVE_TLSv1_2
5647 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5648 PY_SSL_VERSION_TLS1_1);
5649 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5650 PY_SSL_VERSION_TLS1_2);
5651#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005652
Antoine Pitroub5218772010-05-21 09:56:06 +00005653 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005654 PyModule_AddIntConstant(m, "OP_ALL",
5655 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005656 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5657 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5658 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005659#if HAVE_TLSv1_2
5660 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5661 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5662#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005663#ifdef SSL_OP_NO_TLSv1_3
5664 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5665#else
5666 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5667#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005668 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5669 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005670 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005671 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005672#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005673 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005674#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005675#ifdef SSL_OP_NO_COMPRESSION
5676 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5677 SSL_OP_NO_COMPRESSION);
5678#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005679
Christian Heimes61d478c2018-01-27 15:51:38 +01005680#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5681 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5682 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5683#endif
5684#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5685 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5686 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5687#endif
5688#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5689 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5690 X509_CHECK_FLAG_NO_WILDCARDS);
5691#endif
5692#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5693 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5694 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5695#endif
5696#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5697 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5698 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5699#endif
5700#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5701 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5702 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5703#endif
5704
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005705#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005706 r = Py_True;
5707#else
5708 r = Py_False;
5709#endif
5710 Py_INCREF(r);
5711 PyModule_AddObject(m, "HAS_SNI", r);
5712
Antoine Pitrou501da612011-12-21 09:27:41 +01005713#ifdef OPENSSL_NO_ECDH
5714 r = Py_False;
5715#else
5716 r = Py_True;
5717#endif
5718 Py_INCREF(r);
5719 PyModule_AddObject(m, "HAS_ECDH", r);
5720
Christian Heimes6cdb7952018-02-24 22:12:40 +01005721#ifdef HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005722 r = Py_True;
5723#else
5724 r = Py_False;
5725#endif
5726 Py_INCREF(r);
5727 PyModule_AddObject(m, "HAS_NPN", r);
5728
Benjamin Petersoncca27322015-01-23 16:35:37 -05005729#ifdef HAVE_ALPN
5730 r = Py_True;
5731#else
5732 r = Py_False;
5733#endif
5734 Py_INCREF(r);
5735 PyModule_AddObject(m, "HAS_ALPN", r);
5736
Christian Heimescb5b68a2017-09-07 18:07:00 -07005737#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
5738 r = Py_True;
5739#else
5740 r = Py_False;
5741#endif
5742 Py_INCREF(r);
5743 PyModule_AddObject(m, "HAS_TLSv1_3", r);
5744
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005745 /* Mappings for error codes */
5746 err_codes_to_names = PyDict_New();
5747 err_names_to_codes = PyDict_New();
5748 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5749 return NULL;
5750 errcode = error_codes;
5751 while (errcode->mnemonic != NULL) {
5752 PyObject *mnemo, *key;
5753 mnemo = PyUnicode_FromString(errcode->mnemonic);
5754 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5755 if (mnemo == NULL || key == NULL)
5756 return NULL;
5757 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5758 return NULL;
5759 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5760 return NULL;
5761 Py_DECREF(key);
5762 Py_DECREF(mnemo);
5763 errcode++;
5764 }
5765 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5766 return NULL;
5767 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5768 return NULL;
5769
5770 lib_codes_to_names = PyDict_New();
5771 if (lib_codes_to_names == NULL)
5772 return NULL;
5773 libcode = library_codes;
5774 while (libcode->library != NULL) {
5775 PyObject *mnemo, *key;
5776 key = PyLong_FromLong(libcode->code);
5777 mnemo = PyUnicode_FromString(libcode->library);
5778 if (key == NULL || mnemo == NULL)
5779 return NULL;
5780 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5781 return NULL;
5782 Py_DECREF(key);
5783 Py_DECREF(mnemo);
5784 libcode++;
5785 }
5786 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5787 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005788
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005789 /* OpenSSL version */
5790 /* SSLeay() gives us the version of the library linked against,
5791 which could be different from the headers version.
5792 */
5793 libver = SSLeay();
5794 r = PyLong_FromUnsignedLong(libver);
5795 if (r == NULL)
5796 return NULL;
5797 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5798 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005799 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005800 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5801 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5802 return NULL;
5803 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5804 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5805 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005806
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005807 libver = OPENSSL_VERSION_NUMBER;
5808 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5809 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5810 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5811 return NULL;
5812
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005813 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005814}