blob: 376d3bb11a40bbc8694b0ab4d63669a02f42203b [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
Christian Heimesa4833882021-04-13 08:17:26 +020017/* Don't warn about deprecated functions, */
18#ifndef OPENSSL_API_COMPAT
19 // 0x10101000L == 1.1.1, 30000 == 3.0.0
20 #define OPENSSL_API_COMPAT 0x10101000L
21#endif
22#define OPENSSL_NO_DEPRECATED 1
23
Victor Stinner2e57b4e2014-07-01 16:37:17 +020024#define PY_SSIZE_T_CLEAN
25
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000026#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000027
Christian Heimes7f1305e2021-04-17 20:06:38 +020028/* Include symbols from _socket module */
29#include "socketmodule.h"
30
31#include "_ssl.h"
32
Steve Dower68d663c2017-07-17 11:15:48 +020033/* Redefined below for Windows debug builds after important #includes */
34#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020035
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020036#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
Christian Heimes39258d32021-04-17 11:36:35 +020037 do { (save) = PyEval_SaveThread(); } while(0)
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020038#define PySSL_END_ALLOW_THREADS_S(save) \
Christian Heimes39258d32021-04-17 11:36:35 +020039 do { PyEval_RestoreThread(save); _PySSL_FIX_ERRNO; } while(0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000040#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000041 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020042 PySSL_BEGIN_ALLOW_THREADS_S(_save);
43#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
44#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
45#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000046
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010047
48#if defined(HAVE_POLL_H)
49#include <poll.h>
50#elif defined(HAVE_SYS_POLL_H)
51#include <sys/poll.h>
52#endif
53
54/* Include OpenSSL header files */
55#include "openssl/rsa.h"
56#include "openssl/crypto.h"
57#include "openssl/x509.h"
58#include "openssl/x509v3.h"
59#include "openssl/pem.h"
60#include "openssl/ssl.h"
61#include "openssl/err.h"
62#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020063#include "openssl/bio.h"
Alexandru Ardeleanb3a271f2018-09-17 14:53:31 +030064#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010065
Christian Heimesc087a262020-05-15 20:55:25 +020066#ifndef OPENSSL_THREADS
67# error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
68#endif
69
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010070
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010071
72struct py_ssl_error_code {
73 const char *mnemonic;
74 int library, reason;
75};
Christian Heimes7f1305e2021-04-17 20:06:38 +020076
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010077struct py_ssl_library_code {
78 const char *library;
79 int code;
80};
81
Steve Dower68d663c2017-07-17 11:15:48 +020082#if defined(MS_WINDOWS) && defined(Py_DEBUG)
83/* Debug builds on Windows rely on getting errno directly from OpenSSL.
84 * However, because it uses a different CRT, we need to transfer the
85 * value of errno from OpenSSL into our debug CRT.
86 *
87 * Don't be fooled - this is horribly ugly code. The only reasonable
88 * alternative is to do both debug and release builds of OpenSSL, which
89 * requires much uglier code to transform their automatically generated
90 * makefile. This is the lesser of all the evils.
91 */
92
93static void _PySSLFixErrno(void) {
94 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
95 if (!ucrtbase) {
96 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
97 * have a catastrophic failure, but this function is not the
98 * place to raise it. */
99 return;
100 }
101
102 typedef int *(__stdcall *errno_func)(void);
103 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
104 if (ssl_errno) {
105 errno = *ssl_errno();
106 *ssl_errno() = 0;
107 } else {
108 errno = ENOTRECOVERABLE;
109 }
110}
111
112#undef _PySSL_FIX_ERRNO
113#define _PySSL_FIX_ERRNO _PySSLFixErrno()
114#endif
115
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100116/* Include generated data (error codes) */
Christian Heimes150af752021-04-09 17:02:00 +0200117#if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
118#include "_ssl_data_300.h"
119#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
120#include "_ssl_data_111.h"
121#else
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100122#include "_ssl_data.h"
Christian Heimes150af752021-04-09 17:02:00 +0200123#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100124
Christian Heimes39258d32021-04-17 11:36:35 +0200125/* OpenSSL API 1.1.0+ does not include version methods */
Christian Heimesa871f692020-06-01 08:58:14 +0200126#ifndef OPENSSL_NO_TLS1_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200127extern const SSL_METHOD *TLSv1_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200128#endif
129#ifndef OPENSSL_NO_TLS1_1_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200130extern const SSL_METHOD *TLSv1_1_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200131#endif
132#ifndef OPENSSL_NO_TLS1_2_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200133extern const SSL_METHOD *TLSv1_2_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200134#endif
135
Victor Stinner524714e2016-07-22 17:43:59 +0200136#ifndef INVALID_SOCKET /* MS defines this */
137#define INVALID_SOCKET (-1)
138#endif
139
Christian Heimes39258d32021-04-17 11:36:35 +0200140/* OpenSSL 1.1 does not have SSL 2.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200141#define OPENSSL_NO_SSL2
Christian Heimes598894f2016-09-05 23:19:05 +0200142
Christian Heimes892d66e2018-01-29 14:10:18 +0100143/* Default cipher suites */
144#ifndef PY_SSL_DEFAULT_CIPHERS
145#define PY_SSL_DEFAULT_CIPHERS 1
146#endif
147
148#if PY_SSL_DEFAULT_CIPHERS == 0
149 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
150 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
151 #endif
152#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200153/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100154 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
155 * !aNULL:!eNULL: really no NULL ciphers
156 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
157 * !aDSS: no authentication with discrete logarithm DSA algorithm
158 * !SRP:!PSK: no secure remote password or pre-shared key authentication
159 */
160 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
161#elif PY_SSL_DEFAULT_CIPHERS == 2
162/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
163 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
164#else
165 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
166#endif
167
Christian Heimes598894f2016-09-05 23:19:05 +0200168
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000169enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000170 /* these mirror ssl.h */
171 PY_SSL_ERROR_NONE,
172 PY_SSL_ERROR_SSL,
173 PY_SSL_ERROR_WANT_READ,
174 PY_SSL_ERROR_WANT_WRITE,
175 PY_SSL_ERROR_WANT_X509_LOOKUP,
176 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
177 PY_SSL_ERROR_ZERO_RETURN,
178 PY_SSL_ERROR_WANT_CONNECT,
179 /* start of non ssl.h errorcodes */
180 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
181 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
182 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000183};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000184
Thomas Woutersed03b412007-08-28 21:37:11 +0000185enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000186 PY_SSL_CLIENT,
187 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000188};
189
190enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000191 PY_SSL_CERT_NONE,
192 PY_SSL_CERT_OPTIONAL,
193 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000194};
195
196enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000197 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200198 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200199 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100200 PY_SSL_VERSION_TLS1,
201 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200202 PY_SSL_VERSION_TLS1_2,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200203 PY_SSL_VERSION_TLS_CLIENT=0x10,
204 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100205};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200206
Christian Heimes698dde12018-02-27 11:54:43 +0100207enum py_proto_version {
208 PY_PROTO_MINIMUM_SUPPORTED = -2,
209 PY_PROTO_SSLv3 = SSL3_VERSION,
210 PY_PROTO_TLSv1 = TLS1_VERSION,
211 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
212 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
213#ifdef TLS1_3_VERSION
214 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
215#else
216 PY_PROTO_TLSv1_3 = 0x304,
217#endif
218 PY_PROTO_MAXIMUM_SUPPORTED = -1,
219
220/* OpenSSL has no dedicated API to set the minimum version to the maximum
221 * available version, and the other way around. We have to figure out the
222 * minimum and maximum available version on our own and hope for the best.
223 */
224#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
225 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
226#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
227 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
228#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
229 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
230#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
231 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
232#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
233 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
234#else
235 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
236#endif
237
238#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
239 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
240#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
241 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
242#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
243 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
244#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
245 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
246#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
247 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
248#else
249 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
250#endif
251};
252
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000253/* SSL socket object */
254
255#define X509_NAME_MAXLEN 256
256
Antoine Pitroub5218772010-05-21 09:56:06 +0000257
Antoine Pitroud6494802011-07-21 01:11:30 +0200258/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
259 * older SSL, but let's be safe */
260#define PySSL_CB_MAXLEN 128
261
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100262
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000263typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000264 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000265 SSL_CTX *ctx;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500266 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300267 unsigned int alpn_protocols_len;
Christian Heimes11a14932018-02-24 02:35:08 +0100268 PyObject *set_sni_cb;
Christian Heimes1aa9a752013-12-02 02:41:19 +0100269 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100270 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
271 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
272 */
273 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100274 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200275#ifdef TLS1_3_VERSION
276 int post_handshake_auth;
277#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200278 PyObject *msg_cb;
Christian Heimesc7f70692019-05-31 11:44:05 +0200279 PyObject *keylog_filename;
280 BIO *keylog_bio;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200281 /* Cached module state, also used in SSLSocket and SSLSession code. */
282 _sslmodulestate *state;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000283} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000284
Antoine Pitrou152efa22010-05-16 18:19:27 +0000285typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700286 int ssl; /* last seen error from SSL */
287 int c; /* last seen error from libc */
288#ifdef MS_WINDOWS
289 int ws; /* last seen error from winsock */
290#endif
291} _PySSLError;
292
293typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000294 PyObject_HEAD
295 PyObject *Socket; /* weakref to socket on which we're layered */
296 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100297 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200298 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200299 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200300 PyObject *owner; /* Python level "owner" passed to servername callback */
301 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700302 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200303 /* Some SSL callbacks don't have error reporting. Callback wrappers
304 * store exception information on the socket. The handshake, read, write,
305 * and shutdown methods check for chained exceptions.
306 */
307 PyObject *exc_type;
308 PyObject *exc_value;
309 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000310} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000311
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200312typedef struct {
313 PyObject_HEAD
314 BIO *bio;
315 int eof_written;
316} PySSLMemoryBIO;
317
Christian Heimes99a65702016-09-10 23:44:53 +0200318typedef struct {
319 PyObject_HEAD
320 SSL_SESSION *session;
321 PySSLContext *ctx;
322} PySSLSession;
323
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700324static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
325{
326 _PySSLError err = { 0 };
327 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700328#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700329 err.ws = WSAGetLastError();
330 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700331#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700332 err.c = errno;
333 err.ssl = SSL_get_error(ssl, retcode);
334 }
335 return err;
336}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700337
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300338/*[clinic input]
339module _ssl
Christian Heimes7f1305e2021-04-17 20:06:38 +0200340class _ssl._SSLContext "PySSLContext *" "get_state_type(type)->PySSLContext_Type"
341class _ssl._SSLSocket "PySSLSocket *" "get_state_type(type)->PySSLSocket_Type"
342class _ssl.MemoryBIO "PySSLMemoryBIO *" "get_state_type(type)->PySSLMemoryBIO_Type"
343class _ssl.SSLSession "PySSLSession *" "get_state_type(type)->PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300344[clinic start generated code]*/
Christian Heimes7f1305e2021-04-17 20:06:38 +0200345/*[clinic end generated code: output=da39a3ee5e6b4b0d input=d293bed8bae240fd]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300346
347#include "clinic/_ssl.c.h"
348
Victor Stinner14690702015-04-06 22:46:13 +0200349static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000350
Christian Heimes141c5e82018-02-24 21:10:57 +0100351static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
352static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000353
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000354typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000355 SOCKET_IS_NONBLOCKING,
356 SOCKET_IS_BLOCKING,
357 SOCKET_HAS_TIMED_OUT,
358 SOCKET_HAS_BEEN_CLOSED,
359 SOCKET_TOO_LARGE_FOR_SELECT,
360 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000361} timeout_state;
362
Thomas Woutersed03b412007-08-28 21:37:11 +0000363/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000364#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200365#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000366
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200367/* Get the socket from a PySSLSocket, if it has one */
368#define GET_SOCKET(obj) ((obj)->Socket ? \
369 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200370
Victor Stinner14690702015-04-06 22:46:13 +0200371/* If sock is NULL, use a timeout of 0 second */
372#define GET_SOCKET_TIMEOUT(sock) \
373 ((sock != NULL) ? (sock)->sock_timeout : 0)
374
Christian Heimesc7f70692019-05-31 11:44:05 +0200375#include "_ssl/debughelpers.c"
376
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200377/*
378 * SSL errors.
379 */
380
381PyDoc_STRVAR(SSLError_doc,
382"An error occurred in the SSL implementation.");
383
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700384PyDoc_STRVAR(SSLCertVerificationError_doc,
385"A certificate could not be verified.");
386
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200387PyDoc_STRVAR(SSLZeroReturnError_doc,
388"SSL/TLS session closed cleanly.");
389
390PyDoc_STRVAR(SSLWantReadError_doc,
391"Non-blocking SSL socket needs to read more data\n"
392"before the requested operation can be completed.");
393
394PyDoc_STRVAR(SSLWantWriteError_doc,
395"Non-blocking SSL socket needs to write more data\n"
396"before the requested operation can be completed.");
397
398PyDoc_STRVAR(SSLSyscallError_doc,
399"System error when attempting SSL operation.");
400
401PyDoc_STRVAR(SSLEOFError_doc,
402"SSL/TLS connection terminated abruptly.");
403
404static PyObject *
405SSLError_str(PyOSErrorObject *self)
406{
407 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
408 Py_INCREF(self->strerror);
409 return self->strerror;
410 }
411 else
412 return PyObject_Str(self->args);
413}
414
415static PyType_Slot sslerror_type_slots[] = {
Inada Naoki926b0cb2019-04-17 08:39:46 +0900416 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200417 {Py_tp_str, SSLError_str},
418 {0, 0},
419};
420
421static PyType_Spec sslerror_type_spec = {
422 "ssl.SSLError",
423 sizeof(PyOSErrorObject),
424 0,
425 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
426 sslerror_type_slots
427};
428
429static void
Christian Heimes7f1305e2021-04-17 20:06:38 +0200430fill_and_set_sslerror(_sslmodulestate *state,
431 PySSLSocket *sslsock, PyObject *type, int ssl_errno,
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700432 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200433{
434 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700435 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200436 PyObject *init_value, *msg, *key;
437 _Py_IDENTIFIER(reason);
438 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700439 _Py_IDENTIFIER(verify_message);
440 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200441
442 if (errcode != 0) {
443 int lib, reason;
444
445 lib = ERR_GET_LIB(errcode);
446 reason = ERR_GET_REASON(errcode);
447 key = Py_BuildValue("ii", lib, reason);
448 if (key == NULL)
449 goto fail;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200450 reason_obj = PyDict_GetItemWithError(state->err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200451 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300452 if (reason_obj == NULL && PyErr_Occurred()) {
453 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200454 }
455 key = PyLong_FromLong(lib);
456 if (key == NULL)
457 goto fail;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200458 lib_obj = PyDict_GetItemWithError(state->lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200459 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300460 if (lib_obj == NULL && PyErr_Occurred()) {
461 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200462 }
463 if (errstr == NULL)
464 errstr = ERR_reason_error_string(errcode);
465 }
466 if (errstr == NULL)
467 errstr = "unknown error";
468
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700469 /* verify code for cert validation error */
Christian Heimes7f1305e2021-04-17 20:06:38 +0200470 if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700471 const char *verify_str = NULL;
472 long verify_code;
473
474 verify_code = SSL_get_verify_result(sslsock->ssl);
475 verify_code_obj = PyLong_FromLong(verify_code);
476 if (verify_code_obj == NULL) {
477 goto fail;
478 }
479
480 switch (verify_code) {
481 case X509_V_ERR_HOSTNAME_MISMATCH:
482 verify_obj = PyUnicode_FromFormat(
483 "Hostname mismatch, certificate is not valid for '%S'.",
484 sslsock->server_hostname
485 );
486 break;
487 case X509_V_ERR_IP_ADDRESS_MISMATCH:
488 verify_obj = PyUnicode_FromFormat(
489 "IP address mismatch, certificate is not valid for '%S'.",
490 sslsock->server_hostname
491 );
492 break;
493 default:
494 verify_str = X509_verify_cert_error_string(verify_code);
495 if (verify_str != NULL) {
496 verify_obj = PyUnicode_FromString(verify_str);
497 } else {
498 verify_obj = Py_None;
499 Py_INCREF(verify_obj);
500 }
501 break;
502 }
503 if (verify_obj == NULL) {
504 goto fail;
505 }
506 }
507
508 if (verify_obj && reason_obj && lib_obj)
509 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
510 lib_obj, reason_obj, errstr, verify_obj,
511 lineno);
512 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200513 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
514 lib_obj, reason_obj, errstr, lineno);
515 else if (lib_obj)
516 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
517 lib_obj, errstr, lineno);
518 else
519 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200520 if (msg == NULL)
521 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100522
Paul Monsonfb7e7502019-05-15 15:38:55 -0700523 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100524 if (init_value == NULL)
525 goto fail;
526
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200527 err_value = PyObject_CallObject(type, init_value);
528 Py_DECREF(init_value);
529 if (err_value == NULL)
530 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100531
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200532 if (reason_obj == NULL)
533 reason_obj = Py_None;
534 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
535 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700536
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200537 if (lib_obj == NULL)
538 lib_obj = Py_None;
539 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
540 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700541
Christian Heimes7f1305e2021-04-17 20:06:38 +0200542 if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700543 /* Only set verify code / message for SSLCertVerificationError */
544 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
545 verify_code_obj))
546 goto fail;
547 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
548 goto fail;
549 }
550
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200551 PyErr_SetObject(type, err_value);
552fail:
553 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700554 Py_XDECREF(verify_code_obj);
555 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200556}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000557
Christian Heimesc7f70692019-05-31 11:44:05 +0200558static int
559PySSL_ChainExceptions(PySSLSocket *sslsock) {
560 if (sslsock->exc_type == NULL)
561 return 0;
562
563 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
564 sslsock->exc_type = NULL;
565 sslsock->exc_value = NULL;
566 sslsock->exc_tb = NULL;
567 return -1;
568}
569
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000570static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700571PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000572{
Christian Heimes7f1305e2021-04-17 20:06:38 +0200573 PyObject *type;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200574 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700575 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000576 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200577 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000578
Christian Heimes7f1305e2021-04-17 20:06:38 +0200579 assert(sslsock != NULL);
580
581 _sslmodulestate *state = get_state_sock(sslsock);
582 type = state->PySSLErrorObject;
583
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000584 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200585 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000586
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700587 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700588 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000589
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700590 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000591 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200592 errstr = "TLS/SSL connection has been closed (EOF)";
Christian Heimes7f1305e2021-04-17 20:06:38 +0200593 type = state->PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000594 p = PY_SSL_ERROR_ZERO_RETURN;
595 break;
596 case SSL_ERROR_WANT_READ:
597 errstr = "The operation did not complete (read)";
Christian Heimes7f1305e2021-04-17 20:06:38 +0200598 type = state->PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000599 p = PY_SSL_ERROR_WANT_READ;
600 break;
601 case SSL_ERROR_WANT_WRITE:
602 p = PY_SSL_ERROR_WANT_WRITE;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200603 type = state->PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000604 errstr = "The operation did not complete (write)";
605 break;
606 case SSL_ERROR_WANT_X509_LOOKUP:
607 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000608 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000609 break;
610 case SSL_ERROR_WANT_CONNECT:
611 p = PY_SSL_ERROR_WANT_CONNECT;
612 errstr = "The operation did not complete (connect)";
613 break;
614 case SSL_ERROR_SYSCALL:
615 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000616 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700617 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000619 p = PY_SSL_ERROR_EOF;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200620 type = state->PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000621 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200622 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000623 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000624 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700625#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700626 if (err.ws) {
627 return PyErr_SetFromWindowsErr(err.ws);
628 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700629#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700630 if (err.c) {
631 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700632 return PyErr_SetFromErrno(PyExc_OSError);
633 }
Dima Tisnek495bd032020-08-16 02:01:19 +0900634 else {
635 p = PY_SSL_ERROR_EOF;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200636 type = state->PySSLEOFErrorObject;
Dima Tisnek495bd032020-08-16 02:01:19 +0900637 errstr = "EOF occurred in violation of protocol";
638 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000639 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000640 p = PY_SSL_ERROR_SYSCALL;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200641 type = state->PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000642 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000643 }
644 } else {
645 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000646 }
647 break;
648 }
649 case SSL_ERROR_SSL:
650 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000651 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700652 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200653 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000654 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700655 }
656 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
657 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200658 type = state->PySSLCertVerificationErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700659 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000660 break;
661 }
662 default:
663 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
664 errstr = "Invalid error code";
665 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 }
Christian Heimes7f1305e2021-04-17 20:06:38 +0200667 fill_and_set_sslerror(state, sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000668 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200669 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000670 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000671}
672
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000673static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +0200674_setSSLError (_sslmodulestate *state, const char *errstr, int errcode, const char *filename, int lineno)
675{
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200676 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000677 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200678 else
679 errcode = 0;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200680 fill_and_set_sslerror(state, NULL, state->PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000681 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000682 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000683}
684
Christian Heimes61d478c2018-01-27 15:51:38 +0100685/*
686 * SSL objects
687 */
688
689static int
690_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
691{
692 int retval = -1;
693 ASN1_OCTET_STRING *ip;
694 PyObject *hostname;
695 size_t len;
696
697 assert(server_hostname);
698
699 /* Disable OpenSSL's special mode with leading dot in hostname:
700 * When name starts with a dot (e.g ".example.com"), it will be
701 * matched by a certificate valid for any sub-domain of name.
702 */
703 len = strlen(server_hostname);
704 if (len == 0 || *server_hostname == '.') {
705 PyErr_SetString(
706 PyExc_ValueError,
707 "server_hostname cannot be an empty string or start with a "
708 "leading dot.");
709 return retval;
710 }
711
712 /* inet_pton is not available on all platforms. */
713 ip = a2i_IPADDRESS(server_hostname);
714 if (ip == NULL) {
715 ERR_clear_error();
716 }
717
Christian Heimes11a14932018-02-24 02:35:08 +0100718 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100719 if (hostname == NULL) {
720 goto error;
721 }
722 self->server_hostname = hostname;
723
724 /* Only send SNI extension for non-IP hostnames */
725 if (ip == NULL) {
726 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200727 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzc32f2972020-10-25 12:02:30 -0600728 goto error;
Christian Heimes61d478c2018-01-27 15:51:38 +0100729 }
730 }
731 if (self->ctx->check_hostname) {
732 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
733 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200734 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
735 strlen(server_hostname))) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200736 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes61d478c2018-01-27 15:51:38 +0100737 goto error;
738 }
739 } else {
Christian Heimesa871f692020-06-01 08:58:14 +0200740 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
Christian Heimes61d478c2018-01-27 15:51:38 +0100741 ASN1_STRING_length(ip))) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200742 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes61d478c2018-01-27 15:51:38 +0100743 goto error;
744 }
745 }
746 }
747 retval = 0;
748 error:
749 if (ip != NULL) {
750 ASN1_OCTET_STRING_free(ip);
751 }
752 return retval;
753}
754
Antoine Pitrou152efa22010-05-16 18:19:27 +0000755static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100756newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000757 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200758 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100759 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200760 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000761{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000762 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100763 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700764 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000765
Christian Heimes7f1305e2021-04-17 20:06:38 +0200766 self = PyObject_New(PySSLSocket, get_state_ctx(sslctx)->PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000767 if (self == NULL)
768 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000769
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000771 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100772 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700773 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200774 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200775 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700776 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700777 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200778 self->exc_type = NULL;
779 self->exc_value = NULL;
780 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200781
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000782 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000784
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000786 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000787 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700788 if (self->ssl == NULL) {
789 Py_DECREF(self);
Christian Heimes7f1305e2021-04-17 20:06:38 +0200790 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytz4c49da02018-12-07 03:11:30 -0700791 return NULL;
792 }
Christian Heimesb467d9a2021-04-17 10:07:19 +0200793 /* bpo43522 and OpenSSL < 1.1.1l: copy hostflags manually */
794#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION < 0x101010cf
795 X509_VERIFY_PARAM *ssl_params = SSL_get0_param(self->ssl);
796 X509_VERIFY_PARAM_set_hostflags(ssl_params, sslctx->hostflags);
797#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200798 SSL_set_app_data(self->ssl, self);
799 if (sock) {
800 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
801 } else {
802 /* BIOs are reference counted and SSL_set_bio borrows our reference.
803 * To prevent a double free in memory_bio_dealloc() we need to take an
804 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200805 BIO_up_ref(inbio->bio);
806 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200807 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
808 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400809 SSL_set_mode(self->ssl,
810 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000811
Christian Heimesf0f59302019-07-01 08:29:17 +0200812#ifdef TLS1_3_VERSION
813 if (sslctx->post_handshake_auth == 1) {
814 if (socket_type == PY_SSL_SERVER) {
815 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
816 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
817 * only in combination with SSL_VERIFY_PEER flag. */
818 int mode = SSL_get_verify_mode(self->ssl);
819 if (mode & SSL_VERIFY_PEER) {
820 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
821 verify_cb = SSL_get_verify_callback(self->ssl);
822 mode |= SSL_VERIFY_POST_HANDSHAKE;
823 SSL_set_verify(self->ssl, mode, verify_cb);
824 }
825 } else {
826 /* client socket */
827 SSL_set_post_handshake_auth(self->ssl, 1);
828 }
829 }
830#endif
831
Christian Heimes61d478c2018-01-27 15:51:38 +0100832 if (server_hostname != NULL) {
833 if (_ssl_configure_hostname(self, server_hostname) < 0) {
834 Py_DECREF(self);
835 return NULL;
836 }
837 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 /* If the socket is in non-blocking mode or timeout mode, set the BIO
839 * to non-blocking mode (blocking is the default)
840 */
Victor Stinnere2452312015-03-28 03:00:46 +0100841 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000842 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
843 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
844 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000845
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000846 PySSL_BEGIN_ALLOW_THREADS
847 if (socket_type == PY_SSL_CLIENT)
848 SSL_set_connect_state(self->ssl);
849 else
850 SSL_set_accept_state(self->ssl);
851 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000852
Antoine Pitroud6494802011-07-21 01:11:30 +0200853 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200854 if (sock != NULL) {
855 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
856 if (self->Socket == NULL) {
857 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200858 return NULL;
859 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100860 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100861 if (owner && owner != Py_None) {
862 if (PySSL_set_owner(self, owner, NULL) == -1) {
863 Py_DECREF(self);
864 return NULL;
865 }
866 }
867 if (session && session != Py_None) {
868 if (PySSL_set_session(self, session, NULL) == -1) {
869 Py_DECREF(self);
870 return NULL;
871 }
872 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000873 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000874}
875
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000876/* SSL object methods */
877
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300878/*[clinic input]
879_ssl._SSLSocket.do_handshake
880[clinic start generated code]*/
881
882static PyObject *
883_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
884/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000885{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000886 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700887 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000888 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200889 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200890 _PyTime_t timeout, deadline = 0;
891 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000892
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200893 if (sock) {
894 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200895 _setSSLError(get_state_sock(self),
896 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200897 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
898 return NULL;
899 }
900 Py_INCREF(sock);
901
902 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100903 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200904 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
905 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000906 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000907
Victor Stinner14690702015-04-06 22:46:13 +0200908 timeout = GET_SOCKET_TIMEOUT(sock);
909 has_timeout = (timeout > 0);
910 if (has_timeout)
911 deadline = _PyTime_GetMonotonicClock() + timeout;
912
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000913 /* Actually negotiate SSL connection */
914 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000915 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000916 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000917 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700918 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000919 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700920 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200921
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000922 if (PyErr_CheckSignals())
923 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200924
Victor Stinner14690702015-04-06 22:46:13 +0200925 if (has_timeout)
926 timeout = deadline - _PyTime_GetMonotonicClock();
927
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700928 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200929 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700930 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200931 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 } else {
933 sockstate = SOCKET_OPERATION_OK;
934 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200935
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +0100937 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000938 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000939 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200941 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000942 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000943 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200945 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000946 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000947 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
949 break;
950 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700951 } while (err.ssl == SSL_ERROR_WANT_READ ||
952 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200953 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000954 if (ret < 1)
955 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +0200956 if (PySSL_ChainExceptions(self) < 0)
957 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200958 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000959error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200960 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +0200961 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000962 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000963}
964
Thomas Woutersed03b412007-08-28 21:37:11 +0000965static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +0200966_asn1obj2py(_sslmodulestate *state, const ASN1_OBJECT *name, int no_name)
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300967{
968 char buf[X509_NAME_MAXLEN];
969 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300971 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000972
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300973 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200975 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300976 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000977 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300978 /* initial buffer is too small for oid + terminating null byte */
979 if (buflen > X509_NAME_MAXLEN - 1) {
980 /* make OBJ_obj2txt() calculate the required buflen */
981 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
982 /* allocate len + 1 for terminating NULL byte */
983 namebuf = PyMem_Malloc(buflen + 1);
984 if (namebuf == NULL) {
985 PyErr_NoMemory();
986 return NULL;
987 }
988 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
989 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200990 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300991 goto done;
992 }
993 }
994 if (!buflen && no_name) {
995 Py_INCREF(Py_None);
996 name_obj = Py_None;
997 }
998 else {
999 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1000 }
1001
1002 done:
1003 if (buf != namebuf) {
1004 PyMem_Free(namebuf);
1005 }
1006 return name_obj;
1007}
1008
1009static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001010_create_tuple_for_attribute(_sslmodulestate *state,
1011 ASN1_OBJECT *name, ASN1_STRING *value)
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001012{
1013 Py_ssize_t buflen;
1014 unsigned char *valuebuf = NULL;
1015 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001016
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001017 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1018 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001019 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001020 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001021 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02001022 attr = Py_BuildValue("Ns#", _asn1obj2py(state, name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001023 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001024 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001025}
1026
1027static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001028_create_tuple_for_X509_NAME (_sslmodulestate *state, X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001029{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001030 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1031 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1032 PyObject *rdnt;
1033 PyObject *attr = NULL; /* tuple to hold an attribute */
1034 int entry_count = X509_NAME_entry_count(xname);
1035 X509_NAME_ENTRY *entry;
1036 ASN1_OBJECT *name;
1037 ASN1_STRING *value;
1038 int index_counter;
1039 int rdn_level = -1;
1040 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001041
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001042 dn = PyList_New(0);
1043 if (dn == NULL)
1044 return NULL;
1045 /* now create another tuple to hold the top-level RDN */
1046 rdn = PyList_New(0);
1047 if (rdn == NULL)
1048 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001049
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 for (index_counter = 0;
1051 index_counter < entry_count;
1052 index_counter++)
1053 {
1054 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001055
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001056 /* check to see if we've gotten to a new RDN */
1057 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001058 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 /* yes, new RDN */
1060 /* add old RDN to DN */
1061 rdnt = PyList_AsTuple(rdn);
1062 Py_DECREF(rdn);
1063 if (rdnt == NULL)
1064 goto fail0;
1065 retcode = PyList_Append(dn, rdnt);
1066 Py_DECREF(rdnt);
1067 if (retcode < 0)
1068 goto fail0;
1069 /* create new RDN */
1070 rdn = PyList_New(0);
1071 if (rdn == NULL)
1072 goto fail0;
1073 }
1074 }
Christian Heimes598894f2016-09-05 23:19:05 +02001075 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001076
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001077 /* now add this attribute to the current RDN */
1078 name = X509_NAME_ENTRY_get_object(entry);
1079 value = X509_NAME_ENTRY_get_data(entry);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001080 attr = _create_tuple_for_attribute(state, name, value);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081 /*
1082 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1083 entry->set,
1084 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1085 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1086 */
1087 if (attr == NULL)
1088 goto fail1;
1089 retcode = PyList_Append(rdn, attr);
1090 Py_DECREF(attr);
1091 if (retcode < 0)
1092 goto fail1;
1093 }
1094 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001095 if (rdn != NULL) {
1096 if (PyList_GET_SIZE(rdn) > 0) {
1097 rdnt = PyList_AsTuple(rdn);
1098 Py_DECREF(rdn);
1099 if (rdnt == NULL)
1100 goto fail0;
1101 retcode = PyList_Append(dn, rdnt);
1102 Py_DECREF(rdnt);
1103 if (retcode < 0)
1104 goto fail0;
1105 }
1106 else {
1107 Py_DECREF(rdn);
1108 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001110
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 /* convert list to tuple */
1112 rdnt = PyList_AsTuple(dn);
1113 Py_DECREF(dn);
1114 if (rdnt == NULL)
1115 return NULL;
1116 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001117
1118 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001119 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001120
1121 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001122 Py_XDECREF(dn);
1123 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001124}
1125
1126static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001127_get_peer_alt_names (_sslmodulestate *state, X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001128
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 /* this code follows the procedure outlined in
1130 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1131 function to extract the STACK_OF(GENERAL_NAME),
1132 then iterates through the stack to add the
1133 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001134
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001135 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001136 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001137 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001138 GENERAL_NAMES *names = NULL;
1139 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 BIO *biobuf = NULL;
1141 char buf[2048];
1142 char *vptr;
1143 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001144
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 if (certificate == NULL)
1146 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001147
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 /* get a memory buffer */
1149 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001150 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001151 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001152 return NULL;
1153 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001154
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001155 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1156 certificate, NID_subject_alt_name, NULL, NULL);
1157 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001158 if (peer_alt_names == Py_None) {
1159 peer_alt_names = PyList_New(0);
1160 if (peer_alt_names == NULL)
1161 goto fail;
1162 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001163
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001165 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001166 int gntype;
1167 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001168
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001169 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001170 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001171 switch (gntype) {
1172 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001173 /* we special-case DirName as a tuple of
1174 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001175
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001176 t = PyTuple_New(2);
1177 if (t == NULL) {
1178 goto fail;
1179 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001180
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001181 v = PyUnicode_FromString("DirName");
1182 if (v == NULL) {
1183 Py_DECREF(t);
1184 goto fail;
1185 }
1186 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001187
Christian Heimes7f1305e2021-04-17 20:06:38 +02001188 v = _create_tuple_for_X509_NAME(state, name->d.dirn);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001189 if (v == NULL) {
1190 Py_DECREF(t);
1191 goto fail;
1192 }
1193 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001194 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001195
Christian Heimes824f7f32013-08-17 00:54:47 +02001196 case GEN_EMAIL:
1197 case GEN_DNS:
1198 case GEN_URI:
1199 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1200 correctly, CVE-2013-4238 */
1201 t = PyTuple_New(2);
1202 if (t == NULL)
1203 goto fail;
1204 switch (gntype) {
1205 case GEN_EMAIL:
1206 v = PyUnicode_FromString("email");
1207 as = name->d.rfc822Name;
1208 break;
1209 case GEN_DNS:
1210 v = PyUnicode_FromString("DNS");
1211 as = name->d.dNSName;
1212 break;
1213 case GEN_URI:
1214 v = PyUnicode_FromString("URI");
1215 as = name->d.uniformResourceIdentifier;
1216 break;
1217 }
1218 if (v == NULL) {
1219 Py_DECREF(t);
1220 goto fail;
1221 }
1222 PyTuple_SET_ITEM(t, 0, v);
Christian Heimesa871f692020-06-01 08:58:14 +02001223 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
Christian Heimes824f7f32013-08-17 00:54:47 +02001224 ASN1_STRING_length(as));
1225 if (v == NULL) {
1226 Py_DECREF(t);
1227 goto fail;
1228 }
1229 PyTuple_SET_ITEM(t, 1, v);
1230 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001231
Christian Heimes1c03abd2016-09-06 23:25:35 +02001232 case GEN_RID:
1233 t = PyTuple_New(2);
1234 if (t == NULL)
1235 goto fail;
1236
1237 v = PyUnicode_FromString("Registered ID");
1238 if (v == NULL) {
1239 Py_DECREF(t);
1240 goto fail;
1241 }
1242 PyTuple_SET_ITEM(t, 0, v);
1243
1244 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1245 if (len < 0) {
1246 Py_DECREF(t);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001247 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes1c03abd2016-09-06 23:25:35 +02001248 goto fail;
1249 } else if (len >= (int)sizeof(buf)) {
1250 v = PyUnicode_FromString("<INVALID>");
1251 } else {
1252 v = PyUnicode_FromStringAndSize(buf, len);
1253 }
1254 if (v == NULL) {
1255 Py_DECREF(t);
1256 goto fail;
1257 }
1258 PyTuple_SET_ITEM(t, 1, v);
1259 break;
1260
Christian Heimes2b7de662019-12-07 17:59:36 +01001261 case GEN_IPADD:
1262 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1263 * the trailing newline. Remove it in all versions
1264 */
1265 t = PyTuple_New(2);
1266 if (t == NULL)
1267 goto fail;
1268
1269 v = PyUnicode_FromString("IP Address");
1270 if (v == NULL) {
1271 Py_DECREF(t);
1272 goto fail;
1273 }
1274 PyTuple_SET_ITEM(t, 0, v);
1275
1276 if (name->d.ip->length == 4) {
1277 unsigned char *p = name->d.ip->data;
1278 v = PyUnicode_FromFormat(
1279 "%d.%d.%d.%d",
1280 p[0], p[1], p[2], p[3]
1281 );
1282 } else if (name->d.ip->length == 16) {
1283 /* PyUnicode_FromFormat() does not support %X */
1284 unsigned char *p = name->d.ip->data;
1285 len = sprintf(
1286 buf,
1287 "%X:%X:%X:%X:%X:%X:%X:%X",
1288 p[0] << 8 | p[1],
1289 p[2] << 8 | p[3],
1290 p[4] << 8 | p[5],
1291 p[6] << 8 | p[7],
1292 p[8] << 8 | p[9],
1293 p[10] << 8 | p[11],
1294 p[12] << 8 | p[13],
1295 p[14] << 8 | p[15]
1296 );
1297 v = PyUnicode_FromStringAndSize(buf, len);
1298 } else {
1299 v = PyUnicode_FromString("<invalid>");
1300 }
1301
1302 if (v == NULL) {
1303 Py_DECREF(t);
1304 goto fail;
1305 }
1306 PyTuple_SET_ITEM(t, 1, v);
1307 break;
1308
Christian Heimes824f7f32013-08-17 00:54:47 +02001309 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001310 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001311 switch (gntype) {
1312 /* check for new general name type */
1313 case GEN_OTHERNAME:
1314 case GEN_X400:
1315 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001316 case GEN_RID:
1317 break;
1318 default:
1319 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1320 "Unknown general name type %d",
1321 gntype) == -1) {
1322 goto fail;
1323 }
1324 break;
1325 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001326 (void) BIO_reset(biobuf);
1327 GENERAL_NAME_print(biobuf, name);
1328 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1329 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001330 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001331 goto fail;
1332 }
1333 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001334 if (vptr == NULL) {
1335 PyErr_Format(PyExc_ValueError,
1336 "Invalid value %.200s",
1337 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001339 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 t = PyTuple_New(2);
1341 if (t == NULL)
1342 goto fail;
1343 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1344 if (v == NULL) {
1345 Py_DECREF(t);
1346 goto fail;
1347 }
1348 PyTuple_SET_ITEM(t, 0, v);
1349 v = PyUnicode_FromStringAndSize((vptr + 1),
1350 (len - (vptr - buf + 1)));
1351 if (v == NULL) {
1352 Py_DECREF(t);
1353 goto fail;
1354 }
1355 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001356 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001357 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001358
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001360
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 if (PyList_Append(peer_alt_names, t) < 0) {
1362 Py_DECREF(t);
1363 goto fail;
1364 }
1365 Py_DECREF(t);
1366 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001367 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 }
1369 BIO_free(biobuf);
1370 if (peer_alt_names != Py_None) {
1371 v = PyList_AsTuple(peer_alt_names);
1372 Py_DECREF(peer_alt_names);
1373 return v;
1374 } else {
1375 return peer_alt_names;
1376 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001377
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001378
1379 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001380 if (biobuf != NULL)
1381 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001382
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001383 if (peer_alt_names != Py_None) {
1384 Py_XDECREF(peer_alt_names);
1385 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001386
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001387 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001388}
1389
1390static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001391_get_aia_uri(X509 *certificate, int nid) {
1392 PyObject *lst = NULL, *ostr = NULL;
1393 int i, result;
1394 AUTHORITY_INFO_ACCESS *info;
1395
1396 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001397 if (info == NULL)
1398 return Py_None;
1399 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1400 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001401 return Py_None;
1402 }
1403
1404 if ((lst = PyList_New(0)) == NULL) {
1405 goto fail;
1406 }
1407
1408 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1409 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1410 ASN1_IA5STRING *uri;
1411
1412 if ((OBJ_obj2nid(ad->method) != nid) ||
1413 (ad->location->type != GEN_URI)) {
1414 continue;
1415 }
1416 uri = ad->location->d.uniformResourceIdentifier;
1417 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1418 uri->length);
1419 if (ostr == NULL) {
1420 goto fail;
1421 }
1422 result = PyList_Append(lst, ostr);
1423 Py_DECREF(ostr);
1424 if (result < 0) {
1425 goto fail;
1426 }
1427 }
1428 AUTHORITY_INFO_ACCESS_free(info);
1429
1430 /* convert to tuple or None */
1431 if (PyList_Size(lst) == 0) {
1432 Py_DECREF(lst);
1433 return Py_None;
1434 } else {
1435 PyObject *tup;
1436 tup = PyList_AsTuple(lst);
1437 Py_DECREF(lst);
1438 return tup;
1439 }
1440
1441 fail:
1442 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001443 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001444 return NULL;
1445}
1446
1447static PyObject *
1448_get_crl_dp(X509 *certificate) {
1449 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001450 int i, j;
1451 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001452
Christian Heimes598894f2016-09-05 23:19:05 +02001453 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001454
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001455 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001456 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001457
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001458 lst = PyList_New(0);
1459 if (lst == NULL)
1460 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001461
1462 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1463 DIST_POINT *dp;
1464 STACK_OF(GENERAL_NAME) *gns;
1465
1466 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001467 if (dp->distpoint == NULL) {
1468 /* Ignore empty DP value, CVE-2019-5010 */
1469 continue;
1470 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001471 gns = dp->distpoint->name.fullname;
1472
1473 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1474 GENERAL_NAME *gn;
1475 ASN1_IA5STRING *uri;
1476 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001477 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001478
1479 gn = sk_GENERAL_NAME_value(gns, j);
1480 if (gn->type != GEN_URI) {
1481 continue;
1482 }
1483 uri = gn->d.uniformResourceIdentifier;
1484 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1485 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001486 if (ouri == NULL)
1487 goto done;
1488
1489 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001490 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001491 if (err < 0)
1492 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001493 }
1494 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001495
1496 /* Convert to tuple. */
1497 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1498
1499 done:
1500 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001501 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001502 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001503}
1504
1505static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001506_decode_certificate(_sslmodulestate *state, X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001507
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001508 PyObject *retval = NULL;
1509 BIO *biobuf = NULL;
1510 PyObject *peer;
1511 PyObject *peer_alt_names = NULL;
1512 PyObject *issuer;
1513 PyObject *version;
1514 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001515 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001516 ASN1_INTEGER *serialNumber;
1517 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001518 int len, result;
Christian Heimesa871f692020-06-01 08:58:14 +02001519 const ASN1_TIME *notBefore, *notAfter;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001520 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001521
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522 retval = PyDict_New();
1523 if (retval == NULL)
1524 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001526 peer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001527 state,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 X509_get_subject_name(certificate));
1529 if (peer == NULL)
1530 goto fail0;
1531 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1532 Py_DECREF(peer);
1533 goto fail0;
1534 }
1535 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001536
Antoine Pitroufb046912010-11-09 20:21:19 +00001537 issuer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001538 state,
Antoine Pitroufb046912010-11-09 20:21:19 +00001539 X509_get_issuer_name(certificate));
1540 if (issuer == NULL)
1541 goto fail0;
1542 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001543 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001544 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001545 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001546 Py_DECREF(issuer);
1547
1548 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001549 if (version == NULL)
1550 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001551 if (PyDict_SetItemString(retval, "version", version) < 0) {
1552 Py_DECREF(version);
1553 goto fail0;
1554 }
1555 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001556
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001557 /* get a memory buffer */
1558 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001559 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001560 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001561 goto fail0;
1562 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001563
Antoine Pitroufb046912010-11-09 20:21:19 +00001564 (void) BIO_reset(biobuf);
1565 serialNumber = X509_get_serialNumber(certificate);
1566 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1567 i2a_ASN1_INTEGER(biobuf, serialNumber);
1568 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1569 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001570 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001571 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001572 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001573 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1574 if (sn_obj == NULL)
1575 goto fail1;
1576 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1577 Py_DECREF(sn_obj);
1578 goto fail1;
1579 }
1580 Py_DECREF(sn_obj);
1581
1582 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001583 notBefore = X509_get0_notBefore(certificate);
Antoine Pitroufb046912010-11-09 20:21:19 +00001584 ASN1_TIME_print(biobuf, notBefore);
1585 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1586 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001587 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001588 goto fail1;
1589 }
1590 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1591 if (pnotBefore == NULL)
1592 goto fail1;
1593 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1594 Py_DECREF(pnotBefore);
1595 goto fail1;
1596 }
1597 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001598
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001599 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001600 notAfter = X509_get0_notAfter(certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001601 ASN1_TIME_print(biobuf, notAfter);
1602 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1603 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001604 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001605 goto fail1;
1606 }
1607 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1608 if (pnotAfter == NULL)
1609 goto fail1;
1610 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1611 Py_DECREF(pnotAfter);
1612 goto fail1;
1613 }
1614 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001615
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001616 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001617
Christian Heimes7f1305e2021-04-17 20:06:38 +02001618 peer_alt_names = _get_peer_alt_names(state, certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001619 if (peer_alt_names == NULL)
1620 goto fail1;
1621 else if (peer_alt_names != Py_None) {
1622 if (PyDict_SetItemString(retval, "subjectAltName",
1623 peer_alt_names) < 0) {
1624 Py_DECREF(peer_alt_names);
1625 goto fail1;
1626 }
1627 Py_DECREF(peer_alt_names);
1628 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001629
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001630 /* Authority Information Access: OCSP URIs */
1631 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1632 if (obj == NULL) {
1633 goto fail1;
1634 } else if (obj != Py_None) {
1635 result = PyDict_SetItemString(retval, "OCSP", obj);
1636 Py_DECREF(obj);
1637 if (result < 0) {
1638 goto fail1;
1639 }
1640 }
1641
1642 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1643 if (obj == NULL) {
1644 goto fail1;
1645 } else if (obj != Py_None) {
1646 result = PyDict_SetItemString(retval, "caIssuers", obj);
1647 Py_DECREF(obj);
1648 if (result < 0) {
1649 goto fail1;
1650 }
1651 }
1652
1653 /* CDP (CRL distribution points) */
1654 obj = _get_crl_dp(certificate);
1655 if (obj == NULL) {
1656 goto fail1;
1657 } else if (obj != Py_None) {
1658 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1659 Py_DECREF(obj);
1660 if (result < 0) {
1661 goto fail1;
1662 }
1663 }
1664
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001665 BIO_free(biobuf);
1666 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001667
1668 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001669 if (biobuf != NULL)
1670 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001671 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001672 Py_XDECREF(retval);
1673 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001674}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001675
Christian Heimes9a5395a2013-06-17 15:44:12 +02001676static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001677_certificate_to_der(_sslmodulestate *state, X509 *certificate)
Christian Heimes9a5395a2013-06-17 15:44:12 +02001678{
1679 unsigned char *bytes_buf = NULL;
1680 int len;
1681 PyObject *retval;
1682
1683 bytes_buf = NULL;
1684 len = i2d_X509(certificate, &bytes_buf);
1685 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001686 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes9a5395a2013-06-17 15:44:12 +02001687 return NULL;
1688 }
1689 /* this is actually an immutable bytes sequence */
1690 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1691 OPENSSL_free(bytes_buf);
1692 return retval;
1693}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001694
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001695/*[clinic input]
1696_ssl._test_decode_cert
1697 path: object(converter="PyUnicode_FSConverter")
1698 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001699
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001700[clinic start generated code]*/
1701
1702static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001703_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1704/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001705{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001706 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001707 X509 *x=NULL;
1708 BIO *cert;
Christian Heimes7f1305e2021-04-17 20:06:38 +02001709 _sslmodulestate *state = get_ssl_state(module);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001710
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001711 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001712 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001713 "Can't malloc memory to read file");
1714 goto fail0;
1715 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001716
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001717 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001718 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001719 "Can't open file");
1720 goto fail0;
1721 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001722
Alex Gaynor40dad952019-08-15 08:31:28 -04001723 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001724 if (x == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001725 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001726 "Error decoding PEM-encoded file");
1727 goto fail0;
1728 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001729
Christian Heimes7f1305e2021-04-17 20:06:38 +02001730 retval = _decode_certificate(state, x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001731 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001732
1733 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001734 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001735 if (cert != NULL) BIO_free(cert);
1736 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001737}
1738
1739
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001740/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001741_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001742 der as binary_mode: bool = False
1743 /
1744
1745Returns the certificate for the peer.
1746
1747If no certificate was provided, returns None. If a certificate was
1748provided, but not validated, returns an empty dictionary. Otherwise
1749returns a dict containing information about the peer certificate.
1750
1751If the optional argument is True, returns a DER-encoded copy of the
1752peer certificate, or None if no certificate was provided. This will
1753return the certificate even if it wasn't validated.
1754[clinic start generated code]*/
1755
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001756static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001757_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1758/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001759{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001760 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001761 X509 *peer_cert;
1762 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001763
Christian Heimes66dc33b2017-05-23 16:02:02 -07001764 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001765 PyErr_SetString(PyExc_ValueError,
1766 "handshake not done yet");
1767 return NULL;
1768 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001769 peer_cert = SSL_get_peer_certificate(self->ssl);
1770 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001771 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001772
Antoine Pitrou721738f2012-08-15 23:20:39 +02001773 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001774 /* return cert in DER-encoded format */
Christian Heimes7f1305e2021-04-17 20:06:38 +02001775 result = _certificate_to_der(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001776 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001777 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001778 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001779 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001780 else
Christian Heimes7f1305e2021-04-17 20:06:38 +02001781 result = _decode_certificate(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001782 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001783 X509_free(peer_cert);
1784 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001785}
1786
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001787static PyObject *
1788cipher_to_tuple(const SSL_CIPHER *cipher)
1789{
1790 const char *cipher_name, *cipher_protocol;
1791 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001792 if (retval == NULL)
1793 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001794
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001795 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001796 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001797 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001798 PyTuple_SET_ITEM(retval, 0, Py_None);
1799 } else {
1800 v = PyUnicode_FromString(cipher_name);
1801 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001802 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001803 PyTuple_SET_ITEM(retval, 0, v);
1804 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001805
1806 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001807 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001808 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001809 PyTuple_SET_ITEM(retval, 1, Py_None);
1810 } else {
1811 v = PyUnicode_FromString(cipher_protocol);
1812 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001813 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001814 PyTuple_SET_ITEM(retval, 1, v);
1815 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001816
1817 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001818 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001819 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001820 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001821
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001822 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001823
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001824 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 Py_DECREF(retval);
1826 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001827}
1828
Christian Heimes25bfcd52016-09-06 00:04:45 +02001829static PyObject *
1830cipher_to_dict(const SSL_CIPHER *cipher)
1831{
1832 const char *cipher_name, *cipher_protocol;
1833
1834 unsigned long cipher_id;
1835 int alg_bits, strength_bits, len;
1836 char buf[512] = {0};
Christian Heimes25bfcd52016-09-06 00:04:45 +02001837 int aead, nid;
1838 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001839
1840 /* can be NULL */
1841 cipher_name = SSL_CIPHER_get_name(cipher);
1842 cipher_protocol = SSL_CIPHER_get_version(cipher);
1843 cipher_id = SSL_CIPHER_get_id(cipher);
1844 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001845 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1846 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001847 if (len > 1 && buf[len-1] == '\n')
1848 buf[len-1] = '\0';
1849 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1850
Christian Heimes25bfcd52016-09-06 00:04:45 +02001851 aead = SSL_CIPHER_is_aead(cipher);
1852 nid = SSL_CIPHER_get_cipher_nid(cipher);
1853 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1854 nid = SSL_CIPHER_get_digest_nid(cipher);
1855 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1856 nid = SSL_CIPHER_get_kx_nid(cipher);
1857 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1858 nid = SSL_CIPHER_get_auth_nid(cipher);
1859 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001860
Victor Stinner410b9882016-09-12 12:00:23 +02001861 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001862 "{sksssssssisi"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001863 "sOssssssss"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001864 "}",
1865 "id", cipher_id,
1866 "name", cipher_name,
1867 "protocol", cipher_protocol,
1868 "description", buf,
1869 "strength_bits", strength_bits,
1870 "alg_bits", alg_bits
Christian Heimes25bfcd52016-09-06 00:04:45 +02001871 ,"aead", aead ? Py_True : Py_False,
1872 "symmetric", skcipher,
1873 "digest", digest,
1874 "kea", kx,
1875 "auth", auth
Christian Heimes25bfcd52016-09-06 00:04:45 +02001876 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001877}
Christian Heimes25bfcd52016-09-06 00:04:45 +02001878
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001879/*[clinic input]
1880_ssl._SSLSocket.shared_ciphers
1881[clinic start generated code]*/
1882
1883static PyObject *
1884_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1885/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001886{
1887 STACK_OF(SSL_CIPHER) *ciphers;
1888 int i;
1889 PyObject *res;
1890
Christian Heimes598894f2016-09-05 23:19:05 +02001891 ciphers = SSL_get_ciphers(self->ssl);
1892 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001893 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001894 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1895 if (!res)
1896 return NULL;
1897 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1898 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1899 if (!tup) {
1900 Py_DECREF(res);
1901 return NULL;
1902 }
1903 PyList_SET_ITEM(res, i, tup);
1904 }
1905 return res;
1906}
1907
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001908/*[clinic input]
1909_ssl._SSLSocket.cipher
1910[clinic start generated code]*/
1911
1912static PyObject *
1913_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1914/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001915{
1916 const SSL_CIPHER *current;
1917
1918 if (self->ssl == NULL)
1919 Py_RETURN_NONE;
1920 current = SSL_get_current_cipher(self->ssl);
1921 if (current == NULL)
1922 Py_RETURN_NONE;
1923 return cipher_to_tuple(current);
1924}
1925
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001926/*[clinic input]
1927_ssl._SSLSocket.version
1928[clinic start generated code]*/
1929
1930static PyObject *
1931_ssl__SSLSocket_version_impl(PySSLSocket *self)
1932/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001933{
1934 const char *version;
1935
1936 if (self->ssl == NULL)
1937 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001938 if (!SSL_is_init_finished(self->ssl)) {
1939 /* handshake not finished */
1940 Py_RETURN_NONE;
1941 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001942 version = SSL_get_version(self->ssl);
1943 if (!strcmp(version, "unknown"))
1944 Py_RETURN_NONE;
1945 return PyUnicode_FromString(version);
1946}
1947
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001948/*[clinic input]
1949_ssl._SSLSocket.selected_alpn_protocol
1950[clinic start generated code]*/
1951
1952static PyObject *
1953_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1954/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1955{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001956 const unsigned char *out;
1957 unsigned int outlen;
1958
1959 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1960
1961 if (out == NULL)
1962 Py_RETURN_NONE;
1963 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001964}
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001965
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
Christian Heimes7f1305e2021-04-17 20:06:38 +02002000 if (PyObject_TypeCheck(value, self->ctx->state->PySSLContext_Type)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002001 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002002 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002003 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Christian Heimes77cde502021-03-21 16:13:09 +01002004 /* Set SSL* internal msg_callback to state of new context's state */
2005 SSL_set_msg_callback(
2006 self->ssl,
2007 self->ctx->msg_cb ? _PySSL_msg_callback : NULL
2008 );
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002009 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002010 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002011 return -1;
2012 }
2013
2014 return 0;
2015}
2016
2017PyDoc_STRVAR(PySSL_set_context_doc,
2018"_setter_context(ctx)\n\
2019\
2020This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002021used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002022on the SSLContext to change the certificate information associated with the\n\
2023SSLSocket before the cryptographic exchange handshake messages\n");
2024
2025
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002026static PyObject *
2027PySSL_get_server_side(PySSLSocket *self, void *c)
2028{
2029 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2030}
2031
2032PyDoc_STRVAR(PySSL_get_server_side_doc,
2033"Whether this is a server-side socket.");
2034
2035static PyObject *
2036PySSL_get_server_hostname(PySSLSocket *self, void *c)
2037{
2038 if (self->server_hostname == NULL)
2039 Py_RETURN_NONE;
2040 Py_INCREF(self->server_hostname);
2041 return self->server_hostname;
2042}
2043
2044PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2045"The currently set server hostname (for SNI).");
2046
2047static PyObject *
2048PySSL_get_owner(PySSLSocket *self, void *c)
2049{
2050 PyObject *owner;
2051
2052 if (self->owner == NULL)
2053 Py_RETURN_NONE;
2054
2055 owner = PyWeakref_GetObject(self->owner);
2056 Py_INCREF(owner);
2057 return owner;
2058}
2059
2060static int
2061PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2062{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002063 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002064 if (self->owner == NULL)
2065 return -1;
2066 return 0;
2067}
2068
2069PyDoc_STRVAR(PySSL_get_owner_doc,
2070"The Python-level owner of this object.\
2071Passed as \"self\" in servername callback.");
2072
Christian Heimesc7f70692019-05-31 11:44:05 +02002073static int
2074PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2075{
2076 Py_VISIT(self->exc_type);
2077 Py_VISIT(self->exc_value);
2078 Py_VISIT(self->exc_tb);
2079 return 0;
2080}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002081
Christian Heimesc7f70692019-05-31 11:44:05 +02002082static int
2083PySSL_clear(PySSLSocket *self)
2084{
2085 Py_CLEAR(self->exc_type);
2086 Py_CLEAR(self->exc_value);
2087 Py_CLEAR(self->exc_tb);
2088 return 0;
2089}
2090
2091static void
2092PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002093{
Christian Heimes5c36da72020-11-20 09:40:12 +01002094 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002095 if (self->ssl)
2096 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002097 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002098 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002099 Py_XDECREF(self->server_hostname);
2100 Py_XDECREF(self->owner);
Victor Stinner32bd68c2020-12-01 10:37:39 +01002101 PyObject_Free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01002102 Py_DECREF(tp);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002103}
2104
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002105/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002106 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002107 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002108 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002109
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002110static int
Victor Stinner14690702015-04-06 22:46:13 +02002111PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002112{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002113 int rc;
2114#ifdef HAVE_POLL
2115 struct pollfd pollfd;
2116 _PyTime_t ms;
2117#else
2118 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002119 fd_set fds;
2120 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002121#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002122
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002123 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002124 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002125 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002126 else if (timeout < 0) {
2127 if (s->sock_timeout > 0)
2128 return SOCKET_HAS_TIMED_OUT;
2129 else
2130 return SOCKET_IS_BLOCKING;
2131 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002132
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002133 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002134 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002135 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002137 /* Prefer poll, if available, since you can poll() any fd
2138 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002139#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002140 pollfd.fd = s->sock_fd;
2141 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002142
Victor Stinner14690702015-04-06 22:46:13 +02002143 /* timeout is in seconds, poll() uses milliseconds */
2144 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002145 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002146
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002147 PySSL_BEGIN_ALLOW_THREADS
2148 rc = poll(&pollfd, 1, (int)ms);
2149 PySSL_END_ALLOW_THREADS
2150#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002151 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002152 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002153 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002154
Victor Stinner14690702015-04-06 22:46:13 +02002155 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002156
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002157 FD_ZERO(&fds);
2158 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002159
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002160 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002161 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002162 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002163 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002164 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002165 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002166 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002167 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002168#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002169
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002170 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2171 (when we are able to write or when there's something to read) */
2172 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002173}
2174
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002175/*[clinic input]
2176_ssl._SSLSocket.write
2177 b: Py_buffer
2178 /
2179
2180Writes the bytes-like object b into the SSL object.
2181
2182Returns the number of bytes written.
2183[clinic start generated code]*/
2184
2185static PyObject *
2186_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2187/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002188{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002189 int len;
2190 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002191 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002192 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002193 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002194 _PyTime_t timeout, deadline = 0;
2195 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002196
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002197 if (sock != NULL) {
2198 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002199 _setSSLError(get_state_sock(self),
2200 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002201 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2202 return NULL;
2203 }
2204 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002205 }
2206
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002207 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002208 PyErr_Format(PyExc_OverflowError,
2209 "string longer than %d bytes", INT_MAX);
2210 goto error;
2211 }
2212
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002213 if (sock != NULL) {
2214 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002215 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002216 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2217 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2218 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002219
Victor Stinner14690702015-04-06 22:46:13 +02002220 timeout = GET_SOCKET_TIMEOUT(sock);
2221 has_timeout = (timeout > 0);
2222 if (has_timeout)
2223 deadline = _PyTime_GetMonotonicClock() + timeout;
2224
2225 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002226 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002227 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002228 "The write operation timed out");
2229 goto error;
2230 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002231 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002232 "Underlying socket has been closed.");
2233 goto error;
2234 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002235 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002236 "Underlying socket too large for select().");
2237 goto error;
2238 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002239
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002240 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002241 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002242 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002243 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002244 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002245 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002246
2247 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002248 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002249
Victor Stinner14690702015-04-06 22:46:13 +02002250 if (has_timeout)
2251 timeout = deadline - _PyTime_GetMonotonicClock();
2252
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002253 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002254 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002255 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002256 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002257 } else {
2258 sockstate = SOCKET_OPERATION_OK;
2259 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002260
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002261 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002262 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002263 "The write operation timed out");
2264 goto error;
2265 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002266 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002267 "Underlying socket has been closed.");
2268 goto error;
2269 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2270 break;
2271 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002272 } while (err.ssl == SSL_ERROR_WANT_READ ||
2273 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002274
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002275 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002276 if (len <= 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002277 return PySSL_SetError(self, len, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002278 if (PySSL_ChainExceptions(self) < 0)
2279 return NULL;
2280 return PyLong_FromLong(len);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002281error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002282 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002283 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002284 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002285}
2286
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002287/*[clinic input]
2288_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002289
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002290Returns the number of already decrypted bytes available for read, pending on the connection.
2291[clinic start generated code]*/
2292
2293static PyObject *
2294_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2295/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002296{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002297 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002298 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002299
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002300 PySSL_BEGIN_ALLOW_THREADS
2301 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002302 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002303 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002304 self->err = err;
2305
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002306 if (count < 0)
2307 return PySSL_SetError(self, count, __FILE__, __LINE__);
2308 else
2309 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002310}
2311
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002312/*[clinic input]
2313_ssl._SSLSocket.read
2314 size as len: int
2315 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002316 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002317 ]
2318 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002319
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002320Read up to size bytes from the SSL socket.
2321[clinic start generated code]*/
2322
2323static PyObject *
2324_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2325 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002326/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002327{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002328 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002329 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002330 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002331 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002332 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002333 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002334 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002335 _PyTime_t timeout, deadline = 0;
2336 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002337
Martin Panter5503d472016-03-27 05:35:19 +00002338 if (!group_right_1 && len < 0) {
2339 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2340 return NULL;
2341 }
2342
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002343 if (sock != NULL) {
2344 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002345 _setSSLError(get_state_sock(self),
2346 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002347 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2348 return NULL;
2349 }
2350 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002351 }
2352
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002353 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002354 dest = PyBytes_FromStringAndSize(NULL, len);
2355 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002356 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002357 if (len == 0) {
2358 Py_XDECREF(sock);
2359 return dest;
2360 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002361 mem = PyBytes_AS_STRING(dest);
2362 }
2363 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002364 mem = buffer->buf;
2365 if (len <= 0 || len > buffer->len) {
2366 len = (int) buffer->len;
2367 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002368 PyErr_SetString(PyExc_OverflowError,
2369 "maximum length can't fit in a C 'int'");
2370 goto error;
2371 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002372 if (len == 0) {
2373 count = 0;
2374 goto done;
2375 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002376 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002377 }
2378
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002379 if (sock != NULL) {
2380 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002381 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002382 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2383 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2384 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002385
Victor Stinner14690702015-04-06 22:46:13 +02002386 timeout = GET_SOCKET_TIMEOUT(sock);
2387 has_timeout = (timeout > 0);
2388 if (has_timeout)
2389 deadline = _PyTime_GetMonotonicClock() + timeout;
2390
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002391 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002392 PySSL_BEGIN_ALLOW_THREADS
2393 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002394 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002395 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002396 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002397
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002398 if (PyErr_CheckSignals())
2399 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002400
Victor Stinner14690702015-04-06 22:46:13 +02002401 if (has_timeout)
2402 timeout = deadline - _PyTime_GetMonotonicClock();
2403
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002404 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002405 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002406 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002407 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002408 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002409 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002410 {
2411 count = 0;
2412 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002413 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002414 else
2415 sockstate = SOCKET_OPERATION_OK;
2416
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002417 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002418 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002419 "The read operation timed out");
2420 goto error;
2421 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2422 break;
2423 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002424 } while (err.ssl == SSL_ERROR_WANT_READ ||
2425 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002426
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002427 if (count <= 0) {
2428 PySSL_SetError(self, count, __FILE__, __LINE__);
2429 goto error;
2430 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002431 if (self->exc_type != NULL)
2432 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002433
2434done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002435 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002436 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002437 _PyBytes_Resize(&dest, count);
2438 return dest;
2439 }
2440 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002441 return PyLong_FromLong(count);
2442 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002443
2444error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002445 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002446 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002447 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002448 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002449 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002450}
2451
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002452/*[clinic input]
2453_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002454
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002455Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002456[clinic start generated code]*/
2457
2458static PyObject *
2459_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002460/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002461{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002462 _PySSLError err;
2463 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002464 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002465 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002466 _PyTime_t timeout, deadline = 0;
2467 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002468
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002469 if (sock != NULL) {
2470 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002471 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002472 _setSSLError(get_state_sock(self),
2473 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002474 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2475 return NULL;
2476 }
2477 Py_INCREF(sock);
2478
2479 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002480 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002481 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2482 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002483 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002484
Victor Stinner14690702015-04-06 22:46:13 +02002485 timeout = GET_SOCKET_TIMEOUT(sock);
2486 has_timeout = (timeout > 0);
2487 if (has_timeout)
2488 deadline = _PyTime_GetMonotonicClock() + timeout;
2489
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002490 while (1) {
2491 PySSL_BEGIN_ALLOW_THREADS
2492 /* Disable read-ahead so that unwrap can work correctly.
2493 * Otherwise OpenSSL might read in too much data,
2494 * eating clear text data that happens to be
2495 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002496 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002497 * function is used and the shutdown_seen_zero != 0
2498 * condition is met.
2499 */
2500 if (self->shutdown_seen_zero)
2501 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002502 ret = SSL_shutdown(self->ssl);
2503 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002504 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002505 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002506
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002507 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002508 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002509 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002510 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002511 /* Don't loop endlessly; instead preserve legacy
2512 behaviour of trying SSL_shutdown() only twice.
2513 This looks necessary for OpenSSL < 0.9.8m */
2514 if (++zeros > 1)
2515 break;
2516 /* Shutdown was sent, now try receiving */
2517 self->shutdown_seen_zero = 1;
2518 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002519 }
2520
Victor Stinner14690702015-04-06 22:46:13 +02002521 if (has_timeout)
2522 timeout = deadline - _PyTime_GetMonotonicClock();
2523
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002524 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002525 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002526 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002527 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002528 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002529 else
2530 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002531
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002532 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002533 if (err.ssl == SSL_ERROR_WANT_READ)
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002534 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002535 "The read operation timed out");
2536 else
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002537 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002538 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002539 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002540 }
2541 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002542 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002543 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002544 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002545 }
2546 else if (sockstate != SOCKET_OPERATION_OK)
2547 /* Retain the SSL error code */
2548 break;
2549 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002550 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002551 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002552 PySSL_SetError(self, ret, __FILE__, __LINE__);
2553 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002554 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002555 if (self->exc_type != NULL)
2556 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002557 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002558 /* It's already INCREF'ed */
2559 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002560 else
2561 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002562
2563error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002564 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002565 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002566 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002567}
2568
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002569/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002570_ssl._SSLSocket.get_channel_binding
2571 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002572
Christian Heimes141c5e82018-02-24 21:10:57 +01002573Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002574
Christian Heimes141c5e82018-02-24 21:10:57 +01002575Raise ValueError if the requested `cb_type` is not supported. Return bytes
2576of the data or None if the data is not available (e.g. before the handshake).
2577Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002578[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002579
Antoine Pitroud6494802011-07-21 01:11:30 +02002580static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002581_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2582 const char *cb_type)
2583/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002584{
Antoine Pitroud6494802011-07-21 01:11:30 +02002585 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002586 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002587
Christian Heimes141c5e82018-02-24 21:10:57 +01002588 if (strcmp(cb_type, "tls-unique") == 0) {
2589 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2590 /* if session is resumed XOR we are the client */
2591 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2592 }
2593 else {
2594 /* if a new session XOR we are the server */
2595 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2596 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002597 }
2598 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002599 PyErr_Format(
2600 PyExc_ValueError,
2601 "'%s' channel binding type not implemented",
2602 cb_type
2603 );
2604 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002605 }
2606
2607 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002608 if (len == 0)
2609 Py_RETURN_NONE;
2610
Christian Heimes141c5e82018-02-24 21:10:57 +01002611 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002612}
2613
Christian Heimes9fb051f2018-09-23 08:32:31 +02002614/*[clinic input]
2615_ssl._SSLSocket.verify_client_post_handshake
2616
2617Initiate TLS 1.3 post-handshake authentication
2618[clinic start generated code]*/
2619
2620static PyObject *
2621_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2622/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2623{
2624#ifdef TLS1_3_VERSION
2625 int err = SSL_verify_client_post_handshake(self->ssl);
2626 if (err == 0)
Christian Heimes7f1305e2021-04-17 20:06:38 +02002627 return _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes9fb051f2018-09-23 08:32:31 +02002628 else
2629 Py_RETURN_NONE;
2630#else
2631 PyErr_SetString(PyExc_NotImplementedError,
2632 "Post-handshake auth is not supported by your "
2633 "OpenSSL version.");
2634 return NULL;
2635#endif
2636}
2637
Christian Heimes99a65702016-09-10 23:44:53 +02002638static SSL_SESSION*
2639_ssl_session_dup(SSL_SESSION *session) {
2640 SSL_SESSION *newsession = NULL;
2641 int slen;
2642 unsigned char *senc = NULL, *p;
2643 const unsigned char *const_p;
2644
2645 if (session == NULL) {
2646 PyErr_SetString(PyExc_ValueError, "Invalid session");
2647 goto error;
2648 }
2649
2650 /* get length */
2651 slen = i2d_SSL_SESSION(session, NULL);
2652 if (slen == 0 || slen > 0xFF00) {
2653 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2654 goto error;
2655 }
2656 if ((senc = PyMem_Malloc(slen)) == NULL) {
2657 PyErr_NoMemory();
2658 goto error;
2659 }
2660 p = senc;
2661 if (!i2d_SSL_SESSION(session, &p)) {
2662 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2663 goto error;
2664 }
2665 const_p = senc;
2666 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2667 if (session == NULL) {
2668 goto error;
2669 }
2670 PyMem_Free(senc);
2671 return newsession;
2672 error:
2673 if (senc != NULL) {
2674 PyMem_Free(senc);
2675 }
2676 return NULL;
2677}
Christian Heimes99a65702016-09-10 23:44:53 +02002678
2679static PyObject *
2680PySSL_get_session(PySSLSocket *self, void *closure) {
2681 /* get_session can return sessions from a server-side connection,
2682 * it does not check for handshake done or client socket. */
2683 PySSLSession *pysess;
2684 SSL_SESSION *session;
2685
Christian Heimes99a65702016-09-10 23:44:53 +02002686 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2687 * https://github.com/openssl/openssl/issues/1550 */
2688 session = SSL_get0_session(self->ssl); /* borrowed reference */
2689 if (session == NULL) {
2690 Py_RETURN_NONE;
2691 }
2692 if ((session = _ssl_session_dup(session)) == NULL) {
2693 return NULL;
2694 }
Christian Heimes99a65702016-09-10 23:44:53 +02002695 session = SSL_get1_session(self->ssl);
2696 if (session == NULL) {
2697 Py_RETURN_NONE;
2698 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02002699 pysess = PyObject_GC_New(PySSLSession, self->ctx->state->PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002700 if (pysess == NULL) {
2701 SSL_SESSION_free(session);
2702 return NULL;
2703 }
2704
2705 assert(self->ctx);
2706 pysess->ctx = self->ctx;
2707 Py_INCREF(pysess->ctx);
2708 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002709 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002710 return (PyObject *)pysess;
2711}
2712
2713static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2714 void *closure)
2715 {
2716 PySSLSession *pysess;
Christian Heimes99a65702016-09-10 23:44:53 +02002717 SSL_SESSION *session;
Christian Heimes99a65702016-09-10 23:44:53 +02002718 int result;
2719
Christian Heimes7f1305e2021-04-17 20:06:38 +02002720 if (!Py_IS_TYPE(value, get_state_sock(self)->PySSLSession_Type)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002721 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002722 return -1;
2723 }
2724 pysess = (PySSLSession *)value;
2725
2726 if (self->ctx->ctx != pysess->ctx->ctx) {
2727 PyErr_SetString(PyExc_ValueError,
2728 "Session refers to a different SSLContext.");
2729 return -1;
2730 }
2731 if (self->socket_type != PY_SSL_CLIENT) {
2732 PyErr_SetString(PyExc_ValueError,
2733 "Cannot set session for server-side SSLSocket.");
2734 return -1;
2735 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002736 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002737 PyErr_SetString(PyExc_ValueError,
2738 "Cannot set session after handshake.");
2739 return -1;
2740 }
Christian Heimes99a65702016-09-10 23:44:53 +02002741 /* duplicate session */
2742 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2743 return -1;
2744 }
2745 result = SSL_set_session(self->ssl, session);
2746 /* free duplicate, SSL_set_session() bumps ref count */
2747 SSL_SESSION_free(session);
Christian Heimes99a65702016-09-10 23:44:53 +02002748 if (result == 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002749 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes99a65702016-09-10 23:44:53 +02002750 return -1;
2751 }
2752 return 0;
2753}
2754
2755PyDoc_STRVAR(PySSL_set_session_doc,
2756"_setter_session(session)\n\
2757\
2758Get / set SSLSession.");
2759
2760static PyObject *
2761PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2762 if (SSL_session_reused(self->ssl)) {
2763 Py_RETURN_TRUE;
2764 } else {
2765 Py_RETURN_FALSE;
2766 }
2767}
2768
2769PyDoc_STRVAR(PySSL_get_session_reused_doc,
2770"Was the client session reused during handshake?");
2771
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002772static PyGetSetDef ssl_getsetlist[] = {
2773 {"context", (getter) PySSL_get_context,
2774 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002775 {"server_side", (getter) PySSL_get_server_side, NULL,
2776 PySSL_get_server_side_doc},
2777 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2778 PySSL_get_server_hostname_doc},
2779 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2780 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002781 {"session", (getter) PySSL_get_session,
2782 (setter) PySSL_set_session, PySSL_set_session_doc},
2783 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2784 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002785 {NULL}, /* sentinel */
2786};
2787
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002788static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002789 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2790 _SSL__SSLSOCKET_WRITE_METHODDEF
2791 _SSL__SSLSOCKET_READ_METHODDEF
2792 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002793 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2794 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002795 _SSL__SSLSOCKET_CIPHER_METHODDEF
2796 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2797 _SSL__SSLSOCKET_VERSION_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002798 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2799 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2800 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002801 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002802 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002803};
2804
Christian Heimes5c36da72020-11-20 09:40:12 +01002805static PyType_Slot PySSLSocket_slots[] = {
2806 {Py_tp_methods, PySSLMethods},
2807 {Py_tp_getset, ssl_getsetlist},
2808 {Py_tp_dealloc, PySSL_dealloc},
2809 {Py_tp_traverse, PySSL_traverse},
2810 {Py_tp_clear, PySSL_clear},
2811 {0, 0},
2812};
2813
2814static PyType_Spec PySSLSocket_spec = {
2815 "_ssl._SSLSocket",
2816 sizeof(PySSLSocket),
2817 0,
2818 Py_TPFLAGS_DEFAULT,
2819 PySSLSocket_slots,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002820};
2821
Antoine Pitrou152efa22010-05-16 18:19:27 +00002822/*
2823 * _SSLContext objects
2824 */
2825
Christian Heimes5fe668c2016-09-12 00:01:11 +02002826static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02002827_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002828{
2829 int mode;
2830 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2831
2832 switch(n) {
2833 case PY_SSL_CERT_NONE:
2834 mode = SSL_VERIFY_NONE;
2835 break;
2836 case PY_SSL_CERT_OPTIONAL:
2837 mode = SSL_VERIFY_PEER;
2838 break;
2839 case PY_SSL_CERT_REQUIRED:
2840 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2841 break;
2842 default:
2843 PyErr_SetString(PyExc_ValueError,
2844 "invalid value for verify_mode");
2845 return -1;
2846 }
Christian Heimesf0f59302019-07-01 08:29:17 +02002847
2848 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
2849 * server sockets and SSL_set_post_handshake_auth() for client. */
2850
Christian Heimes5fe668c2016-09-12 00:01:11 +02002851 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02002852 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2853 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002854 return 0;
2855}
2856
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002857/*[clinic input]
2858@classmethod
2859_ssl._SSLContext.__new__
2860 protocol as proto_version: int
2861 /
2862[clinic start generated code]*/
2863
Antoine Pitrou152efa22010-05-16 18:19:27 +00002864static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002865_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2866/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002867{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002868 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002869 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002870 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002871 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002872 int result;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002873
Christian Heimes7f1305e2021-04-17 20:06:38 +02002874 /* slower approach, walk MRO and get borrowed reference to module.
2875 * _PyType_GetModuleByDef is required for SSLContext subclasses */
2876 PyObject *module = _PyType_GetModuleByDef(type, &_sslmodule_def);
2877 if (module == NULL) {
2878 PyErr_SetString(PyExc_RuntimeError,
2879 "Cannot find internal module state");
2880 return NULL;
2881 }
2882
Antoine Pitrou152efa22010-05-16 18:19:27 +00002883 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes6e8cda92020-05-16 03:33:05 +02002884 switch(proto_version) {
2885#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
2886 case PY_SSL_VERSION_SSL3:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002887 ctx = SSL_CTX_new(SSLv3_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02002888 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05002889#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002890#if (defined(TLS1_VERSION) && \
2891 !defined(OPENSSL_NO_TLS1) && \
2892 !defined(OPENSSL_NO_TLS1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002893 case PY_SSL_VERSION_TLS1:
2894 ctx = SSL_CTX_new(TLSv1_method());
2895 break;
Victor Stinner3de49192011-05-09 00:42:58 +02002896#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002897#if (defined(TLS1_1_VERSION) && \
2898 !defined(OPENSSL_NO_TLS1_1) && \
2899 !defined(OPENSSL_NO_TLS1_1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002900 case PY_SSL_VERSION_TLS1_1:
2901 ctx = SSL_CTX_new(TLSv1_1_method());
2902 break;
2903#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002904#if (defined(TLS1_2_VERSION) && \
2905 !defined(OPENSSL_NO_TLS1_2) && \
2906 !defined(OPENSSL_NO_TLS1_2_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002907 case PY_SSL_VERSION_TLS1_2:
2908 ctx = SSL_CTX_new(TLSv1_2_method());
2909 break;
2910#endif
2911 case PY_SSL_VERSION_TLS:
2912 /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002913 ctx = SSL_CTX_new(TLS_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02002914 break;
2915 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes5fe668c2016-09-12 00:01:11 +02002916 ctx = SSL_CTX_new(TLS_client_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02002917 break;
2918 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes5fe668c2016-09-12 00:01:11 +02002919 ctx = SSL_CTX_new(TLS_server_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02002920 break;
2921 default:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002922 proto_version = -1;
Christian Heimes6e8cda92020-05-16 03:33:05 +02002923 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002924 PySSL_END_ALLOW_THREADS
2925
2926 if (proto_version == -1) {
2927 PyErr_SetString(PyExc_ValueError,
Christian Heimes6e8cda92020-05-16 03:33:05 +02002928 "invalid or unsupported protocol version");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002929 return NULL;
2930 }
2931 if (ctx == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002932 _setSSLError(get_ssl_state(module), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002933 return NULL;
2934 }
2935
2936 assert(type != NULL && type->tp_alloc != NULL);
2937 self = (PySSLContext *) type->tp_alloc(type, 0);
2938 if (self == NULL) {
2939 SSL_CTX_free(ctx);
2940 return NULL;
2941 }
2942 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002943 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01002944 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02002945 self->msg_cb = NULL;
Christian Heimesc7f70692019-05-31 11:44:05 +02002946 self->keylog_filename = NULL;
2947 self->keylog_bio = NULL;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002948 self->alpn_protocols = NULL;
Christian Heimes11a14932018-02-24 02:35:08 +01002949 self->set_sni_cb = NULL;
Christian Heimes7f1305e2021-04-17 20:06:38 +02002950 self->state = get_ssl_state(module);
2951
Christian Heimes1aa9a752013-12-02 02:41:19 +01002952 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002953 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2954 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02002955 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02002956 Py_DECREF(self);
2957 return NULL;
2958 }
2959 } else {
2960 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02002961 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02002962 Py_DECREF(self);
2963 return NULL;
2964 }
2965 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002966 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002967 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2968 if (proto_version != PY_SSL_VERSION_SSL2)
2969 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002970 if (proto_version != PY_SSL_VERSION_SSL3)
2971 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002972 /* Minimal security flags for server and client side context.
2973 * Client sockets ignore server-side parameters. */
2974#ifdef SSL_OP_NO_COMPRESSION
2975 options |= SSL_OP_NO_COMPRESSION;
2976#endif
2977#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2978 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2979#endif
2980#ifdef SSL_OP_SINGLE_DH_USE
2981 options |= SSL_OP_SINGLE_DH_USE;
2982#endif
2983#ifdef SSL_OP_SINGLE_ECDH_USE
2984 options |= SSL_OP_SINGLE_ECDH_USE;
2985#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02002986#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
2987 /* Make OpenSSL 3.0.0 behave like 1.1.1 */
2988 options |= SSL_OP_IGNORE_UNEXPECTED_EOF;
2989#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002990 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002991
Semen Zhydenko1295e112017-10-15 21:28:31 +02002992 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02002993 * It's far from perfect but gives users a better head start. */
2994 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01002995#if PY_SSL_DEFAULT_CIPHERS == 2
2996 /* stick to OpenSSL's default settings */
2997 result = 1;
2998#else
2999 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3000#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003001 } else {
3002 /* SSLv2 needs MD5 */
3003 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3004 }
3005 if (result == 0) {
3006 Py_DECREF(self);
3007 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003008 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Christian Heimes358cfd42016-09-10 22:43:48 +02003009 "No cipher can be selected.");
3010 return NULL;
3011 }
3012
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003013 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
Christian Heimes39258d32021-04-17 11:36:35 +02003014 usage for no cost at all. */
3015 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003016
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003017#define SID_CTX "Python"
3018 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3019 sizeof(SID_CTX));
3020#undef SID_CTX
3021
Christian Heimes61d478c2018-01-27 15:51:38 +01003022 params = SSL_CTX_get0_param(self->ctx);
Christian Heimes61d478c2018-01-27 15:51:38 +01003023 /* Improve trust chain building when cross-signed intermediate
3024 certificates are present. See https://bugs.python.org/issue23476. */
3025 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Christian Heimes61d478c2018-01-27 15:51:38 +01003026 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003027
Christian Heimes9fb051f2018-09-23 08:32:31 +02003028#ifdef TLS1_3_VERSION
3029 self->post_handshake_auth = 0;
3030 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3031#endif
3032
Antoine Pitrou152efa22010-05-16 18:19:27 +00003033 return (PyObject *)self;
3034}
3035
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003036static int
3037context_traverse(PySSLContext *self, visitproc visit, void *arg)
3038{
Christian Heimes11a14932018-02-24 02:35:08 +01003039 Py_VISIT(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003040 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003041 return 0;
3042}
3043
3044static int
3045context_clear(PySSLContext *self)
3046{
Christian Heimes11a14932018-02-24 02:35:08 +01003047 Py_CLEAR(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003048 Py_CLEAR(self->msg_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003049 Py_CLEAR(self->keylog_filename);
3050 if (self->keylog_bio != NULL) {
3051 PySSL_BEGIN_ALLOW_THREADS
3052 BIO_free_all(self->keylog_bio);
3053 PySSL_END_ALLOW_THREADS
3054 self->keylog_bio = NULL;
3055 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003056 return 0;
3057}
3058
Antoine Pitrou152efa22010-05-16 18:19:27 +00003059static void
3060context_dealloc(PySSLContext *self)
3061{
Christian Heimes5c36da72020-11-20 09:40:12 +01003062 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09003063 /* bpo-31095: UnTrack is needed before calling any callbacks */
3064 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003065 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003066 SSL_CTX_free(self->ctx);
Christian Heimes39258d32021-04-17 11:36:35 +02003067 PyMem_FREE(self->alpn_protocols);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003068 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01003069 Py_DECREF(tp);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003070}
3071
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003072/*[clinic input]
3073_ssl._SSLContext.set_ciphers
3074 cipherlist: str
3075 /
3076[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003077
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003078static PyObject *
3079_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3080/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3081{
3082 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003083 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003084 /* Clearing the error queue is necessary on some OpenSSL versions,
3085 otherwise the error will be reported again when another SSL call
3086 is done. */
3087 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003088 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003089 "No cipher can be selected.");
3090 return NULL;
3091 }
3092 Py_RETURN_NONE;
3093}
3094
Christian Heimes25bfcd52016-09-06 00:04:45 +02003095/*[clinic input]
3096_ssl._SSLContext.get_ciphers
3097[clinic start generated code]*/
3098
3099static PyObject *
3100_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3101/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3102{
3103 SSL *ssl = NULL;
3104 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003105 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003106 int i=0;
3107 PyObject *result = NULL, *dct;
3108
3109 ssl = SSL_new(self->ctx);
3110 if (ssl == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003111 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes25bfcd52016-09-06 00:04:45 +02003112 goto exit;
3113 }
3114 sk = SSL_get_ciphers(ssl);
3115
3116 result = PyList_New(sk_SSL_CIPHER_num(sk));
3117 if (result == NULL) {
3118 goto exit;
3119 }
3120
3121 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3122 cipher = sk_SSL_CIPHER_value(sk, i);
3123 dct = cipher_to_dict(cipher);
3124 if (dct == NULL) {
3125 Py_CLEAR(result);
3126 goto exit;
3127 }
3128 PyList_SET_ITEM(result, i, dct);
3129 }
3130
3131 exit:
3132 if (ssl != NULL)
3133 SSL_free(ssl);
3134 return result;
3135
3136}
Christian Heimes25bfcd52016-09-06 00:04:45 +02003137
3138
Benjamin Petersoncca27322015-01-23 16:35:37 -05003139static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003140do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3141 const unsigned char *server_protocols, unsigned int server_protocols_len,
3142 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003143{
Benjamin Peterson88615022015-01-23 17:30:26 -05003144 int ret;
3145 if (client_protocols == NULL) {
3146 client_protocols = (unsigned char *)"";
3147 client_protocols_len = 0;
3148 }
3149 if (server_protocols == NULL) {
3150 server_protocols = (unsigned char *)"";
3151 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003152 }
3153
Benjamin Peterson88615022015-01-23 17:30:26 -05003154 ret = SSL_select_next_proto(out, outlen,
3155 server_protocols, server_protocols_len,
3156 client_protocols, client_protocols_len);
3157 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3158 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003159
3160 return SSL_TLSEXT_ERR_OK;
3161}
3162
Benjamin Petersoncca27322015-01-23 16:35:37 -05003163static int
3164_selectALPN_cb(SSL *s,
3165 const unsigned char **out, unsigned char *outlen,
3166 const unsigned char *client_protocols, unsigned int client_protocols_len,
3167 void *args)
3168{
3169 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003170 return do_protocol_selection(1, (unsigned char **)out, outlen,
3171 ctx->alpn_protocols, ctx->alpn_protocols_len,
3172 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003173}
Benjamin Petersoncca27322015-01-23 16:35:37 -05003174
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003175/*[clinic input]
3176_ssl._SSLContext._set_alpn_protocols
3177 protos: Py_buffer
3178 /
3179[clinic start generated code]*/
3180
Benjamin Petersoncca27322015-01-23 16:35:37 -05003181static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003182_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3183 Py_buffer *protos)
3184/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003185{
Victor Stinner5a615592017-09-14 01:10:30 -07003186 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003187 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003188 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003189 return NULL;
3190 }
3191
Victor Stinner00d7abd2020-12-01 09:56:42 +01003192 PyMem_Free(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003193 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003194 if (!self->alpn_protocols)
3195 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003196 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003197 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003198
3199 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3200 return PyErr_NoMemory();
3201 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3202
Benjamin Petersoncca27322015-01-23 16:35:37 -05003203 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003204}
3205
Antoine Pitrou152efa22010-05-16 18:19:27 +00003206static PyObject *
3207get_verify_mode(PySSLContext *self, void *c)
3208{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003209 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3210 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3211 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3212 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003213 case SSL_VERIFY_NONE:
3214 return PyLong_FromLong(PY_SSL_CERT_NONE);
3215 case SSL_VERIFY_PEER:
3216 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3217 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3218 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3219 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02003220 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003221 "invalid return value from SSL_CTX_get_verify_mode");
3222 return NULL;
3223}
3224
3225static int
3226set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3227{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003228 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003229 if (!PyArg_Parse(arg, "i", &n))
3230 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003231 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003232 PyErr_SetString(PyExc_ValueError,
3233 "Cannot set verify_mode to CERT_NONE when "
3234 "check_hostname is enabled.");
3235 return -1;
3236 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003237 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003238}
3239
3240static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003241get_verify_flags(PySSLContext *self, void *c)
3242{
Christian Heimes598894f2016-09-05 23:19:05 +02003243 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003244 unsigned long flags;
3245
Christian Heimes61d478c2018-01-27 15:51:38 +01003246 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003247 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003248 return PyLong_FromUnsignedLong(flags);
3249}
3250
3251static int
3252set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3253{
Christian Heimes598894f2016-09-05 23:19:05 +02003254 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003255 unsigned long new_flags, flags, set, clear;
3256
3257 if (!PyArg_Parse(arg, "k", &new_flags))
3258 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003259 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003260 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003261 clear = flags & ~new_flags;
3262 set = ~flags & new_flags;
3263 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003264 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003265 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003266 return -1;
3267 }
3268 }
3269 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003270 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003271 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003272 return -1;
3273 }
3274 }
3275 return 0;
3276}
3277
Christian Heimes698dde12018-02-27 11:54:43 +01003278/* Getter and setter for protocol version */
Christian Heimes698dde12018-02-27 11:54:43 +01003279static int
3280set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3281{
3282 long v;
3283 int result;
3284
3285 if (!PyArg_Parse(arg, "l", &v))
3286 return -1;
3287 if (v > INT_MAX) {
3288 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3289 return -1;
3290 }
3291
3292 switch(self->protocol) {
3293 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3294 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3295 case PY_SSL_VERSION_TLS:
3296 break;
3297 default:
3298 PyErr_SetString(
3299 PyExc_ValueError,
3300 "The context's protocol doesn't support modification of "
3301 "highest and lowest version."
3302 );
3303 return -1;
3304 }
3305
3306 if (what == 0) {
3307 switch(v) {
3308 case PY_PROTO_MINIMUM_SUPPORTED:
3309 v = 0;
3310 break;
3311 case PY_PROTO_MAXIMUM_SUPPORTED:
3312 /* Emulate max for set_min_proto_version */
3313 v = PY_PROTO_MAXIMUM_AVAILABLE;
3314 break;
3315 default:
3316 break;
3317 }
3318 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3319 }
3320 else {
3321 switch(v) {
3322 case PY_PROTO_MAXIMUM_SUPPORTED:
3323 v = 0;
3324 break;
3325 case PY_PROTO_MINIMUM_SUPPORTED:
3326 /* Emulate max for set_min_proto_version */
3327 v = PY_PROTO_MINIMUM_AVAILABLE;
3328 break;
3329 default:
3330 break;
3331 }
3332 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3333 }
3334 if (result == 0) {
3335 PyErr_Format(PyExc_ValueError,
3336 "Unsupported protocol version 0x%x", v);
3337 return -1;
3338 }
3339 return 0;
3340}
3341
3342static PyObject *
3343get_minimum_version(PySSLContext *self, void *c)
3344{
3345 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3346 if (v == 0) {
3347 v = PY_PROTO_MINIMUM_SUPPORTED;
3348 }
3349 return PyLong_FromLong(v);
3350}
3351
3352static int
3353set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3354{
3355 return set_min_max_proto_version(self, arg, 0);
3356}
3357
3358static PyObject *
3359get_maximum_version(PySSLContext *self, void *c)
3360{
3361 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3362 if (v == 0) {
3363 v = PY_PROTO_MAXIMUM_SUPPORTED;
3364 }
3365 return PyLong_FromLong(v);
3366}
3367
3368static int
3369set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3370{
3371 return set_min_max_proto_version(self, arg, 1);
3372}
Christian Heimes698dde12018-02-27 11:54:43 +01003373
Christian Heimes39258d32021-04-17 11:36:35 +02003374#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02003375static PyObject *
3376get_num_tickets(PySSLContext *self, void *c)
3377{
Victor Stinner76611c72019-07-09 13:30:52 +02003378 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003379}
3380
3381static int
3382set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3383{
3384 long num;
3385 if (!PyArg_Parse(arg, "l", &num))
3386 return -1;
3387 if (num < 0) {
3388 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3389 return -1;
3390 }
3391 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3392 PyErr_SetString(PyExc_ValueError,
3393 "SSLContext is not a server context.");
3394 return -1;
3395 }
3396 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3397 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3398 return -1;
3399 }
3400 return 0;
3401}
3402
3403PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3404"Control the number of TLSv1.3 session tickets");
Christian Heimes39258d32021-04-17 11:36:35 +02003405#endif /* TLS1_3_VERSION */
Christian Heimes78c7d522019-06-03 21:00:10 +02003406
matthewhughes9348e836bb2020-07-17 09:59:15 +01003407static PyObject *
3408get_security_level(PySSLContext *self, void *c)
3409{
3410 return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3411}
3412PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
matthewhughes9348e836bb2020-07-17 09:59:15 +01003413
Christian Heimes22587792013-11-21 23:56:13 +01003414static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003415get_options(PySSLContext *self, void *c)
3416{
3417 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3418}
3419
3420static int
3421set_options(PySSLContext *self, PyObject *arg, void *c)
3422{
3423 long new_opts, opts, set, clear;
3424 if (!PyArg_Parse(arg, "l", &new_opts))
3425 return -1;
3426 opts = SSL_CTX_get_options(self->ctx);
3427 clear = opts & ~new_opts;
3428 set = ~opts & new_opts;
3429 if (clear) {
Antoine Pitroub5218772010-05-21 09:56:06 +00003430 SSL_CTX_clear_options(self->ctx, clear);
Antoine Pitroub5218772010-05-21 09:56:06 +00003431 }
3432 if (set)
3433 SSL_CTX_set_options(self->ctx, set);
3434 return 0;
3435}
3436
Christian Heimes1aa9a752013-12-02 02:41:19 +01003437static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003438get_host_flags(PySSLContext *self, void *c)
3439{
3440 return PyLong_FromUnsignedLong(self->hostflags);
3441}
3442
3443static int
3444set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3445{
3446 X509_VERIFY_PARAM *param;
3447 unsigned int new_flags = 0;
3448
3449 if (!PyArg_Parse(arg, "I", &new_flags))
3450 return -1;
3451
3452 param = SSL_CTX_get0_param(self->ctx);
3453 self->hostflags = new_flags;
3454 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3455 return 0;
3456}
3457
3458static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003459get_check_hostname(PySSLContext *self, void *c)
3460{
3461 return PyBool_FromLong(self->check_hostname);
3462}
3463
3464static int
3465set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3466{
3467 int check_hostname;
3468 if (!PyArg_Parse(arg, "p", &check_hostname))
3469 return -1;
3470 if (check_hostname &&
3471 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003472 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003473 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003474 return -1;
3475 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003476 }
3477 self->check_hostname = check_hostname;
3478 return 0;
3479}
3480
Christian Heimes11a14932018-02-24 02:35:08 +01003481static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003482get_post_handshake_auth(PySSLContext *self, void *c) {
3483#if TLS1_3_VERSION
3484 return PyBool_FromLong(self->post_handshake_auth);
3485#else
3486 Py_RETURN_NONE;
3487#endif
3488}
3489
3490#if TLS1_3_VERSION
3491static int
3492set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003493 if (arg == NULL) {
3494 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3495 return -1;
3496 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003497 int pha = PyObject_IsTrue(arg);
3498
3499 if (pha == -1) {
3500 return -1;
3501 }
3502 self->post_handshake_auth = pha;
3503
Christian Heimesf0f59302019-07-01 08:29:17 +02003504 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3505 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003506
3507 return 0;
3508}
3509#endif
3510
3511static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003512get_protocol(PySSLContext *self, void *c) {
3513 return PyLong_FromLong(self->protocol);
3514}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003515
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003516typedef struct {
3517 PyThreadState *thread_state;
3518 PyObject *callable;
3519 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003520 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003521 int error;
3522} _PySSLPasswordInfo;
3523
3524static int
3525_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3526 const char *bad_type_error)
3527{
3528 /* Set the password and size fields of a _PySSLPasswordInfo struct
3529 from a unicode, bytes, or byte array object.
3530 The password field will be dynamically allocated and must be freed
3531 by the caller */
3532 PyObject *password_bytes = NULL;
3533 const char *data = NULL;
3534 Py_ssize_t size;
3535
3536 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003537 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003538 if (!password_bytes) {
3539 goto error;
3540 }
3541 data = PyBytes_AS_STRING(password_bytes);
3542 size = PyBytes_GET_SIZE(password_bytes);
3543 } else if (PyBytes_Check(password)) {
3544 data = PyBytes_AS_STRING(password);
3545 size = PyBytes_GET_SIZE(password);
3546 } else if (PyByteArray_Check(password)) {
3547 data = PyByteArray_AS_STRING(password);
3548 size = PyByteArray_GET_SIZE(password);
3549 } else {
3550 PyErr_SetString(PyExc_TypeError, bad_type_error);
3551 goto error;
3552 }
3553
Victor Stinner9ee02032013-06-23 15:08:23 +02003554 if (size > (Py_ssize_t)INT_MAX) {
3555 PyErr_Format(PyExc_ValueError,
3556 "password cannot be longer than %d bytes", INT_MAX);
3557 goto error;
3558 }
3559
Victor Stinner11ebff22013-07-07 17:07:52 +02003560 PyMem_Free(pw_info->password);
3561 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003562 if (!pw_info->password) {
3563 PyErr_SetString(PyExc_MemoryError,
3564 "unable to allocate password buffer");
3565 goto error;
3566 }
3567 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003568 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003569
3570 Py_XDECREF(password_bytes);
3571 return 1;
3572
3573error:
3574 Py_XDECREF(password_bytes);
3575 return 0;
3576}
3577
3578static int
3579_password_callback(char *buf, int size, int rwflag, void *userdata)
3580{
3581 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3582 PyObject *fn_ret = NULL;
3583
3584 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3585
Christian Heimesd3b73f32021-04-09 15:23:38 +02003586 if (pw_info->error) {
3587 /* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
3588 * callback multiple times which can lead to fatal Python error in
3589 * exception check. */
3590 goto error;
3591 }
3592
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003593 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003594 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003595 if (!fn_ret) {
3596 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3597 core python API, so we could use it to add a frame here */
3598 goto error;
3599 }
3600
3601 if (!_pwinfo_set(pw_info, fn_ret,
3602 "password callback must return a string")) {
3603 goto error;
3604 }
3605 Py_CLEAR(fn_ret);
3606 }
3607
3608 if (pw_info->size > size) {
3609 PyErr_Format(PyExc_ValueError,
3610 "password cannot be longer than %d bytes", size);
3611 goto error;
3612 }
3613
3614 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3615 memcpy(buf, pw_info->password, pw_info->size);
3616 return pw_info->size;
3617
3618error:
3619 Py_XDECREF(fn_ret);
3620 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3621 pw_info->error = 1;
3622 return -1;
3623}
3624
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003625/*[clinic input]
3626_ssl._SSLContext.load_cert_chain
3627 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003628 keyfile: object = None
3629 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003630
3631[clinic start generated code]*/
3632
Antoine Pitroub5218772010-05-21 09:56:06 +00003633static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003634_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3635 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003636/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003637{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003638 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003639 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3640 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003641 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003642 int r;
3643
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003644 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003645 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003646 if (keyfile == Py_None)
3647 keyfile = NULL;
3648 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003649 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3650 PyErr_SetString(PyExc_TypeError,
3651 "certfile should be a valid filesystem path");
3652 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003653 return NULL;
3654 }
3655 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003656 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3657 PyErr_SetString(PyExc_TypeError,
3658 "keyfile should be a valid filesystem path");
3659 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003660 goto error;
3661 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003662 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003663 if (PyCallable_Check(password)) {
3664 pw_info.callable = password;
3665 } else if (!_pwinfo_set(&pw_info, password,
3666 "password should be a string or callable")) {
3667 goto error;
3668 }
3669 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3670 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3671 }
3672 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003673 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3674 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003675 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003676 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003677 if (pw_info.error) {
3678 ERR_clear_error();
3679 /* the password callback has already set the error information */
3680 }
3681 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003682 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003683 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003684 }
3685 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003686 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003687 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003688 goto error;
3689 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003690 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003691 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003692 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3693 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003694 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3695 Py_CLEAR(keyfile_bytes);
3696 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003697 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003698 if (pw_info.error) {
3699 ERR_clear_error();
3700 /* the password callback has already set the error information */
3701 }
3702 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003703 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003704 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003705 }
3706 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003707 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003708 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003709 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003710 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003711 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003712 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003713 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003714 if (r != 1) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003715 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003716 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003717 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003718 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3719 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003720 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003721 Py_RETURN_NONE;
3722
3723error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003724 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3725 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003726 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003727 Py_XDECREF(keyfile_bytes);
3728 Py_XDECREF(certfile_bytes);
3729 return NULL;
3730}
3731
Christian Heimesefff7062013-11-21 03:35:02 +01003732/* internal helper function, returns -1 on error
3733 */
3734static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03003735_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01003736 int filetype)
3737{
3738 BIO *biobuf = NULL;
3739 X509_STORE *store;
3740 int retval = 0, err, loaded = 0;
3741
3742 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3743
3744 if (len <= 0) {
3745 PyErr_SetString(PyExc_ValueError,
3746 "Empty certificate data");
3747 return -1;
3748 } else if (len > INT_MAX) {
3749 PyErr_SetString(PyExc_OverflowError,
3750 "Certificate data is too long.");
3751 return -1;
3752 }
3753
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003754 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003755 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003756 _setSSLError(get_state_ctx(self), "Can't allocate buffer", 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003757 return -1;
3758 }
3759
3760 store = SSL_CTX_get_cert_store(self->ctx);
3761 assert(store != NULL);
3762
3763 while (1) {
3764 X509 *cert = NULL;
3765 int r;
3766
3767 if (filetype == SSL_FILETYPE_ASN1) {
3768 cert = d2i_X509_bio(biobuf, NULL);
3769 } else {
3770 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003771 SSL_CTX_get_default_passwd_cb(self->ctx),
3772 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3773 );
Christian Heimesefff7062013-11-21 03:35:02 +01003774 }
3775 if (cert == NULL) {
3776 break;
3777 }
3778 r = X509_STORE_add_cert(store, cert);
3779 X509_free(cert);
3780 if (!r) {
3781 err = ERR_peek_last_error();
3782 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3783 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3784 /* cert already in hash table, not an error */
3785 ERR_clear_error();
3786 } else {
3787 break;
3788 }
3789 }
3790 loaded++;
3791 }
3792
3793 err = ERR_peek_last_error();
3794 if ((filetype == SSL_FILETYPE_ASN1) &&
3795 (loaded > 0) &&
3796 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3797 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3798 /* EOF ASN1 file, not an error */
3799 ERR_clear_error();
3800 retval = 0;
3801 } else if ((filetype == SSL_FILETYPE_PEM) &&
3802 (loaded > 0) &&
3803 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3804 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3805 /* EOF PEM file, not an error */
3806 ERR_clear_error();
3807 retval = 0;
3808 } else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003809 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003810 retval = -1;
3811 }
3812
3813 BIO_free(biobuf);
3814 return retval;
3815}
3816
3817
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003818/*[clinic input]
3819_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003820 cafile: object = None
3821 capath: object = None
3822 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003823
3824[clinic start generated code]*/
3825
Antoine Pitrou152efa22010-05-16 18:19:27 +00003826static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003827_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3828 PyObject *cafile,
3829 PyObject *capath,
3830 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003831/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003832{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003833 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3834 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003835 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003836
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003837 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003838 if (cafile == Py_None)
3839 cafile = NULL;
3840 if (capath == Py_None)
3841 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003842 if (cadata == Py_None)
3843 cadata = NULL;
3844
3845 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003846 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003847 "cafile, capath and cadata cannot be all omitted");
3848 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003849 }
3850 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003851 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3852 PyErr_SetString(PyExc_TypeError,
3853 "cafile should be a valid filesystem path");
3854 }
Christian Heimesefff7062013-11-21 03:35:02 +01003855 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003856 }
3857 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003858 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3859 PyErr_SetString(PyExc_TypeError,
3860 "capath should be a valid filesystem path");
3861 }
Christian Heimesefff7062013-11-21 03:35:02 +01003862 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003863 }
Christian Heimesefff7062013-11-21 03:35:02 +01003864
3865 /* validata cadata type and load cadata */
3866 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003867 if (PyUnicode_Check(cadata)) {
3868 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
3869 if (cadata_ascii == NULL) {
3870 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
3871 goto invalid_cadata;
3872 }
3873 goto error;
3874 }
3875 r = _add_ca_certs(self,
3876 PyBytes_AS_STRING(cadata_ascii),
3877 PyBytes_GET_SIZE(cadata_ascii),
3878 SSL_FILETYPE_PEM);
3879 Py_DECREF(cadata_ascii);
3880 if (r == -1) {
3881 goto error;
3882 }
3883 }
3884 else if (PyObject_CheckBuffer(cadata)) {
3885 Py_buffer buf;
3886 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
3887 goto error;
3888 }
Christian Heimesefff7062013-11-21 03:35:02 +01003889 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3890 PyBuffer_Release(&buf);
3891 PyErr_SetString(PyExc_TypeError,
3892 "cadata should be a contiguous buffer with "
3893 "a single dimension");
3894 goto error;
3895 }
3896 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3897 PyBuffer_Release(&buf);
3898 if (r == -1) {
3899 goto error;
3900 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003901 }
3902 else {
3903 invalid_cadata:
3904 PyErr_SetString(PyExc_TypeError,
3905 "cadata should be an ASCII string or a "
3906 "bytes-like object");
3907 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01003908 }
3909 }
3910
3911 /* load cafile or capath */
3912 if (cafile || capath) {
3913 if (cafile)
3914 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3915 if (capath)
3916 capath_buf = PyBytes_AS_STRING(capath_bytes);
3917 PySSL_BEGIN_ALLOW_THREADS
3918 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3919 PySSL_END_ALLOW_THREADS
3920 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01003921 if (errno != 0) {
3922 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003923 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003924 }
3925 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003926 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003927 }
3928 goto error;
3929 }
3930 }
3931 goto end;
3932
3933 error:
3934 ok = 0;
3935 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003936 Py_XDECREF(cafile_bytes);
3937 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003938 if (ok) {
3939 Py_RETURN_NONE;
3940 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003941 return NULL;
3942 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003943}
3944
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003945/*[clinic input]
3946_ssl._SSLContext.load_dh_params
3947 path as filepath: object
3948 /
3949
3950[clinic start generated code]*/
3951
Antoine Pitrou152efa22010-05-16 18:19:27 +00003952static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003953_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3954/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003955{
3956 FILE *f;
3957 DH *dh;
3958
Victor Stinnerdaf45552013-08-28 00:53:59 +02003959 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003960 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003961 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003962
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003963 errno = 0;
3964 PySSL_BEGIN_ALLOW_THREADS
3965 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003966 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003967 PySSL_END_ALLOW_THREADS
3968 if (dh == NULL) {
3969 if (errno != 0) {
3970 ERR_clear_error();
3971 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3972 }
3973 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003974 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003975 }
3976 return NULL;
3977 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06003978 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
3979 DH_free(dh);
Christian Heimes7f1305e2021-04-17 20:06:38 +02003980 return _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzaebc0492020-07-07 22:21:58 -06003981 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003982 DH_free(dh);
3983 Py_RETURN_NONE;
3984}
3985
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003986/*[clinic input]
3987_ssl._SSLContext._wrap_socket
Christian Heimes7f1305e2021-04-17 20:06:38 +02003988 sock: object(subclass_of="get_state_ctx(self)->Sock_Type")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003989 server_side: int
3990 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01003991 *
3992 owner: object = None
3993 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003994
3995[clinic start generated code]*/
3996
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003997static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003998_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01003999 int server_side, PyObject *hostname_obj,
4000 PyObject *owner, PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004001/*[clinic end generated code: output=f103f238633940b4 input=f5916eadbc6eae81]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004002{
Antoine Pitroud5323212010-10-22 18:19:07 +00004003 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004004 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004005
Antoine Pitroud5323212010-10-22 18:19:07 +00004006 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004007 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004008 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004009 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004010 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004011 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004012
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004013 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4014 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004015 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004016 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004017 if (hostname != NULL)
4018 PyMem_Free(hostname);
4019 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004020}
4021
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004022/*[clinic input]
4023_ssl._SSLContext._wrap_bio
Christian Heimes7f1305e2021-04-17 20:06:38 +02004024 incoming: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4025 outgoing: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004026 server_side: int
4027 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004028 *
4029 owner: object = None
4030 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004031
4032[clinic start generated code]*/
4033
Antoine Pitroub0182c82010-10-12 20:09:02 +00004034static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004035_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4036 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004037 PyObject *hostname_obj, PyObject *owner,
4038 PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004039/*[clinic end generated code: output=5c5d6d9b41f99332 input=331edeec9c738382]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004040{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004041 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004042 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004043
4044 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004045 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004046 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004047 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004048 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004049 }
4050
4051 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004052 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004053 incoming, outgoing);
4054
4055 PyMem_Free(hostname);
4056 return res;
4057}
4058
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004059/*[clinic input]
4060_ssl._SSLContext.session_stats
4061[clinic start generated code]*/
4062
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004063static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004064_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4065/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004066{
4067 int r;
4068 PyObject *value, *stats = PyDict_New();
4069 if (!stats)
4070 return NULL;
4071
4072#define ADD_STATS(SSL_NAME, KEY_NAME) \
4073 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4074 if (value == NULL) \
4075 goto error; \
4076 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4077 Py_DECREF(value); \
4078 if (r < 0) \
4079 goto error;
4080
4081 ADD_STATS(number, "number");
4082 ADD_STATS(connect, "connect");
4083 ADD_STATS(connect_good, "connect_good");
4084 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4085 ADD_STATS(accept, "accept");
4086 ADD_STATS(accept_good, "accept_good");
4087 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4088 ADD_STATS(accept, "accept");
4089 ADD_STATS(hits, "hits");
4090 ADD_STATS(misses, "misses");
4091 ADD_STATS(timeouts, "timeouts");
4092 ADD_STATS(cache_full, "cache_full");
4093
4094#undef ADD_STATS
4095
4096 return stats;
4097
4098error:
4099 Py_DECREF(stats);
4100 return NULL;
4101}
4102
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004103/*[clinic input]
4104_ssl._SSLContext.set_default_verify_paths
4105[clinic start generated code]*/
4106
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004107static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004108_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4109/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004110{
4111 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004112 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004113 return NULL;
4114 }
4115 Py_RETURN_NONE;
4116}
4117
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004118/*[clinic input]
4119_ssl._SSLContext.set_ecdh_curve
4120 name: object
4121 /
4122
4123[clinic start generated code]*/
4124
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004125static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004126_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4127/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004128{
4129 PyObject *name_bytes;
4130 int nid;
4131 EC_KEY *key;
4132
4133 if (!PyUnicode_FSConverter(name, &name_bytes))
4134 return NULL;
4135 assert(PyBytes_Check(name_bytes));
4136 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4137 Py_DECREF(name_bytes);
4138 if (nid == 0) {
4139 PyErr_Format(PyExc_ValueError,
4140 "unknown elliptic curve name %R", name);
4141 return NULL;
4142 }
4143 key = EC_KEY_new_by_curve_name(nid);
4144 if (key == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004145 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004146 return NULL;
4147 }
4148 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4149 EC_KEY_free(key);
4150 Py_RETURN_NONE;
4151}
4152
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004153static int
4154_servername_callback(SSL *s, int *al, void *args)
4155{
4156 int ret;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004157 PySSLContext *sslctx = (PySSLContext *) args;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004158 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004159 PyObject *result;
4160 /* The high-level ssl.SSLSocket object */
4161 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004162 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004163 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004164
Christian Heimes7f1305e2021-04-17 20:06:38 +02004165 if (sslctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004166 /* remove race condition in this the call back while if removing the
4167 * callback is in progress */
4168 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004169 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004170 }
4171
4172 ssl = SSL_get_app_data(s);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004173 assert(Py_IS_TYPE(ssl, get_state_ctx(sslctx)->PySSLSocket_Type));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004174
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004175 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004176 * SSL connection and that has a .context attribute that can be changed to
4177 * identify the requested hostname. Since the official API is the Python
4178 * level API we want to pass the callback a Python level object rather than
4179 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4180 * SSLObject) that will be passed. Otherwise if there's a socket then that
4181 * will be passed. If both do not exist only then the C-level object is
4182 * passed. */
4183 if (ssl->owner)
4184 ssl_socket = PyWeakref_GetObject(ssl->owner);
4185 else if (ssl->Socket)
4186 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4187 else
4188 ssl_socket = (PyObject *) ssl;
4189
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004190 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004191 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004192 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004193
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004194 if (servername == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004195 result = PyObject_CallFunctionObjArgs(sslctx->set_sni_cb, ssl_socket,
4196 Py_None, sslctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004197 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004198 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004199 PyObject *servername_bytes;
4200 PyObject *servername_str;
4201
4202 servername_bytes = PyBytes_FromString(servername);
4203 if (servername_bytes == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004204 PyErr_WriteUnraisable((PyObject *) sslctx);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004205 goto error;
4206 }
Christian Heimes11a14932018-02-24 02:35:08 +01004207 /* server_hostname was encoded to an A-label by our caller; put it
4208 * back into a str object, but still as an A-label (bpo-28414)
4209 */
4210 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004211 if (servername_str == NULL) {
4212 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004213 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004214 goto error;
4215 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004216 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004217 result = PyObject_CallFunctionObjArgs(
Christian Heimes7f1305e2021-04-17 20:06:38 +02004218 sslctx->set_sni_cb, ssl_socket, servername_str,
4219 sslctx, NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004220 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004221 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004222 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004223
4224 if (result == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004225 PyErr_WriteUnraisable(sslctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004226 *al = SSL_AD_HANDSHAKE_FAILURE;
4227 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4228 }
4229 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004230 /* Result may be None, a SSLContext or an integer
4231 * None and SSLContext are OK, integer or other values are an error.
4232 */
4233 if (result == Py_None) {
4234 ret = SSL_TLSEXT_ERR_OK;
4235 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004236 *al = (int) PyLong_AsLong(result);
4237 if (PyErr_Occurred()) {
4238 PyErr_WriteUnraisable(result);
4239 *al = SSL_AD_INTERNAL_ERROR;
4240 }
4241 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4242 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004243 Py_DECREF(result);
4244 }
4245
4246 PyGILState_Release(gstate);
4247 return ret;
4248
4249error:
4250 Py_DECREF(ssl_socket);
4251 *al = SSL_AD_INTERNAL_ERROR;
4252 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4253 PyGILState_Release(gstate);
4254 return ret;
4255}
4256
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004257static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004258get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004259{
Christian Heimes11a14932018-02-24 02:35:08 +01004260 PyObject *cb = self->set_sni_cb;
4261 if (cb == NULL) {
4262 Py_RETURN_NONE;
4263 }
4264 Py_INCREF(cb);
4265 return cb;
4266}
4267
4268static int
4269set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4270{
4271 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4272 PyErr_SetString(PyExc_ValueError,
4273 "sni_callback cannot be set on TLS_CLIENT context");
4274 return -1;
4275 }
Christian Heimes11a14932018-02-24 02:35:08 +01004276 Py_CLEAR(self->set_sni_cb);
4277 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004278 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4279 }
4280 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004281 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004282 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4283 PyErr_SetString(PyExc_TypeError,
4284 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004285 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004286 }
Christian Heimes11a14932018-02-24 02:35:08 +01004287 Py_INCREF(arg);
4288 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004289 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4290 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4291 }
Christian Heimes11a14932018-02-24 02:35:08 +01004292 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004293}
4294
Christian Heimes11a14932018-02-24 02:35:08 +01004295PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4296"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4297\n\
4298If the argument is None then the callback is disabled. The method is called\n\
4299with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4300See RFC 6066 for details of the SNI extension.");
4301
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004302/*[clinic input]
4303_ssl._SSLContext.cert_store_stats
4304
4305Returns quantities of loaded X.509 certificates.
4306
4307X.509 certificates with a CA extension and certificate revocation lists
4308inside the context's cert store.
4309
4310NOTE: Certificates in a capath directory aren't loaded unless they have
4311been used at least once.
4312[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004313
4314static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004315_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4316/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004317{
4318 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004319 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004320 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004321 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004322
4323 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004324 objs = X509_STORE_get0_objects(store);
4325 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4326 obj = sk_X509_OBJECT_value(objs, i);
4327 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004328 case X509_LU_X509:
4329 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004330 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004331 ca++;
4332 }
4333 break;
4334 case X509_LU_CRL:
4335 crl++;
4336 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004337 default:
4338 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4339 * As far as I can tell they are internal states and never
4340 * stored in a cert store */
4341 break;
4342 }
4343 }
4344 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4345 "x509_ca", ca);
4346}
4347
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004348/*[clinic input]
4349_ssl._SSLContext.get_ca_certs
4350 binary_form: bool = False
4351
4352Returns a list of dicts with information of loaded CA certs.
4353
4354If the optional argument is True, returns a DER-encoded copy of the CA
4355certificate.
4356
4357NOTE: Certificates in a capath directory aren't loaded unless they have
4358been used at least once.
4359[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004360
4361static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004362_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4363/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004364{
4365 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004366 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004367 PyObject *ci = NULL, *rlist = NULL;
4368 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004369
4370 if ((rlist = PyList_New(0)) == NULL) {
4371 return NULL;
4372 }
4373
4374 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004375 objs = X509_STORE_get0_objects(store);
4376 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004377 X509_OBJECT *obj;
4378 X509 *cert;
4379
Christian Heimes598894f2016-09-05 23:19:05 +02004380 obj = sk_X509_OBJECT_value(objs, i);
4381 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004382 /* not a x509 cert */
4383 continue;
4384 }
4385 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004386 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004387 if (!X509_check_ca(cert)) {
4388 continue;
4389 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004390 if (binary_form) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004391 ci = _certificate_to_der(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004392 } else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004393 ci = _decode_certificate(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004394 }
4395 if (ci == NULL) {
4396 goto error;
4397 }
4398 if (PyList_Append(rlist, ci) == -1) {
4399 goto error;
4400 }
4401 Py_CLEAR(ci);
4402 }
4403 return rlist;
4404
4405 error:
4406 Py_XDECREF(ci);
4407 Py_XDECREF(rlist);
4408 return NULL;
4409}
4410
4411
Antoine Pitrou152efa22010-05-16 18:19:27 +00004412static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004413 {"check_hostname", (getter) get_check_hostname,
4414 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004415 {"_host_flags", (getter) get_host_flags,
4416 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004417 {"minimum_version", (getter) get_minimum_version,
4418 (setter) set_minimum_version, NULL},
4419 {"maximum_version", (getter) get_maximum_version,
4420 (setter) set_maximum_version, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004421 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4422 (setter) _PySSLContext_set_keylog_filename, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004423 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4424 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004425 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004426 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes39258d32021-04-17 11:36:35 +02004427#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02004428 {"num_tickets", (getter) get_num_tickets,
4429 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4430#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004431 {"options", (getter) get_options,
4432 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004433 {"post_handshake_auth", (getter) get_post_handshake_auth,
4434#ifdef TLS1_3_VERSION
4435 (setter) set_post_handshake_auth,
4436#else
4437 NULL,
4438#endif
4439 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004440 {"protocol", (getter) get_protocol,
4441 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004442 {"verify_flags", (getter) get_verify_flags,
4443 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004444 {"verify_mode", (getter) get_verify_mode,
4445 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004446 {"security_level", (getter) get_security_level,
4447 NULL, PySSLContext_security_level_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004448 {NULL}, /* sentinel */
4449};
4450
4451static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004452 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4453 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4454 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4455 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004456 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4457 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4458 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4459 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4460 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4461 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004462 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4463 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004464 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004465 {NULL, NULL} /* sentinel */
4466};
4467
Christian Heimes5c36da72020-11-20 09:40:12 +01004468static PyType_Slot PySSLContext_slots[] = {
4469 {Py_tp_methods, context_methods},
4470 {Py_tp_getset, context_getsetlist},
4471 {Py_tp_new, _ssl__SSLContext},
4472 {Py_tp_dealloc, context_dealloc},
4473 {Py_tp_traverse, context_traverse},
4474 {Py_tp_clear, context_clear},
4475 {0, 0},
4476};
4477
4478static PyType_Spec PySSLContext_spec = {
4479 "_ssl._SSLContext",
4480 sizeof(PySSLContext),
4481 0,
4482 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
4483 PySSLContext_slots,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004484};
4485
4486
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004487/*
4488 * MemoryBIO objects
4489 */
4490
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004491/*[clinic input]
4492@classmethod
4493_ssl.MemoryBIO.__new__
4494
4495[clinic start generated code]*/
4496
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004497static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004498_ssl_MemoryBIO_impl(PyTypeObject *type)
4499/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004500{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004501 BIO *bio;
4502 PySSLMemoryBIO *self;
4503
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004504 bio = BIO_new(BIO_s_mem());
4505 if (bio == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004506 PyErr_SetString(PyExc_MemoryError, "failed to allocate BIO");
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004507 return NULL;
4508 }
4509 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4510 * just that no data is currently available. The SSL routines should retry
4511 * the read, which we can achieve by calling BIO_set_retry_read(). */
4512 BIO_set_retry_read(bio);
4513 BIO_set_mem_eof_return(bio, -1);
4514
4515 assert(type != NULL && type->tp_alloc != NULL);
4516 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4517 if (self == NULL) {
4518 BIO_free(bio);
4519 return NULL;
4520 }
4521 self->bio = bio;
4522 self->eof_written = 0;
4523
4524 return (PyObject *) self;
4525}
4526
4527static void
4528memory_bio_dealloc(PySSLMemoryBIO *self)
4529{
Christian Heimes5c36da72020-11-20 09:40:12 +01004530 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004531 BIO_free(self->bio);
4532 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004533 Py_DECREF(tp);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004534}
4535
4536static PyObject *
4537memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4538{
Segev Finer5cff6372017-07-27 01:19:17 +03004539 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004540}
4541
4542PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4543"The number of bytes pending in the memory BIO.");
4544
4545static PyObject *
4546memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4547{
4548 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4549 && self->eof_written);
4550}
4551
4552PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4553"Whether the memory BIO is at EOF.");
4554
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004555/*[clinic input]
4556_ssl.MemoryBIO.read
4557 size as len: int = -1
4558 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004559
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004560Read up to size bytes from the memory BIO.
4561
4562If size is not specified, read the entire buffer.
4563If the return value is an empty bytes instance, this means either
4564EOF or that no data is available. Use the "eof" property to
4565distinguish between the two.
4566[clinic start generated code]*/
4567
4568static PyObject *
4569_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4570/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4571{
4572 int avail, nbytes;
4573 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004574
Segev Finer5cff6372017-07-27 01:19:17 +03004575 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004576 if ((len < 0) || (len > avail))
4577 len = avail;
4578
4579 result = PyBytes_FromStringAndSize(NULL, len);
4580 if ((result == NULL) || (len == 0))
4581 return result;
4582
4583 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004584 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004585 _sslmodulestate *state = get_state_mbio(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004586 Py_DECREF(result);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004587 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004588 return NULL;
4589 }
4590
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004591 /* There should never be any short reads but check anyway. */
4592 if (nbytes < len) {
4593 _PyBytes_Resize(&result, nbytes);
4594 }
4595
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004596 return result;
4597}
4598
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004599/*[clinic input]
4600_ssl.MemoryBIO.write
4601 b: Py_buffer
4602 /
4603
4604Writes the bytes b into the memory BIO.
4605
4606Returns the number of bytes written.
4607[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004608
4609static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004610_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4611/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004612{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004613 int nbytes;
4614
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004615 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004616 PyErr_Format(PyExc_OverflowError,
4617 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004618 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004619 }
4620
4621 if (self->eof_written) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004622 PyObject *module = PyType_GetModule(Py_TYPE(self));
4623 if (module == NULL)
4624 return NULL;
4625 PyErr_SetString(get_ssl_state(module)->PySSLErrorObject,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004626 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004627 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004628 }
4629
Segev Finer5cff6372017-07-27 01:19:17 +03004630 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004631 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004632 _sslmodulestate *state = get_state_mbio(self);
4633 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004634 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004635 }
4636
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004637 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004638}
4639
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004640/*[clinic input]
4641_ssl.MemoryBIO.write_eof
4642
4643Write an EOF marker to the memory BIO.
4644
4645When all data has been read, the "eof" property will be True.
4646[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004647
4648static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004649_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4650/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004651{
4652 self->eof_written = 1;
4653 /* After an EOF is written, a zero return from read() should be a real EOF
4654 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4655 BIO_clear_retry_flags(self->bio);
4656 BIO_set_mem_eof_return(self->bio, 0);
4657
4658 Py_RETURN_NONE;
4659}
4660
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004661static PyGetSetDef memory_bio_getsetlist[] = {
4662 {"pending", (getter) memory_bio_get_pending, NULL,
4663 PySSL_memory_bio_pending_doc},
4664 {"eof", (getter) memory_bio_get_eof, NULL,
4665 PySSL_memory_bio_eof_doc},
4666 {NULL}, /* sentinel */
4667};
4668
4669static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004670 _SSL_MEMORYBIO_READ_METHODDEF
4671 _SSL_MEMORYBIO_WRITE_METHODDEF
4672 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004673 {NULL, NULL} /* sentinel */
4674};
4675
Christian Heimes5c36da72020-11-20 09:40:12 +01004676static PyType_Slot PySSLMemoryBIO_slots[] = {
4677 {Py_tp_methods, memory_bio_methods},
4678 {Py_tp_getset, memory_bio_getsetlist},
4679 {Py_tp_new, _ssl_MemoryBIO},
4680 {Py_tp_dealloc, memory_bio_dealloc},
4681 {0, 0},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004682};
4683
Christian Heimes5c36da72020-11-20 09:40:12 +01004684static PyType_Spec PySSLMemoryBIO_spec = {
4685 "_ssl.MemoryBIO",
4686 sizeof(PySSLMemoryBIO),
4687 0,
4688 Py_TPFLAGS_DEFAULT,
4689 PySSLMemoryBIO_slots,
4690};
Antoine Pitrou152efa22010-05-16 18:19:27 +00004691
Christian Heimes99a65702016-09-10 23:44:53 +02004692/*
4693 * SSL Session object
4694 */
4695
4696static void
4697PySSLSession_dealloc(PySSLSession *self)
4698{
Christian Heimes5c36da72020-11-20 09:40:12 +01004699 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09004700 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004701 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004702 Py_XDECREF(self->ctx);
4703 if (self->session != NULL) {
4704 SSL_SESSION_free(self->session);
4705 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004706 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004707 Py_DECREF(tp);
Christian Heimes99a65702016-09-10 23:44:53 +02004708}
4709
4710static PyObject *
4711PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4712{
4713 int result;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004714 PyTypeObject *sesstype = ((PySSLSession*)left)->ctx->state->PySSLSession_Type;
Christian Heimes99a65702016-09-10 23:44:53 +02004715
4716 if (left == NULL || right == NULL) {
4717 PyErr_BadInternalCall();
4718 return NULL;
4719 }
4720
Christian Heimes7f1305e2021-04-17 20:06:38 +02004721 if (!Py_IS_TYPE(left, sesstype) || !Py_IS_TYPE(right, sesstype)) {
Christian Heimes99a65702016-09-10 23:44:53 +02004722 Py_RETURN_NOTIMPLEMENTED;
4723 }
4724
4725 if (left == right) {
4726 result = 0;
4727 } else {
4728 const unsigned char *left_id, *right_id;
4729 unsigned int left_len, right_len;
4730 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4731 &left_len);
4732 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4733 &right_len);
4734 if (left_len == right_len) {
4735 result = memcmp(left_id, right_id, left_len);
4736 } else {
4737 result = 1;
4738 }
4739 }
4740
4741 switch (op) {
4742 case Py_EQ:
4743 if (result == 0) {
4744 Py_RETURN_TRUE;
4745 } else {
4746 Py_RETURN_FALSE;
4747 }
4748 break;
4749 case Py_NE:
4750 if (result != 0) {
4751 Py_RETURN_TRUE;
4752 } else {
4753 Py_RETURN_FALSE;
4754 }
4755 break;
4756 case Py_LT:
4757 case Py_LE:
4758 case Py_GT:
4759 case Py_GE:
4760 Py_RETURN_NOTIMPLEMENTED;
4761 break;
4762 default:
4763 PyErr_BadArgument();
4764 return NULL;
4765 }
4766}
4767
4768static int
4769PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4770{
4771 Py_VISIT(self->ctx);
4772 return 0;
4773}
4774
4775static int
4776PySSLSession_clear(PySSLSession *self)
4777{
4778 Py_CLEAR(self->ctx);
4779 return 0;
4780}
4781
4782
4783static PyObject *
4784PySSLSession_get_time(PySSLSession *self, void *closure) {
4785 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4786}
4787
4788PyDoc_STRVAR(PySSLSession_get_time_doc,
4789"Session creation time (seconds since epoch).");
4790
4791
4792static PyObject *
4793PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4794 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4795}
4796
4797PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4798"Session timeout (delta in seconds).");
4799
4800
4801static PyObject *
4802PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4803 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4804 return PyLong_FromUnsignedLong(hint);
4805}
4806
4807PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4808"Ticket life time hint.");
4809
4810
4811static PyObject *
4812PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4813 const unsigned char *id;
4814 unsigned int len;
4815 id = SSL_SESSION_get_id(self->session, &len);
4816 return PyBytes_FromStringAndSize((const char *)id, len);
4817}
4818
4819PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4820"Session id");
4821
4822
4823static PyObject *
4824PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4825 if (SSL_SESSION_has_ticket(self->session)) {
4826 Py_RETURN_TRUE;
4827 } else {
4828 Py_RETURN_FALSE;
4829 }
4830}
4831
4832PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4833"Does the session contain a ticket?");
4834
4835
4836static PyGetSetDef PySSLSession_getsetlist[] = {
4837 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4838 PySSLSession_get_has_ticket_doc},
4839 {"id", (getter) PySSLSession_get_session_id, NULL,
4840 PySSLSession_get_session_id_doc},
4841 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4842 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4843 {"time", (getter) PySSLSession_get_time, NULL,
4844 PySSLSession_get_time_doc},
4845 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4846 PySSLSession_get_timeout_doc},
4847 {NULL}, /* sentinel */
4848};
4849
Christian Heimes5c36da72020-11-20 09:40:12 +01004850static PyType_Slot PySSLSession_slots[] = {
4851 {Py_tp_getset,PySSLSession_getsetlist},
4852 {Py_tp_richcompare, PySSLSession_richcompare},
4853 {Py_tp_dealloc, PySSLSession_dealloc},
4854 {Py_tp_traverse, PySSLSession_traverse},
4855 {Py_tp_clear, PySSLSession_clear},
4856 {0, 0},
4857};
4858
4859static PyType_Spec PySSLSession_spec = {
4860 "_ssl.SSLSession",
4861 sizeof(PySSLSession),
4862 0,
4863 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
4864 PySSLSession_slots,
Christian Heimes99a65702016-09-10 23:44:53 +02004865};
4866
4867
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004868/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004869/*[clinic input]
4870_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004871 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004872 entropy: double
4873 /
4874
4875Mix string into the OpenSSL PRNG state.
4876
4877entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304878string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004879[clinic start generated code]*/
4880
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004881static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004882_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004883/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004884{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004885 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004886 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004887
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004888 buf = (const char *)view->buf;
4889 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004890 do {
4891 written = Py_MIN(len, INT_MAX);
4892 RAND_add(buf, (int)written, entropy);
4893 buf += written;
4894 len -= written;
4895 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004896 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004897}
4898
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004899static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02004900PySSL_RAND(PyObject *module, int len, int pseudo)
Victor Stinner99c8b162011-05-24 12:05:19 +02004901{
4902 int ok;
4903 PyObject *bytes;
4904 unsigned long err;
4905 const char *errstr;
4906 PyObject *v;
4907
Victor Stinner1e81a392013-12-19 16:47:04 +01004908 if (len < 0) {
4909 PyErr_SetString(PyExc_ValueError, "num must be positive");
4910 return NULL;
4911 }
4912
Victor Stinner99c8b162011-05-24 12:05:19 +02004913 bytes = PyBytes_FromStringAndSize(NULL, len);
4914 if (bytes == NULL)
4915 return NULL;
4916 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02004917 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Victor Stinner99c8b162011-05-24 12:05:19 +02004918 if (ok == 0 || ok == 1)
4919 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4920 }
4921 else {
4922 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4923 if (ok == 1)
4924 return bytes;
4925 }
4926 Py_DECREF(bytes);
4927
4928 err = ERR_get_error();
4929 errstr = ERR_reason_error_string(err);
4930 v = Py_BuildValue("(ks)", err, errstr);
4931 if (v != NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004932 PyErr_SetObject(get_ssl_state(module)->PySSLErrorObject, v);
Victor Stinner99c8b162011-05-24 12:05:19 +02004933 Py_DECREF(v);
4934 }
4935 return NULL;
4936}
4937
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004938/*[clinic input]
4939_ssl.RAND_bytes
4940 n: int
4941 /
4942
4943Generate n cryptographically strong pseudo-random bytes.
4944[clinic start generated code]*/
4945
Victor Stinner99c8b162011-05-24 12:05:19 +02004946static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004947_ssl_RAND_bytes_impl(PyObject *module, int n)
4948/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004949{
Christian Heimes7f1305e2021-04-17 20:06:38 +02004950 return PySSL_RAND(module, n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004951}
4952
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004953/*[clinic input]
4954_ssl.RAND_pseudo_bytes
4955 n: int
4956 /
4957
4958Generate n pseudo-random bytes.
4959
4960Return a pair (bytes, is_cryptographic). is_cryptographic is True
4961if the bytes generated are cryptographically strong.
4962[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004963
4964static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004965_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4966/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004967{
Christian Heimes7f1305e2021-04-17 20:06:38 +02004968 return PySSL_RAND(module, n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004969}
4970
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004971/*[clinic input]
4972_ssl.RAND_status
4973
4974Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4975
4976It is necessary to seed the PRNG with RAND_add() on some platforms before
4977using the ssl() function.
4978[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004979
4980static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004981_ssl_RAND_status_impl(PyObject *module)
4982/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004983{
Christian Heimes217cfd12007-12-02 14:31:20 +00004984 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004985}
4986
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004987/*[clinic input]
4988_ssl.get_default_verify_paths
4989
4990Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4991
4992The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4993[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004994
4995static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004996_ssl_get_default_verify_paths_impl(PyObject *module)
4997/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004998{
4999 PyObject *ofile_env = NULL;
5000 PyObject *ofile = NULL;
5001 PyObject *odir_env = NULL;
5002 PyObject *odir = NULL;
5003
Benjamin Petersond113c962015-07-18 10:59:13 -07005004#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005005 const char *tmp = (info); \
5006 target = NULL; \
5007 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5008 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5009 target = PyBytes_FromString(tmp); } \
5010 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005011 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005012
Benjamin Petersond113c962015-07-18 10:59:13 -07005013 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5014 CONVERT(X509_get_default_cert_file(), ofile);
5015 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5016 CONVERT(X509_get_default_cert_dir(), odir);
5017#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005018
Christian Heimes200bb1b2013-06-14 15:14:29 +02005019 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005020
5021 error:
5022 Py_XDECREF(ofile_env);
5023 Py_XDECREF(ofile);
5024 Py_XDECREF(odir_env);
5025 Py_XDECREF(odir);
5026 return NULL;
5027}
5028
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005029static PyObject*
Christian Heimes7f1305e2021-04-17 20:06:38 +02005030asn1obj2py(_sslmodulestate *state, ASN1_OBJECT *obj)
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005031{
5032 int nid;
5033 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005034
5035 nid = OBJ_obj2nid(obj);
5036 if (nid == NID_undef) {
5037 PyErr_Format(PyExc_ValueError, "Unknown object");
5038 return NULL;
5039 }
5040 sn = OBJ_nid2sn(nid);
5041 ln = OBJ_nid2ln(nid);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005042 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(state, obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005043}
5044
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005045/*[clinic input]
5046_ssl.txt2obj
5047 txt: str
5048 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005049
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005050Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5051
5052By default objects are looked up by OID. With name=True short and
5053long name are also matched.
5054[clinic start generated code]*/
5055
5056static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005057_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5058/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005059{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005060 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005061 ASN1_OBJECT *obj;
5062
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005063 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5064 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005065 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005066 return NULL;
5067 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005068 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005069 ASN1_OBJECT_free(obj);
5070 return result;
5071}
5072
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005073/*[clinic input]
5074_ssl.nid2obj
5075 nid: int
5076 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005077
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005078Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5079[clinic start generated code]*/
5080
5081static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005082_ssl_nid2obj_impl(PyObject *module, int nid)
5083/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005084{
5085 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005086 ASN1_OBJECT *obj;
5087
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005088 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005089 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005090 return NULL;
5091 }
5092 obj = OBJ_nid2obj(nid);
5093 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005094 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005095 return NULL;
5096 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005097 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005098 ASN1_OBJECT_free(obj);
5099 return result;
5100}
5101
Christian Heimes46bebee2013-06-09 19:03:31 +02005102#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005103
5104static PyObject*
5105certEncodingType(DWORD encodingType)
5106{
5107 static PyObject *x509_asn = NULL;
5108 static PyObject *pkcs_7_asn = NULL;
5109
5110 if (x509_asn == NULL) {
5111 x509_asn = PyUnicode_InternFromString("x509_asn");
5112 if (x509_asn == NULL)
5113 return NULL;
5114 }
5115 if (pkcs_7_asn == NULL) {
5116 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5117 if (pkcs_7_asn == NULL)
5118 return NULL;
5119 }
5120 switch(encodingType) {
5121 case X509_ASN_ENCODING:
5122 Py_INCREF(x509_asn);
5123 return x509_asn;
5124 case PKCS_7_ASN_ENCODING:
5125 Py_INCREF(pkcs_7_asn);
5126 return pkcs_7_asn;
5127 default:
5128 return PyLong_FromLong(encodingType);
5129 }
5130}
5131
5132static PyObject*
5133parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5134{
5135 CERT_ENHKEY_USAGE *usage;
5136 DWORD size, error, i;
5137 PyObject *retval;
5138
5139 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5140 error = GetLastError();
5141 if (error == CRYPT_E_NOT_FOUND) {
5142 Py_RETURN_TRUE;
5143 }
5144 return PyErr_SetFromWindowsErr(error);
5145 }
5146
5147 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5148 if (usage == NULL) {
5149 return PyErr_NoMemory();
5150 }
5151
5152 /* Now get the actual enhanced usage property */
5153 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5154 PyMem_Free(usage);
5155 error = GetLastError();
5156 if (error == CRYPT_E_NOT_FOUND) {
5157 Py_RETURN_TRUE;
5158 }
5159 return PyErr_SetFromWindowsErr(error);
5160 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005161 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005162 if (retval == NULL) {
5163 goto error;
5164 }
5165 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5166 if (usage->rgpszUsageIdentifier[i]) {
5167 PyObject *oid;
5168 int err;
5169 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5170 if (oid == NULL) {
5171 Py_CLEAR(retval);
5172 goto error;
5173 }
5174 err = PySet_Add(retval, oid);
5175 Py_DECREF(oid);
5176 if (err == -1) {
5177 Py_CLEAR(retval);
5178 goto error;
5179 }
5180 }
5181 }
5182 error:
5183 PyMem_Free(usage);
5184 return retval;
5185}
5186
kctherookied93fbbf2019-03-29 00:59:06 +07005187static HCERTSTORE
5188ssl_collect_certificates(const char *store_name)
5189{
5190/* this function collects the system certificate stores listed in
5191 * system_stores into a collection certificate store for being
5192 * enumerated. The store must be readable to be added to the
5193 * store collection.
5194 */
5195
5196 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5197 static DWORD system_stores[] = {
5198 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5199 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5200 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5201 CERT_SYSTEM_STORE_CURRENT_USER,
5202 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5203 CERT_SYSTEM_STORE_SERVICES,
5204 CERT_SYSTEM_STORE_USERS};
5205 size_t i, storesAdded;
5206 BOOL result;
5207
5208 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5209 (HCRYPTPROV)NULL, 0, NULL);
5210 if (!hCollectionStore) {
5211 return NULL;
5212 }
5213 storesAdded = 0;
5214 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5215 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5216 (HCRYPTPROV)NULL,
5217 CERT_STORE_READONLY_FLAG |
5218 system_stores[i], store_name);
5219 if (hSystemStore) {
5220 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5221 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5222 if (result) {
5223 ++storesAdded;
5224 }
neoneneed701292019-09-09 21:33:43 +09005225 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005226 }
5227 }
5228 if (storesAdded == 0) {
5229 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5230 return NULL;
5231 }
5232
5233 return hCollectionStore;
5234}
5235
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005236/*[clinic input]
5237_ssl.enum_certificates
5238 store_name: str
5239
5240Retrieve certificates from Windows' cert store.
5241
5242store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5243more cert storages, too. The function returns a list of (bytes,
5244encoding_type, trust) tuples. The encoding_type flag can be interpreted
5245with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5246a set of OIDs or the boolean True.
5247[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005248
Christian Heimes46bebee2013-06-09 19:03:31 +02005249static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005250_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5251/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005252{
kctherookied93fbbf2019-03-29 00:59:06 +07005253 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005254 PCCERT_CONTEXT pCertCtx = NULL;
5255 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005256 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005257
Christian Heimes915cd3f2019-09-09 18:06:55 +02005258 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005259 if (result == NULL) {
5260 return NULL;
5261 }
kctherookied93fbbf2019-03-29 00:59:06 +07005262 hCollectionStore = ssl_collect_certificates(store_name);
5263 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005264 Py_DECREF(result);
5265 return PyErr_SetFromWindowsErr(GetLastError());
5266 }
5267
kctherookied93fbbf2019-03-29 00:59:06 +07005268 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005269 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5270 pCertCtx->cbCertEncoded);
5271 if (!cert) {
5272 Py_CLEAR(result);
5273 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005274 }
Christian Heimes44109d72013-11-22 01:51:30 +01005275 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5276 Py_CLEAR(result);
5277 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005278 }
Christian Heimes44109d72013-11-22 01:51:30 +01005279 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5280 if (keyusage == Py_True) {
5281 Py_DECREF(keyusage);
5282 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005283 }
Christian Heimes44109d72013-11-22 01:51:30 +01005284 if (keyusage == NULL) {
5285 Py_CLEAR(result);
5286 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005287 }
Christian Heimes44109d72013-11-22 01:51:30 +01005288 if ((tup = PyTuple_New(3)) == NULL) {
5289 Py_CLEAR(result);
5290 break;
5291 }
5292 PyTuple_SET_ITEM(tup, 0, cert);
5293 cert = NULL;
5294 PyTuple_SET_ITEM(tup, 1, enc);
5295 enc = NULL;
5296 PyTuple_SET_ITEM(tup, 2, keyusage);
5297 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005298 if (PySet_Add(result, tup) == -1) {
5299 Py_CLEAR(result);
5300 Py_CLEAR(tup);
5301 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005302 }
5303 Py_CLEAR(tup);
5304 }
5305 if (pCertCtx) {
5306 /* loop ended with an error, need to clean up context manually */
5307 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005308 }
5309
5310 /* In error cases cert, enc and tup may not be NULL */
5311 Py_XDECREF(cert);
5312 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005313 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005314 Py_XDECREF(tup);
5315
kctherookied93fbbf2019-03-29 00:59:06 +07005316 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5317 associated with the store, in this case our collection store and the
5318 associated system stores. */
5319 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005320 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005321 Py_XDECREF(result);
5322 return PyErr_SetFromWindowsErr(GetLastError());
5323 }
kctherookied93fbbf2019-03-29 00:59:06 +07005324
Christian Heimes915cd3f2019-09-09 18:06:55 +02005325 /* convert set to list */
5326 if (result == NULL) {
5327 return NULL;
5328 } else {
5329 PyObject *lst = PySequence_List(result);
5330 Py_DECREF(result);
5331 return lst;
5332 }
Christian Heimes44109d72013-11-22 01:51:30 +01005333}
5334
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005335/*[clinic input]
5336_ssl.enum_crls
5337 store_name: str
5338
5339Retrieve CRLs from Windows' cert store.
5340
5341store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5342more cert storages, too. The function returns a list of (bytes,
5343encoding_type) tuples. The encoding_type flag can be interpreted with
5344X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5345[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005346
5347static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005348_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5349/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005350{
kctherookied93fbbf2019-03-29 00:59:06 +07005351 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005352 PCCRL_CONTEXT pCrlCtx = NULL;
5353 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5354 PyObject *result = NULL;
5355
Christian Heimes915cd3f2019-09-09 18:06:55 +02005356 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005357 if (result == NULL) {
5358 return NULL;
5359 }
kctherookied93fbbf2019-03-29 00:59:06 +07005360 hCollectionStore = ssl_collect_certificates(store_name);
5361 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005362 Py_DECREF(result);
5363 return PyErr_SetFromWindowsErr(GetLastError());
5364 }
Christian Heimes44109d72013-11-22 01:51:30 +01005365
kctherookied93fbbf2019-03-29 00:59:06 +07005366 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005367 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5368 pCrlCtx->cbCrlEncoded);
5369 if (!crl) {
5370 Py_CLEAR(result);
5371 break;
5372 }
5373 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5374 Py_CLEAR(result);
5375 break;
5376 }
5377 if ((tup = PyTuple_New(2)) == NULL) {
5378 Py_CLEAR(result);
5379 break;
5380 }
5381 PyTuple_SET_ITEM(tup, 0, crl);
5382 crl = NULL;
5383 PyTuple_SET_ITEM(tup, 1, enc);
5384 enc = NULL;
5385
Christian Heimes915cd3f2019-09-09 18:06:55 +02005386 if (PySet_Add(result, tup) == -1) {
5387 Py_CLEAR(result);
5388 Py_CLEAR(tup);
5389 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005390 }
5391 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005392 }
Christian Heimes44109d72013-11-22 01:51:30 +01005393 if (pCrlCtx) {
5394 /* loop ended with an error, need to clean up context manually */
5395 CertFreeCRLContext(pCrlCtx);
5396 }
5397
5398 /* In error cases cert, enc and tup may not be NULL */
5399 Py_XDECREF(crl);
5400 Py_XDECREF(enc);
5401 Py_XDECREF(tup);
5402
kctherookied93fbbf2019-03-29 00:59:06 +07005403 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5404 associated with the store, in this case our collection store and the
5405 associated system stores. */
5406 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005407 /* This error case might shadow another exception.*/
5408 Py_XDECREF(result);
5409 return PyErr_SetFromWindowsErr(GetLastError());
5410 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005411 /* convert set to list */
5412 if (result == NULL) {
5413 return NULL;
5414 } else {
5415 PyObject *lst = PySequence_List(result);
5416 Py_DECREF(result);
5417 return lst;
5418 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005419}
Christian Heimes44109d72013-11-22 01:51:30 +01005420
5421#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005422
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005423/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005424static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005425 _SSL__TEST_DECODE_CERT_METHODDEF
5426 _SSL_RAND_ADD_METHODDEF
5427 _SSL_RAND_BYTES_METHODDEF
5428 _SSL_RAND_PSEUDO_BYTES_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005429 _SSL_RAND_STATUS_METHODDEF
5430 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5431 _SSL_ENUM_CERTIFICATES_METHODDEF
5432 _SSL_ENUM_CRLS_METHODDEF
5433 _SSL_TXT2OBJ_METHODDEF
5434 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005435 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005436};
5437
5438
Christian Heimes7f1305e2021-04-17 20:06:38 +02005439PyDoc_STRVAR(module_doc,
5440"Implementation module for SSL socket operations. See the socket module\n\
5441for documentation.");
Christian Heimes5c36da72020-11-20 09:40:12 +01005442
5443static int
5444sslmodule_init_exceptions(PyObject *module)
5445{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005446 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005447 PyObject *bases = NULL;
5448
Christian Heimes7f1305e2021-04-17 20:06:38 +02005449#define add_exception(exc, name, doc, base) \
5450do { \
5451 (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5452 if ((state) == NULL) goto error; \
5453 if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
Christian Heimes5c36da72020-11-20 09:40:12 +01005454} while(0)
5455
Christian Heimes7f1305e2021-04-17 20:06:38 +02005456 state->PySSLErrorObject = PyType_FromSpecWithBases(
5457 &sslerror_type_spec, PyExc_OSError);
5458 if (state->PySSLErrorObject == NULL) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005459 goto error;
5460 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005461 if (PyModule_AddObjectRef(module, "SSLError", state->PySSLErrorObject) < 0) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005462 goto error;
5463 }
5464
5465 /* ssl.CertificateError used to be a subclass of ValueError */
Christian Heimes7f1305e2021-04-17 20:06:38 +02005466 bases = PyTuple_Pack(2, state->PySSLErrorObject, PyExc_ValueError);
Christian Heimes5c36da72020-11-20 09:40:12 +01005467 if (bases == NULL) {
5468 goto error;
5469 }
5470 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005471 state->PySSLCertVerificationErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005472 "SSLCertVerificationError",
5473 SSLCertVerificationError_doc,
5474 bases
5475 );
5476 Py_CLEAR(bases);
5477
5478 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005479 state->PySSLZeroReturnErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005480 "SSLZeroReturnError",
5481 SSLZeroReturnError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005482 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005483 );
5484
5485 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005486 state->PySSLWantWriteErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005487 "SSLWantWriteError",
5488 SSLWantWriteError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005489 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005490 );
5491
5492 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005493 state->PySSLWantReadErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005494 "SSLWantReadError",
5495 SSLWantReadError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005496 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005497 );
5498
5499 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005500 state->PySSLSyscallErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005501 "SSLSyscallError",
5502 SSLSyscallError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005503 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005504 );
5505
5506 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005507 state->PySSLEOFErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005508 "SSLEOFError",
5509 SSLEOFError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005510 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005511 );
5512#undef add_exception
5513
5514 return 0;
5515 error:
5516 Py_XDECREF(bases);
5517 return -1;
5518}
5519
5520static int
5521sslmodule_init_socketapi(PyObject *module)
5522{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005523 _sslmodulestate *state = get_ssl_state(module);
5524 PySocketModule_APIObject *sockmod = PySocketModule_ImportModuleAndAPI();
Christian Heimes5c36da72020-11-20 09:40:12 +01005525
Christian Heimes7f1305e2021-04-17 20:06:38 +02005526 if ((sockmod == NULL) || (sockmod->Sock_Type == NULL)) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005527 return -1;
Christian Heimes5c36da72020-11-20 09:40:12 +01005528 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005529 state->Sock_Type = sockmod->Sock_Type;
5530 Py_INCREF(state->Sock_Type);
Christian Heimes5c36da72020-11-20 09:40:12 +01005531 return 0;
5532}
Christian Heimesc941e622017-09-05 15:47:11 +02005533
Christian Heimes5c36da72020-11-20 09:40:12 +01005534static int
5535sslmodule_init_constants(PyObject *m)
5536{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005537
Christian Heimes892d66e2018-01-29 14:10:18 +01005538 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5539 PY_SSL_DEFAULT_CIPHER_STRING);
5540
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005541 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5542 PY_SSL_ERROR_ZERO_RETURN);
5543 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5544 PY_SSL_ERROR_WANT_READ);
5545 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5546 PY_SSL_ERROR_WANT_WRITE);
5547 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5548 PY_SSL_ERROR_WANT_X509_LOOKUP);
5549 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5550 PY_SSL_ERROR_SYSCALL);
5551 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5552 PY_SSL_ERROR_SSL);
5553 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5554 PY_SSL_ERROR_WANT_CONNECT);
5555 /* non ssl.h errorcodes */
5556 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5557 PY_SSL_ERROR_EOF);
5558 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5559 PY_SSL_ERROR_INVALID_ERROR_CODE);
5560 /* cert requirements */
5561 PyModule_AddIntConstant(m, "CERT_NONE",
5562 PY_SSL_CERT_NONE);
5563 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5564 PY_SSL_CERT_OPTIONAL);
5565 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5566 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005567 /* CRL verification for verification_flags */
5568 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5569 0);
5570 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5571 X509_V_FLAG_CRL_CHECK);
5572 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5573 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5574 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5575 X509_V_FLAG_X509_STRICT);
Chris Burre0b4aa02021-03-18 09:24:01 +01005576 PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
5577 X509_V_FLAG_ALLOW_PROXY_CERTS);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005578 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5579 X509_V_FLAG_TRUSTED_FIRST);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005580
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005581 /* Alert Descriptions from ssl.h */
5582 /* note RESERVED constants no longer intended for use have been removed */
5583 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5584
5585#define ADD_AD_CONSTANT(s) \
5586 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5587 SSL_AD_##s)
5588
5589 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5590 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5591 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5592 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5593 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5594 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5595 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5596 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5597 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5598 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5599 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5600 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5601 ADD_AD_CONSTANT(UNKNOWN_CA);
5602 ADD_AD_CONSTANT(ACCESS_DENIED);
5603 ADD_AD_CONSTANT(DECODE_ERROR);
5604 ADD_AD_CONSTANT(DECRYPT_ERROR);
5605 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5606 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5607 ADD_AD_CONSTANT(INTERNAL_ERROR);
5608 ADD_AD_CONSTANT(USER_CANCELLED);
5609 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005610 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005611#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5612 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5613#endif
5614#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5615 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5616#endif
5617#ifdef SSL_AD_UNRECOGNIZED_NAME
5618 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5619#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005620#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5621 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5622#endif
5623#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5624 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5625#endif
5626#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5627 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5628#endif
5629
5630#undef ADD_AD_CONSTANT
5631
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005632 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005633#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005634 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5635 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005636#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005637#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005638 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5639 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005640#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005641 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005642 PY_SSL_VERSION_TLS);
5643 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5644 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005645 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5646 PY_SSL_VERSION_TLS_CLIENT);
5647 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5648 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005649 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5650 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005651 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5652 PY_SSL_VERSION_TLS1_1);
5653 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5654 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005655
Antoine Pitroub5218772010-05-21 09:56:06 +00005656 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005657 PyModule_AddIntConstant(m, "OP_ALL",
5658 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005659 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5660 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5661 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005662 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5663 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005664#ifdef SSL_OP_NO_TLSv1_3
5665 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5666#else
5667 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5668#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005669 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5670 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005671 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005672 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005673#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005674 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005675#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005676#ifdef SSL_OP_NO_COMPRESSION
5677 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5678 SSL_OP_NO_COMPRESSION);
5679#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005680#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5681 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5682 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5683#endif
Christian Heimes67c48012018-05-15 16:25:40 -04005684#ifdef SSL_OP_NO_RENEGOTIATION
5685 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5686 SSL_OP_NO_RENEGOTIATION);
5687#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02005688#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
5689 PyModule_AddIntConstant(m, "OP_IGNORE_UNEXPECTED_EOF",
5690 SSL_OP_IGNORE_UNEXPECTED_EOF);
5691#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005692
Christian Heimes61d478c2018-01-27 15:51:38 +01005693#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5694 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5695 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5696#endif
5697#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5698 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5699 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5700#endif
5701#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5702 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5703 X509_CHECK_FLAG_NO_WILDCARDS);
5704#endif
5705#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5706 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5707 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5708#endif
5709#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5710 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5711 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5712#endif
5713#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5714 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5715 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5716#endif
5717
Christian Heimes698dde12018-02-27 11:54:43 +01005718 /* protocol versions */
5719 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5720 PY_PROTO_MINIMUM_SUPPORTED);
5721 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5722 PY_PROTO_MAXIMUM_SUPPORTED);
5723 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5724 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5725 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5726 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5727 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005728
Victor Stinnerb37672d2018-11-22 03:37:50 +01005729#define addbool(m, key, value) \
5730 do { \
5731 PyObject *bool_obj = (value) ? Py_True : Py_False; \
5732 Py_INCREF(bool_obj); \
5733 PyModule_AddObject((m), (key), bool_obj); \
5734 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01005735
Christian Heimes698dde12018-02-27 11:54:43 +01005736 addbool(m, "HAS_SNI", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005737 addbool(m, "HAS_TLS_UNIQUE", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005738 addbool(m, "HAS_ECDH", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005739 addbool(m, "HAS_NPN", 0);
Christian Heimes698dde12018-02-27 11:54:43 +01005740 addbool(m, "HAS_ALPN", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005741
5742#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5743 addbool(m, "HAS_SSLv2", 1);
5744#else
5745 addbool(m, "HAS_SSLv2", 0);
5746#endif
5747
5748#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5749 addbool(m, "HAS_SSLv3", 1);
5750#else
5751 addbool(m, "HAS_SSLv3", 0);
5752#endif
5753
5754#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5755 addbool(m, "HAS_TLSv1", 1);
5756#else
5757 addbool(m, "HAS_TLSv1", 0);
5758#endif
5759
5760#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5761 addbool(m, "HAS_TLSv1_1", 1);
5762#else
5763 addbool(m, "HAS_TLSv1_1", 0);
5764#endif
5765
5766#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5767 addbool(m, "HAS_TLSv1_2", 1);
5768#else
5769 addbool(m, "HAS_TLSv1_2", 0);
5770#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005771
Christian Heimescb5b68a2017-09-07 18:07:00 -07005772#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005773 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005774#else
Christian Heimes698dde12018-02-27 11:54:43 +01005775 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005776#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005777
Christian Heimes5c36da72020-11-20 09:40:12 +01005778 return 0;
5779}
5780
Christian Heimes7f1305e2021-04-17 20:06:38 +02005781static int
5782sslmodule_init_errorcodes(PyObject *module)
5783{
5784 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005785
Christian Heimes7f1305e2021-04-17 20:06:38 +02005786 struct py_ssl_error_code *errcode;
5787 struct py_ssl_library_code *libcode;
Christian Heimes5c36da72020-11-20 09:40:12 +01005788
Christian Heimes7f1305e2021-04-17 20:06:38 +02005789 /* Mappings for error codes */
5790 state->err_codes_to_names = PyDict_New();
5791 if (state->err_codes_to_names == NULL)
5792 return -1;
5793 state->err_names_to_codes = PyDict_New();
5794 if (state->err_names_to_codes == NULL)
5795 return -1;
5796 state->lib_codes_to_names = PyDict_New();
5797 if (state->lib_codes_to_names == NULL)
5798 return -1;
5799
5800 errcode = error_codes;
5801 while (errcode->mnemonic != NULL) {
5802 PyObject *mnemo, *key;
5803 mnemo = PyUnicode_FromString(errcode->mnemonic);
5804 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5805 if (mnemo == NULL || key == NULL)
5806 return -1;
5807 if (PyDict_SetItem(state->err_codes_to_names, key, mnemo))
5808 return -1;
5809 if (PyDict_SetItem(state->err_names_to_codes, mnemo, key))
5810 return -1;
5811 Py_DECREF(key);
5812 Py_DECREF(mnemo);
5813 errcode++;
5814 }
5815
5816 libcode = library_codes;
5817 while (libcode->library != NULL) {
5818 PyObject *mnemo, *key;
5819 key = PyLong_FromLong(libcode->code);
5820 mnemo = PyUnicode_FromString(libcode->library);
5821 if (key == NULL || mnemo == NULL)
5822 return -1;
5823 if (PyDict_SetItem(state->lib_codes_to_names, key, mnemo))
5824 return -1;
5825 Py_DECREF(key);
5826 Py_DECREF(mnemo);
5827 libcode++;
5828 }
5829
5830 if (PyModule_AddObjectRef(module, "err_codes_to_names", state->err_codes_to_names))
5831 return -1;
5832 if (PyModule_AddObjectRef(module, "err_names_to_codes", state->err_names_to_codes))
5833 return -1;
5834 if (PyModule_AddObjectRef(module, "lib_codes_to_names", state->lib_codes_to_names))
5835 return -1;
5836
5837 return 0;
5838}
5839
5840static void
5841parse_openssl_version(unsigned long libver,
5842 unsigned int *major, unsigned int *minor,
5843 unsigned int *fix, unsigned int *patch,
5844 unsigned int *status)
5845{
5846 *status = libver & 0xF;
5847 libver >>= 4;
5848 *patch = libver & 0xFF;
5849 libver >>= 8;
5850 *fix = libver & 0xFF;
5851 libver >>= 8;
5852 *minor = libver & 0xFF;
5853 libver >>= 8;
5854 *major = libver & 0xFF;
5855}
5856
5857static int
5858sslmodule_init_versioninfo(PyObject *m)
5859{
5860 PyObject *r;
5861 unsigned long libver;
5862 unsigned int major, minor, fix, patch, status;
5863
5864 /* OpenSSL version */
5865 /* SSLeay() gives us the version of the library linked against,
5866 which could be different from the headers version.
5867 */
5868 libver = OpenSSL_version_num();
5869 r = PyLong_FromUnsignedLong(libver);
5870 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5871 return -1;
5872
5873 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5874 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5875 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5876 return -1;
5877
5878 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
5879 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5880 return -1;
5881
5882 libver = OPENSSL_VERSION_NUMBER;
5883 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5884 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5885 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5886 return -1;
5887
5888 return 0;
5889}
5890
5891static int
5892sslmodule_init_types(PyObject *module)
5893{
5894 _sslmodulestate *state = get_ssl_state(module);
5895
5896 state->PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5897 module, &PySSLContext_spec, NULL
5898 );
5899 if (state->PySSLContext_Type == NULL)
5900 return -1;
5901
5902 state->PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5903 module, &PySSLSocket_spec, NULL
5904 );
5905 if (state->PySSLSocket_Type == NULL)
5906 return -1;
5907
5908 state->PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5909 module, &PySSLMemoryBIO_spec, NULL
5910 );
5911 if (state->PySSLMemoryBIO_Type == NULL)
5912 return -1;
5913
5914 state->PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5915 module, &PySSLSession_spec, NULL
5916 );
5917 if (state->PySSLSession_Type == NULL)
5918 return -1;
5919
5920 if (PyModule_AddType(module, state->PySSLContext_Type))
5921 return -1;
5922 if (PyModule_AddType(module, state->PySSLSocket_Type))
5923 return -1;
5924 if (PyModule_AddType(module, state->PySSLMemoryBIO_Type))
5925 return -1;
5926 if (PyModule_AddType(module, state->PySSLSession_Type))
5927 return -1;
5928
5929 return 0;
5930}
5931
5932static PyModuleDef_Slot sslmodule_slots[] = {
5933 {Py_mod_exec, sslmodule_init_types},
5934 {Py_mod_exec, sslmodule_init_exceptions},
5935 {Py_mod_exec, sslmodule_init_socketapi},
5936 {Py_mod_exec, sslmodule_init_errorcodes},
5937 {Py_mod_exec, sslmodule_init_constants},
5938 {Py_mod_exec, sslmodule_init_versioninfo},
5939 {0, NULL}
5940};
5941
5942static int
5943sslmodule_traverse(PyObject *m, visitproc visit, void *arg)
5944{
5945 _sslmodulestate *state = get_ssl_state(m);
5946
5947 Py_VISIT(state->PySSLContext_Type);
5948 Py_VISIT(state->PySSLSocket_Type);
5949 Py_VISIT(state->PySSLMemoryBIO_Type);
5950 Py_VISIT(state->PySSLSession_Type);
5951 Py_VISIT(state->PySSLErrorObject);
5952 Py_VISIT(state->PySSLCertVerificationErrorObject);
5953 Py_VISIT(state->PySSLZeroReturnErrorObject);
5954 Py_VISIT(state->PySSLWantReadErrorObject);
5955 Py_VISIT(state->PySSLWantWriteErrorObject);
5956 Py_VISIT(state->PySSLSyscallErrorObject);
5957 Py_VISIT(state->PySSLEOFErrorObject);
5958 Py_VISIT(state->err_codes_to_names);
5959 Py_VISIT(state->err_names_to_codes);
5960 Py_VISIT(state->lib_codes_to_names);
5961 Py_VISIT(state->Sock_Type);
5962
5963 return 0;
5964}
5965
5966static int
5967sslmodule_clear(PyObject *m)
5968{
5969 _sslmodulestate *state = get_ssl_state(m);
5970
5971 Py_CLEAR(state->PySSLContext_Type);
5972 Py_CLEAR(state->PySSLSocket_Type);
5973 Py_CLEAR(state->PySSLMemoryBIO_Type);
5974 Py_CLEAR(state->PySSLSession_Type);
5975 Py_CLEAR(state->PySSLErrorObject);
5976 Py_CLEAR(state->PySSLCertVerificationErrorObject);
5977 Py_CLEAR(state->PySSLZeroReturnErrorObject);
5978 Py_CLEAR(state->PySSLWantReadErrorObject);
5979 Py_CLEAR(state->PySSLWantWriteErrorObject);
5980 Py_CLEAR(state->PySSLSyscallErrorObject);
5981 Py_CLEAR(state->PySSLEOFErrorObject);
5982 Py_CLEAR(state->err_codes_to_names);
5983 Py_CLEAR(state->err_names_to_codes);
5984 Py_CLEAR(state->lib_codes_to_names);
5985 Py_CLEAR(state->Sock_Type);
5986
5987 return 0;
5988}
5989
5990static void
5991sslmodule_free(void *m)
5992{
5993 sslmodule_clear((PyObject *)m);
5994}
5995
5996static struct PyModuleDef _sslmodule_def = {
Christian Heimes5c36da72020-11-20 09:40:12 +01005997 PyModuleDef_HEAD_INIT,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005998 .m_name = "_ssl",
5999 .m_doc = module_doc,
6000 .m_size = sizeof(_sslmodulestate),
6001 .m_methods = PySSL_methods,
6002 .m_slots = sslmodule_slots,
6003 .m_traverse = sslmodule_traverse,
6004 .m_clear = sslmodule_clear,
6005 .m_free = sslmodule_free
Christian Heimes5c36da72020-11-20 09:40:12 +01006006};
6007
6008PyMODINIT_FUNC
6009PyInit__ssl(void)
6010{
Christian Heimes7f1305e2021-04-17 20:06:38 +02006011 return PyModuleDef_Init(&_sslmodule_def);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006012}