blob: 934c59e26d2d4559016870df23f557c396f27f66 [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 Heimes2875c602021-04-19 07:27:10 +0200685static int
686_ssl_deprecated(const char* name, int stacklevel) {
687 return PyErr_WarnFormat(
688 PyExc_DeprecationWarning, stacklevel,
689 "ssl module: %s is deprecated", name
690 );
691}
692
693#define PY_SSL_DEPRECATED(name, stacklevel, ret) \
694 if (_ssl_deprecated((name), (stacklevel)) == -1) return (ret)
695
Christian Heimes61d478c2018-01-27 15:51:38 +0100696/*
697 * SSL objects
698 */
699
700static int
701_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
702{
703 int retval = -1;
704 ASN1_OCTET_STRING *ip;
705 PyObject *hostname;
706 size_t len;
707
708 assert(server_hostname);
709
710 /* Disable OpenSSL's special mode with leading dot in hostname:
711 * When name starts with a dot (e.g ".example.com"), it will be
712 * matched by a certificate valid for any sub-domain of name.
713 */
714 len = strlen(server_hostname);
715 if (len == 0 || *server_hostname == '.') {
716 PyErr_SetString(
717 PyExc_ValueError,
718 "server_hostname cannot be an empty string or start with a "
719 "leading dot.");
720 return retval;
721 }
722
723 /* inet_pton is not available on all platforms. */
724 ip = a2i_IPADDRESS(server_hostname);
725 if (ip == NULL) {
726 ERR_clear_error();
727 }
728
Christian Heimes11a14932018-02-24 02:35:08 +0100729 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100730 if (hostname == NULL) {
731 goto error;
732 }
733 self->server_hostname = hostname;
734
735 /* Only send SNI extension for non-IP hostnames */
736 if (ip == NULL) {
737 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200738 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzc32f2972020-10-25 12:02:30 -0600739 goto error;
Christian Heimes61d478c2018-01-27 15:51:38 +0100740 }
741 }
742 if (self->ctx->check_hostname) {
743 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
744 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200745 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
746 strlen(server_hostname))) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200747 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes61d478c2018-01-27 15:51:38 +0100748 goto error;
749 }
750 } else {
Christian Heimesa871f692020-06-01 08:58:14 +0200751 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
Christian Heimes61d478c2018-01-27 15:51:38 +0100752 ASN1_STRING_length(ip))) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200753 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes61d478c2018-01-27 15:51:38 +0100754 goto error;
755 }
756 }
757 }
758 retval = 0;
759 error:
760 if (ip != NULL) {
761 ASN1_OCTET_STRING_free(ip);
762 }
763 return retval;
764}
765
Antoine Pitrou152efa22010-05-16 18:19:27 +0000766static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100767newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000768 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200769 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100770 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200771 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000772{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000773 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100774 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700775 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000776
Christian Heimes7f1305e2021-04-17 20:06:38 +0200777 self = PyObject_New(PySSLSocket, get_state_ctx(sslctx)->PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000778 if (self == NULL)
779 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000780
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000781 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000782 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100783 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700784 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200785 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200786 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700787 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700788 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200789 self->exc_type = NULL;
790 self->exc_value = NULL;
791 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200792
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000793 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000795
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000797 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000798 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700799 if (self->ssl == NULL) {
800 Py_DECREF(self);
Christian Heimes7f1305e2021-04-17 20:06:38 +0200801 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytz4c49da02018-12-07 03:11:30 -0700802 return NULL;
803 }
Christian Heimesb467d9a2021-04-17 10:07:19 +0200804 /* bpo43522 and OpenSSL < 1.1.1l: copy hostflags manually */
805#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION < 0x101010cf
806 X509_VERIFY_PARAM *ssl_params = SSL_get0_param(self->ssl);
807 X509_VERIFY_PARAM_set_hostflags(ssl_params, sslctx->hostflags);
808#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200809 SSL_set_app_data(self->ssl, self);
810 if (sock) {
811 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
812 } else {
813 /* BIOs are reference counted and SSL_set_bio borrows our reference.
814 * To prevent a double free in memory_bio_dealloc() we need to take an
815 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200816 BIO_up_ref(inbio->bio);
817 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200818 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
819 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400820 SSL_set_mode(self->ssl,
821 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000822
Christian Heimesf0f59302019-07-01 08:29:17 +0200823#ifdef TLS1_3_VERSION
824 if (sslctx->post_handshake_auth == 1) {
825 if (socket_type == PY_SSL_SERVER) {
826 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
827 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
828 * only in combination with SSL_VERIFY_PEER flag. */
829 int mode = SSL_get_verify_mode(self->ssl);
830 if (mode & SSL_VERIFY_PEER) {
831 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
832 verify_cb = SSL_get_verify_callback(self->ssl);
833 mode |= SSL_VERIFY_POST_HANDSHAKE;
834 SSL_set_verify(self->ssl, mode, verify_cb);
835 }
836 } else {
837 /* client socket */
838 SSL_set_post_handshake_auth(self->ssl, 1);
839 }
840 }
841#endif
842
Christian Heimes61d478c2018-01-27 15:51:38 +0100843 if (server_hostname != NULL) {
844 if (_ssl_configure_hostname(self, server_hostname) < 0) {
845 Py_DECREF(self);
846 return NULL;
847 }
848 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000849 /* If the socket is in non-blocking mode or timeout mode, set the BIO
850 * to non-blocking mode (blocking is the default)
851 */
Victor Stinnere2452312015-03-28 03:00:46 +0100852 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000853 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
854 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
855 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000856
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000857 PySSL_BEGIN_ALLOW_THREADS
858 if (socket_type == PY_SSL_CLIENT)
859 SSL_set_connect_state(self->ssl);
860 else
861 SSL_set_accept_state(self->ssl);
862 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000863
Antoine Pitroud6494802011-07-21 01:11:30 +0200864 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200865 if (sock != NULL) {
866 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
867 if (self->Socket == NULL) {
868 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200869 return NULL;
870 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100871 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100872 if (owner && owner != Py_None) {
873 if (PySSL_set_owner(self, owner, NULL) == -1) {
874 Py_DECREF(self);
875 return NULL;
876 }
877 }
878 if (session && session != Py_None) {
879 if (PySSL_set_session(self, session, NULL) == -1) {
880 Py_DECREF(self);
881 return NULL;
882 }
883 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000884 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000885}
886
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000887/* SSL object methods */
888
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300889/*[clinic input]
890_ssl._SSLSocket.do_handshake
891[clinic start generated code]*/
892
893static PyObject *
894_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
895/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000896{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000897 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700898 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000899 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200900 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200901 _PyTime_t timeout, deadline = 0;
902 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000903
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200904 if (sock) {
905 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200906 _setSSLError(get_state_sock(self),
907 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200908 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
909 return NULL;
910 }
911 Py_INCREF(sock);
912
913 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100914 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200915 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
916 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000917 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000918
Victor Stinner14690702015-04-06 22:46:13 +0200919 timeout = GET_SOCKET_TIMEOUT(sock);
920 has_timeout = (timeout > 0);
921 if (has_timeout)
922 deadline = _PyTime_GetMonotonicClock() + timeout;
923
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000924 /* Actually negotiate SSL connection */
925 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000926 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000927 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000928 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700929 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700931 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200932
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000933 if (PyErr_CheckSignals())
934 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200935
Victor Stinner14690702015-04-06 22:46:13 +0200936 if (has_timeout)
937 timeout = deadline - _PyTime_GetMonotonicClock();
938
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700939 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200940 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700941 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200942 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 } else {
944 sockstate = SOCKET_OPERATION_OK;
945 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200946
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000947 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +0100948 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000949 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000950 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000951 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200952 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000953 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000954 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200956 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000957 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000958 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
960 break;
961 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700962 } while (err.ssl == SSL_ERROR_WANT_READ ||
963 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200964 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000965 if (ret < 1)
966 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +0200967 if (PySSL_ChainExceptions(self) < 0)
968 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200969 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000970error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200971 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +0200972 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000973 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000974}
975
Thomas Woutersed03b412007-08-28 21:37:11 +0000976static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +0200977_asn1obj2py(_sslmodulestate *state, const ASN1_OBJECT *name, int no_name)
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300978{
979 char buf[X509_NAME_MAXLEN];
980 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000981 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300982 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000983
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300984 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000985 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200986 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300987 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000988 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300989 /* initial buffer is too small for oid + terminating null byte */
990 if (buflen > X509_NAME_MAXLEN - 1) {
991 /* make OBJ_obj2txt() calculate the required buflen */
992 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
993 /* allocate len + 1 for terminating NULL byte */
994 namebuf = PyMem_Malloc(buflen + 1);
995 if (namebuf == NULL) {
996 PyErr_NoMemory();
997 return NULL;
998 }
999 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1000 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001001 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001002 goto done;
1003 }
1004 }
1005 if (!buflen && no_name) {
1006 Py_INCREF(Py_None);
1007 name_obj = Py_None;
1008 }
1009 else {
1010 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1011 }
1012
1013 done:
1014 if (buf != namebuf) {
1015 PyMem_Free(namebuf);
1016 }
1017 return name_obj;
1018}
1019
1020static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001021_create_tuple_for_attribute(_sslmodulestate *state,
1022 ASN1_OBJECT *name, ASN1_STRING *value)
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001023{
1024 Py_ssize_t buflen;
1025 unsigned char *valuebuf = NULL;
1026 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001027
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001028 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1029 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001030 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001031 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001032 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02001033 attr = Py_BuildValue("Ns#", _asn1obj2py(state, name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001034 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001035 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001036}
1037
1038static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001039_create_tuple_for_X509_NAME (_sslmodulestate *state, X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001040{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001041 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1042 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1043 PyObject *rdnt;
1044 PyObject *attr = NULL; /* tuple to hold an attribute */
1045 int entry_count = X509_NAME_entry_count(xname);
1046 X509_NAME_ENTRY *entry;
1047 ASN1_OBJECT *name;
1048 ASN1_STRING *value;
1049 int index_counter;
1050 int rdn_level = -1;
1051 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001052
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001053 dn = PyList_New(0);
1054 if (dn == NULL)
1055 return NULL;
1056 /* now create another tuple to hold the top-level RDN */
1057 rdn = PyList_New(0);
1058 if (rdn == NULL)
1059 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001060
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001061 for (index_counter = 0;
1062 index_counter < entry_count;
1063 index_counter++)
1064 {
1065 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001066
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001067 /* check to see if we've gotten to a new RDN */
1068 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001069 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001070 /* yes, new RDN */
1071 /* add old RDN to DN */
1072 rdnt = PyList_AsTuple(rdn);
1073 Py_DECREF(rdn);
1074 if (rdnt == NULL)
1075 goto fail0;
1076 retcode = PyList_Append(dn, rdnt);
1077 Py_DECREF(rdnt);
1078 if (retcode < 0)
1079 goto fail0;
1080 /* create new RDN */
1081 rdn = PyList_New(0);
1082 if (rdn == NULL)
1083 goto fail0;
1084 }
1085 }
Christian Heimes598894f2016-09-05 23:19:05 +02001086 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001087
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001088 /* now add this attribute to the current RDN */
1089 name = X509_NAME_ENTRY_get_object(entry);
1090 value = X509_NAME_ENTRY_get_data(entry);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001091 attr = _create_tuple_for_attribute(state, name, value);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001092 /*
1093 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1094 entry->set,
1095 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1096 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1097 */
1098 if (attr == NULL)
1099 goto fail1;
1100 retcode = PyList_Append(rdn, attr);
1101 Py_DECREF(attr);
1102 if (retcode < 0)
1103 goto fail1;
1104 }
1105 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001106 if (rdn != NULL) {
1107 if (PyList_GET_SIZE(rdn) > 0) {
1108 rdnt = PyList_AsTuple(rdn);
1109 Py_DECREF(rdn);
1110 if (rdnt == NULL)
1111 goto fail0;
1112 retcode = PyList_Append(dn, rdnt);
1113 Py_DECREF(rdnt);
1114 if (retcode < 0)
1115 goto fail0;
1116 }
1117 else {
1118 Py_DECREF(rdn);
1119 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001121
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001122 /* convert list to tuple */
1123 rdnt = PyList_AsTuple(dn);
1124 Py_DECREF(dn);
1125 if (rdnt == NULL)
1126 return NULL;
1127 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001128
1129 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001130 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001131
1132 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001133 Py_XDECREF(dn);
1134 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001135}
1136
1137static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001138_get_peer_alt_names (_sslmodulestate *state, X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001139
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 /* this code follows the procedure outlined in
1141 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1142 function to extract the STACK_OF(GENERAL_NAME),
1143 then iterates through the stack to add the
1144 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001145
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001146 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001148 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001149 GENERAL_NAMES *names = NULL;
1150 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001151 BIO *biobuf = NULL;
1152 char buf[2048];
1153 char *vptr;
1154 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001155
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001156 if (certificate == NULL)
1157 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001158
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001159 /* get a memory buffer */
1160 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001161 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001162 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001163 return NULL;
1164 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001165
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001166 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1167 certificate, NID_subject_alt_name, NULL, NULL);
1168 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001169 if (peer_alt_names == Py_None) {
1170 peer_alt_names = PyList_New(0);
1171 if (peer_alt_names == NULL)
1172 goto fail;
1173 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001174
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001175 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001176 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001177 int gntype;
1178 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001179
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001180 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001181 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001182 switch (gntype) {
1183 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001184 /* we special-case DirName as a tuple of
1185 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001186
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001187 t = PyTuple_New(2);
1188 if (t == NULL) {
1189 goto fail;
1190 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001191
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001192 v = PyUnicode_FromString("DirName");
1193 if (v == NULL) {
1194 Py_DECREF(t);
1195 goto fail;
1196 }
1197 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001198
Christian Heimes7f1305e2021-04-17 20:06:38 +02001199 v = _create_tuple_for_X509_NAME(state, name->d.dirn);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001200 if (v == NULL) {
1201 Py_DECREF(t);
1202 goto fail;
1203 }
1204 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001205 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001206
Christian Heimes824f7f32013-08-17 00:54:47 +02001207 case GEN_EMAIL:
1208 case GEN_DNS:
1209 case GEN_URI:
1210 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1211 correctly, CVE-2013-4238 */
1212 t = PyTuple_New(2);
1213 if (t == NULL)
1214 goto fail;
1215 switch (gntype) {
1216 case GEN_EMAIL:
1217 v = PyUnicode_FromString("email");
1218 as = name->d.rfc822Name;
1219 break;
1220 case GEN_DNS:
1221 v = PyUnicode_FromString("DNS");
1222 as = name->d.dNSName;
1223 break;
1224 case GEN_URI:
1225 v = PyUnicode_FromString("URI");
1226 as = name->d.uniformResourceIdentifier;
1227 break;
1228 }
1229 if (v == NULL) {
1230 Py_DECREF(t);
1231 goto fail;
1232 }
1233 PyTuple_SET_ITEM(t, 0, v);
Christian Heimesa871f692020-06-01 08:58:14 +02001234 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
Christian Heimes824f7f32013-08-17 00:54:47 +02001235 ASN1_STRING_length(as));
1236 if (v == NULL) {
1237 Py_DECREF(t);
1238 goto fail;
1239 }
1240 PyTuple_SET_ITEM(t, 1, v);
1241 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001242
Christian Heimes1c03abd2016-09-06 23:25:35 +02001243 case GEN_RID:
1244 t = PyTuple_New(2);
1245 if (t == NULL)
1246 goto fail;
1247
1248 v = PyUnicode_FromString("Registered ID");
1249 if (v == NULL) {
1250 Py_DECREF(t);
1251 goto fail;
1252 }
1253 PyTuple_SET_ITEM(t, 0, v);
1254
1255 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1256 if (len < 0) {
1257 Py_DECREF(t);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001258 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes1c03abd2016-09-06 23:25:35 +02001259 goto fail;
1260 } else if (len >= (int)sizeof(buf)) {
1261 v = PyUnicode_FromString("<INVALID>");
1262 } else {
1263 v = PyUnicode_FromStringAndSize(buf, len);
1264 }
1265 if (v == NULL) {
1266 Py_DECREF(t);
1267 goto fail;
1268 }
1269 PyTuple_SET_ITEM(t, 1, v);
1270 break;
1271
Christian Heimes2b7de662019-12-07 17:59:36 +01001272 case GEN_IPADD:
1273 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1274 * the trailing newline. Remove it in all versions
1275 */
1276 t = PyTuple_New(2);
1277 if (t == NULL)
1278 goto fail;
1279
1280 v = PyUnicode_FromString("IP Address");
1281 if (v == NULL) {
1282 Py_DECREF(t);
1283 goto fail;
1284 }
1285 PyTuple_SET_ITEM(t, 0, v);
1286
1287 if (name->d.ip->length == 4) {
1288 unsigned char *p = name->d.ip->data;
1289 v = PyUnicode_FromFormat(
1290 "%d.%d.%d.%d",
1291 p[0], p[1], p[2], p[3]
1292 );
1293 } else if (name->d.ip->length == 16) {
1294 /* PyUnicode_FromFormat() does not support %X */
1295 unsigned char *p = name->d.ip->data;
1296 len = sprintf(
1297 buf,
1298 "%X:%X:%X:%X:%X:%X:%X:%X",
1299 p[0] << 8 | p[1],
1300 p[2] << 8 | p[3],
1301 p[4] << 8 | p[5],
1302 p[6] << 8 | p[7],
1303 p[8] << 8 | p[9],
1304 p[10] << 8 | p[11],
1305 p[12] << 8 | p[13],
1306 p[14] << 8 | p[15]
1307 );
1308 v = PyUnicode_FromStringAndSize(buf, len);
1309 } else {
1310 v = PyUnicode_FromString("<invalid>");
1311 }
1312
1313 if (v == NULL) {
1314 Py_DECREF(t);
1315 goto fail;
1316 }
1317 PyTuple_SET_ITEM(t, 1, v);
1318 break;
1319
Christian Heimes824f7f32013-08-17 00:54:47 +02001320 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001321 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001322 switch (gntype) {
1323 /* check for new general name type */
1324 case GEN_OTHERNAME:
1325 case GEN_X400:
1326 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001327 case GEN_RID:
1328 break;
1329 default:
1330 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1331 "Unknown general name type %d",
1332 gntype) == -1) {
1333 goto fail;
1334 }
1335 break;
1336 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001337 (void) BIO_reset(biobuf);
1338 GENERAL_NAME_print(biobuf, name);
1339 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1340 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001341 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001342 goto fail;
1343 }
1344 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001345 if (vptr == NULL) {
1346 PyErr_Format(PyExc_ValueError,
1347 "Invalid value %.200s",
1348 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001349 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001350 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001351 t = PyTuple_New(2);
1352 if (t == NULL)
1353 goto fail;
1354 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1355 if (v == NULL) {
1356 Py_DECREF(t);
1357 goto fail;
1358 }
1359 PyTuple_SET_ITEM(t, 0, v);
1360 v = PyUnicode_FromStringAndSize((vptr + 1),
1361 (len - (vptr - buf + 1)));
1362 if (v == NULL) {
1363 Py_DECREF(t);
1364 goto fail;
1365 }
1366 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001367 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001369
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001371
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001372 if (PyList_Append(peer_alt_names, t) < 0) {
1373 Py_DECREF(t);
1374 goto fail;
1375 }
1376 Py_DECREF(t);
1377 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001378 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001379 }
1380 BIO_free(biobuf);
1381 if (peer_alt_names != Py_None) {
1382 v = PyList_AsTuple(peer_alt_names);
1383 Py_DECREF(peer_alt_names);
1384 return v;
1385 } else {
1386 return peer_alt_names;
1387 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001388
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001389
1390 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001391 if (biobuf != NULL)
1392 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001393
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001394 if (peer_alt_names != Py_None) {
1395 Py_XDECREF(peer_alt_names);
1396 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001397
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001398 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001399}
1400
1401static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001402_get_aia_uri(X509 *certificate, int nid) {
1403 PyObject *lst = NULL, *ostr = NULL;
1404 int i, result;
1405 AUTHORITY_INFO_ACCESS *info;
1406
1407 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001408 if (info == NULL)
1409 return Py_None;
1410 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1411 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001412 return Py_None;
1413 }
1414
1415 if ((lst = PyList_New(0)) == NULL) {
1416 goto fail;
1417 }
1418
1419 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1420 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1421 ASN1_IA5STRING *uri;
1422
1423 if ((OBJ_obj2nid(ad->method) != nid) ||
1424 (ad->location->type != GEN_URI)) {
1425 continue;
1426 }
1427 uri = ad->location->d.uniformResourceIdentifier;
1428 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1429 uri->length);
1430 if (ostr == NULL) {
1431 goto fail;
1432 }
1433 result = PyList_Append(lst, ostr);
1434 Py_DECREF(ostr);
1435 if (result < 0) {
1436 goto fail;
1437 }
1438 }
1439 AUTHORITY_INFO_ACCESS_free(info);
1440
1441 /* convert to tuple or None */
1442 if (PyList_Size(lst) == 0) {
1443 Py_DECREF(lst);
1444 return Py_None;
1445 } else {
1446 PyObject *tup;
1447 tup = PyList_AsTuple(lst);
1448 Py_DECREF(lst);
1449 return tup;
1450 }
1451
1452 fail:
1453 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001454 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001455 return NULL;
1456}
1457
1458static PyObject *
1459_get_crl_dp(X509 *certificate) {
1460 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001461 int i, j;
1462 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001463
Christian Heimes598894f2016-09-05 23:19:05 +02001464 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001465
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001466 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001467 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001468
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001469 lst = PyList_New(0);
1470 if (lst == NULL)
1471 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001472
1473 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1474 DIST_POINT *dp;
1475 STACK_OF(GENERAL_NAME) *gns;
1476
1477 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001478 if (dp->distpoint == NULL) {
1479 /* Ignore empty DP value, CVE-2019-5010 */
1480 continue;
1481 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001482 gns = dp->distpoint->name.fullname;
1483
1484 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1485 GENERAL_NAME *gn;
1486 ASN1_IA5STRING *uri;
1487 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001488 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001489
1490 gn = sk_GENERAL_NAME_value(gns, j);
1491 if (gn->type != GEN_URI) {
1492 continue;
1493 }
1494 uri = gn->d.uniformResourceIdentifier;
1495 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1496 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001497 if (ouri == NULL)
1498 goto done;
1499
1500 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001501 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001502 if (err < 0)
1503 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001504 }
1505 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001506
1507 /* Convert to tuple. */
1508 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1509
1510 done:
1511 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001512 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001513 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001514}
1515
1516static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001517_decode_certificate(_sslmodulestate *state, X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001518
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001519 PyObject *retval = NULL;
1520 BIO *biobuf = NULL;
1521 PyObject *peer;
1522 PyObject *peer_alt_names = NULL;
1523 PyObject *issuer;
1524 PyObject *version;
1525 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001526 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001527 ASN1_INTEGER *serialNumber;
1528 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001529 int len, result;
Christian Heimesa871f692020-06-01 08:58:14 +02001530 const ASN1_TIME *notBefore, *notAfter;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001531 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001532
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001533 retval = PyDict_New();
1534 if (retval == NULL)
1535 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001536
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001537 peer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001538 state,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001539 X509_get_subject_name(certificate));
1540 if (peer == NULL)
1541 goto fail0;
1542 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1543 Py_DECREF(peer);
1544 goto fail0;
1545 }
1546 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001547
Antoine Pitroufb046912010-11-09 20:21:19 +00001548 issuer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001549 state,
Antoine Pitroufb046912010-11-09 20:21:19 +00001550 X509_get_issuer_name(certificate));
1551 if (issuer == NULL)
1552 goto fail0;
1553 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001554 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001555 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001556 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001557 Py_DECREF(issuer);
1558
1559 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001560 if (version == NULL)
1561 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001562 if (PyDict_SetItemString(retval, "version", version) < 0) {
1563 Py_DECREF(version);
1564 goto fail0;
1565 }
1566 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568 /* get a memory buffer */
1569 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001570 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001571 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001572 goto fail0;
1573 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001574
Antoine Pitroufb046912010-11-09 20:21:19 +00001575 (void) BIO_reset(biobuf);
1576 serialNumber = X509_get_serialNumber(certificate);
1577 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1578 i2a_ASN1_INTEGER(biobuf, serialNumber);
1579 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1580 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001581 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001582 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001583 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001584 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1585 if (sn_obj == NULL)
1586 goto fail1;
1587 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1588 Py_DECREF(sn_obj);
1589 goto fail1;
1590 }
1591 Py_DECREF(sn_obj);
1592
1593 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001594 notBefore = X509_get0_notBefore(certificate);
Antoine Pitroufb046912010-11-09 20:21:19 +00001595 ASN1_TIME_print(biobuf, notBefore);
1596 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1597 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001598 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001599 goto fail1;
1600 }
1601 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1602 if (pnotBefore == NULL)
1603 goto fail1;
1604 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1605 Py_DECREF(pnotBefore);
1606 goto fail1;
1607 }
1608 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001609
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001610 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001611 notAfter = X509_get0_notAfter(certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001612 ASN1_TIME_print(biobuf, notAfter);
1613 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1614 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001615 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001616 goto fail1;
1617 }
1618 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1619 if (pnotAfter == NULL)
1620 goto fail1;
1621 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1622 Py_DECREF(pnotAfter);
1623 goto fail1;
1624 }
1625 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001627 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001628
Christian Heimes7f1305e2021-04-17 20:06:38 +02001629 peer_alt_names = _get_peer_alt_names(state, certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001630 if (peer_alt_names == NULL)
1631 goto fail1;
1632 else if (peer_alt_names != Py_None) {
1633 if (PyDict_SetItemString(retval, "subjectAltName",
1634 peer_alt_names) < 0) {
1635 Py_DECREF(peer_alt_names);
1636 goto fail1;
1637 }
1638 Py_DECREF(peer_alt_names);
1639 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001640
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001641 /* Authority Information Access: OCSP URIs */
1642 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1643 if (obj == NULL) {
1644 goto fail1;
1645 } else if (obj != Py_None) {
1646 result = PyDict_SetItemString(retval, "OCSP", obj);
1647 Py_DECREF(obj);
1648 if (result < 0) {
1649 goto fail1;
1650 }
1651 }
1652
1653 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1654 if (obj == NULL) {
1655 goto fail1;
1656 } else if (obj != Py_None) {
1657 result = PyDict_SetItemString(retval, "caIssuers", obj);
1658 Py_DECREF(obj);
1659 if (result < 0) {
1660 goto fail1;
1661 }
1662 }
1663
1664 /* CDP (CRL distribution points) */
1665 obj = _get_crl_dp(certificate);
1666 if (obj == NULL) {
1667 goto fail1;
1668 } else if (obj != Py_None) {
1669 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1670 Py_DECREF(obj);
1671 if (result < 0) {
1672 goto fail1;
1673 }
1674 }
1675
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001676 BIO_free(biobuf);
1677 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001678
1679 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001680 if (biobuf != NULL)
1681 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001682 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001683 Py_XDECREF(retval);
1684 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001685}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001686
Christian Heimes9a5395a2013-06-17 15:44:12 +02001687static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001688_certificate_to_der(_sslmodulestate *state, X509 *certificate)
Christian Heimes9a5395a2013-06-17 15:44:12 +02001689{
1690 unsigned char *bytes_buf = NULL;
1691 int len;
1692 PyObject *retval;
1693
1694 bytes_buf = NULL;
1695 len = i2d_X509(certificate, &bytes_buf);
1696 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001697 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes9a5395a2013-06-17 15:44:12 +02001698 return NULL;
1699 }
1700 /* this is actually an immutable bytes sequence */
1701 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1702 OPENSSL_free(bytes_buf);
1703 return retval;
1704}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001705
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001706/*[clinic input]
1707_ssl._test_decode_cert
1708 path: object(converter="PyUnicode_FSConverter")
1709 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001710
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001711[clinic start generated code]*/
1712
1713static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001714_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1715/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001716{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001717 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001718 X509 *x=NULL;
1719 BIO *cert;
Christian Heimes7f1305e2021-04-17 20:06:38 +02001720 _sslmodulestate *state = get_ssl_state(module);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001721
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001722 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001723 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001724 "Can't malloc memory to read file");
1725 goto fail0;
1726 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001727
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001728 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001729 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001730 "Can't open file");
1731 goto fail0;
1732 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001733
Alex Gaynor40dad952019-08-15 08:31:28 -04001734 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001735 if (x == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001736 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 "Error decoding PEM-encoded file");
1738 goto fail0;
1739 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001740
Christian Heimes7f1305e2021-04-17 20:06:38 +02001741 retval = _decode_certificate(state, x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001742 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001743
1744 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001745 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001746 if (cert != NULL) BIO_free(cert);
1747 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001748}
1749
1750
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001751/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001752_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001753 der as binary_mode: bool = False
1754 /
1755
1756Returns the certificate for the peer.
1757
1758If no certificate was provided, returns None. If a certificate was
1759provided, but not validated, returns an empty dictionary. Otherwise
1760returns a dict containing information about the peer certificate.
1761
1762If the optional argument is True, returns a DER-encoded copy of the
1763peer certificate, or None if no certificate was provided. This will
1764return the certificate even if it wasn't validated.
1765[clinic start generated code]*/
1766
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001767static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001768_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1769/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001770{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001771 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001772 X509 *peer_cert;
1773 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001774
Christian Heimes66dc33b2017-05-23 16:02:02 -07001775 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001776 PyErr_SetString(PyExc_ValueError,
1777 "handshake not done yet");
1778 return NULL;
1779 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001780 peer_cert = SSL_get_peer_certificate(self->ssl);
1781 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001782 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001783
Antoine Pitrou721738f2012-08-15 23:20:39 +02001784 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001785 /* return cert in DER-encoded format */
Christian Heimes7f1305e2021-04-17 20:06:38 +02001786 result = _certificate_to_der(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001787 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001788 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001789 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001790 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001791 else
Christian Heimes7f1305e2021-04-17 20:06:38 +02001792 result = _decode_certificate(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001793 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001794 X509_free(peer_cert);
1795 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001796}
1797
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001798static PyObject *
1799cipher_to_tuple(const SSL_CIPHER *cipher)
1800{
1801 const char *cipher_name, *cipher_protocol;
1802 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001803 if (retval == NULL)
1804 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001805
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001806 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001807 if (cipher_name == 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, 0, Py_None);
1810 } else {
1811 v = PyUnicode_FromString(cipher_name);
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, 0, v);
1815 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001816
1817 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001818 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001819 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001820 PyTuple_SET_ITEM(retval, 1, Py_None);
1821 } else {
1822 v = PyUnicode_FromString(cipher_protocol);
1823 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001824 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 PyTuple_SET_ITEM(retval, 1, v);
1826 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001827
1828 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001829 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001830 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001831 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001832
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001833 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001834
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001835 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001836 Py_DECREF(retval);
1837 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001838}
1839
Christian Heimes25bfcd52016-09-06 00:04:45 +02001840static PyObject *
1841cipher_to_dict(const SSL_CIPHER *cipher)
1842{
1843 const char *cipher_name, *cipher_protocol;
1844
1845 unsigned long cipher_id;
1846 int alg_bits, strength_bits, len;
1847 char buf[512] = {0};
Christian Heimes25bfcd52016-09-06 00:04:45 +02001848 int aead, nid;
1849 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001850
1851 /* can be NULL */
1852 cipher_name = SSL_CIPHER_get_name(cipher);
1853 cipher_protocol = SSL_CIPHER_get_version(cipher);
1854 cipher_id = SSL_CIPHER_get_id(cipher);
1855 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001856 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1857 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001858 if (len > 1 && buf[len-1] == '\n')
1859 buf[len-1] = '\0';
1860 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1861
Christian Heimes25bfcd52016-09-06 00:04:45 +02001862 aead = SSL_CIPHER_is_aead(cipher);
1863 nid = SSL_CIPHER_get_cipher_nid(cipher);
1864 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1865 nid = SSL_CIPHER_get_digest_nid(cipher);
1866 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1867 nid = SSL_CIPHER_get_kx_nid(cipher);
1868 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1869 nid = SSL_CIPHER_get_auth_nid(cipher);
1870 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001871
Victor Stinner410b9882016-09-12 12:00:23 +02001872 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001873 "{sksssssssisi"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001874 "sOssssssss"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001875 "}",
1876 "id", cipher_id,
1877 "name", cipher_name,
1878 "protocol", cipher_protocol,
1879 "description", buf,
1880 "strength_bits", strength_bits,
1881 "alg_bits", alg_bits
Christian Heimes25bfcd52016-09-06 00:04:45 +02001882 ,"aead", aead ? Py_True : Py_False,
1883 "symmetric", skcipher,
1884 "digest", digest,
1885 "kea", kx,
1886 "auth", auth
Christian Heimes25bfcd52016-09-06 00:04:45 +02001887 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001888}
Christian Heimes25bfcd52016-09-06 00:04:45 +02001889
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001890/*[clinic input]
1891_ssl._SSLSocket.shared_ciphers
1892[clinic start generated code]*/
1893
1894static PyObject *
1895_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1896/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001897{
1898 STACK_OF(SSL_CIPHER) *ciphers;
1899 int i;
1900 PyObject *res;
1901
Christian Heimes598894f2016-09-05 23:19:05 +02001902 ciphers = SSL_get_ciphers(self->ssl);
1903 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001904 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001905 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1906 if (!res)
1907 return NULL;
1908 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1909 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1910 if (!tup) {
1911 Py_DECREF(res);
1912 return NULL;
1913 }
1914 PyList_SET_ITEM(res, i, tup);
1915 }
1916 return res;
1917}
1918
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001919/*[clinic input]
1920_ssl._SSLSocket.cipher
1921[clinic start generated code]*/
1922
1923static PyObject *
1924_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1925/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001926{
1927 const SSL_CIPHER *current;
1928
1929 if (self->ssl == NULL)
1930 Py_RETURN_NONE;
1931 current = SSL_get_current_cipher(self->ssl);
1932 if (current == NULL)
1933 Py_RETURN_NONE;
1934 return cipher_to_tuple(current);
1935}
1936
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001937/*[clinic input]
1938_ssl._SSLSocket.version
1939[clinic start generated code]*/
1940
1941static PyObject *
1942_ssl__SSLSocket_version_impl(PySSLSocket *self)
1943/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001944{
1945 const char *version;
1946
1947 if (self->ssl == NULL)
1948 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001949 if (!SSL_is_init_finished(self->ssl)) {
1950 /* handshake not finished */
1951 Py_RETURN_NONE;
1952 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001953 version = SSL_get_version(self->ssl);
1954 if (!strcmp(version, "unknown"))
1955 Py_RETURN_NONE;
1956 return PyUnicode_FromString(version);
1957}
1958
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001959/*[clinic input]
1960_ssl._SSLSocket.selected_alpn_protocol
1961[clinic start generated code]*/
1962
1963static PyObject *
1964_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1965/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1966{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001967 const unsigned char *out;
1968 unsigned int outlen;
1969
1970 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1971
1972 if (out == NULL)
1973 Py_RETURN_NONE;
1974 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001975}
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001976
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001977/*[clinic input]
1978_ssl._SSLSocket.compression
1979[clinic start generated code]*/
1980
1981static PyObject *
1982_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1983/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1984{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001985#ifdef OPENSSL_NO_COMP
1986 Py_RETURN_NONE;
1987#else
1988 const COMP_METHOD *comp_method;
1989 const char *short_name;
1990
1991 if (self->ssl == NULL)
1992 Py_RETURN_NONE;
1993 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001994 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001995 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001996 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001997 if (short_name == NULL)
1998 Py_RETURN_NONE;
1999 return PyUnicode_DecodeFSDefault(short_name);
2000#endif
2001}
2002
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002003static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2004 Py_INCREF(self->ctx);
2005 return self->ctx;
2006}
2007
2008static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2009 void *closure) {
2010
Christian Heimes7f1305e2021-04-17 20:06:38 +02002011 if (PyObject_TypeCheck(value, self->ctx->state->PySSLContext_Type)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002012 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002013 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002014 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Christian Heimes77cde502021-03-21 16:13:09 +01002015 /* Set SSL* internal msg_callback to state of new context's state */
2016 SSL_set_msg_callback(
2017 self->ssl,
2018 self->ctx->msg_cb ? _PySSL_msg_callback : NULL
2019 );
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002020 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002021 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002022 return -1;
2023 }
2024
2025 return 0;
2026}
2027
2028PyDoc_STRVAR(PySSL_set_context_doc,
2029"_setter_context(ctx)\n\
2030\
2031This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002032used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002033on the SSLContext to change the certificate information associated with the\n\
2034SSLSocket before the cryptographic exchange handshake messages\n");
2035
2036
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002037static PyObject *
2038PySSL_get_server_side(PySSLSocket *self, void *c)
2039{
2040 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2041}
2042
2043PyDoc_STRVAR(PySSL_get_server_side_doc,
2044"Whether this is a server-side socket.");
2045
2046static PyObject *
2047PySSL_get_server_hostname(PySSLSocket *self, void *c)
2048{
2049 if (self->server_hostname == NULL)
2050 Py_RETURN_NONE;
2051 Py_INCREF(self->server_hostname);
2052 return self->server_hostname;
2053}
2054
2055PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2056"The currently set server hostname (for SNI).");
2057
2058static PyObject *
2059PySSL_get_owner(PySSLSocket *self, void *c)
2060{
2061 PyObject *owner;
2062
2063 if (self->owner == NULL)
2064 Py_RETURN_NONE;
2065
2066 owner = PyWeakref_GetObject(self->owner);
2067 Py_INCREF(owner);
2068 return owner;
2069}
2070
2071static int
2072PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2073{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002074 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002075 if (self->owner == NULL)
2076 return -1;
2077 return 0;
2078}
2079
2080PyDoc_STRVAR(PySSL_get_owner_doc,
2081"The Python-level owner of this object.\
2082Passed as \"self\" in servername callback.");
2083
Christian Heimesc7f70692019-05-31 11:44:05 +02002084static int
2085PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2086{
2087 Py_VISIT(self->exc_type);
2088 Py_VISIT(self->exc_value);
2089 Py_VISIT(self->exc_tb);
2090 return 0;
2091}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002092
Christian Heimesc7f70692019-05-31 11:44:05 +02002093static int
2094PySSL_clear(PySSLSocket *self)
2095{
2096 Py_CLEAR(self->exc_type);
2097 Py_CLEAR(self->exc_value);
2098 Py_CLEAR(self->exc_tb);
2099 return 0;
2100}
2101
2102static void
2103PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002104{
Christian Heimes5c36da72020-11-20 09:40:12 +01002105 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002106 if (self->ssl)
2107 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002108 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002109 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002110 Py_XDECREF(self->server_hostname);
2111 Py_XDECREF(self->owner);
Victor Stinner32bd68c2020-12-01 10:37:39 +01002112 PyObject_Free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01002113 Py_DECREF(tp);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002114}
2115
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002116/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002117 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002118 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002119 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002120
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002121static int
Victor Stinner14690702015-04-06 22:46:13 +02002122PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002123{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002124 int rc;
2125#ifdef HAVE_POLL
2126 struct pollfd pollfd;
2127 _PyTime_t ms;
2128#else
2129 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002130 fd_set fds;
2131 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002132#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002133
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002134 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002135 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002136 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002137 else if (timeout < 0) {
2138 if (s->sock_timeout > 0)
2139 return SOCKET_HAS_TIMED_OUT;
2140 else
2141 return SOCKET_IS_BLOCKING;
2142 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002143
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002144 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002145 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002146 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002147
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002148 /* Prefer poll, if available, since you can poll() any fd
2149 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002150#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002151 pollfd.fd = s->sock_fd;
2152 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002153
Victor Stinner14690702015-04-06 22:46:13 +02002154 /* timeout is in seconds, poll() uses milliseconds */
2155 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002156 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002157
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002158 PySSL_BEGIN_ALLOW_THREADS
2159 rc = poll(&pollfd, 1, (int)ms);
2160 PySSL_END_ALLOW_THREADS
2161#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002162 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002163 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002164 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002165
Victor Stinner14690702015-04-06 22:46:13 +02002166 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002167
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002168 FD_ZERO(&fds);
2169 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002170
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002171 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002172 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002173 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002174 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002175 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002176 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002177 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002178 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002179#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002180
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002181 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2182 (when we are able to write or when there's something to read) */
2183 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002184}
2185
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002186/*[clinic input]
2187_ssl._SSLSocket.write
2188 b: Py_buffer
2189 /
2190
2191Writes the bytes-like object b into the SSL object.
2192
2193Returns the number of bytes written.
2194[clinic start generated code]*/
2195
2196static PyObject *
2197_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2198/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002199{
Christian Heimes89d15502021-04-19 06:55:30 +02002200 size_t count = 0;
2201 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002202 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002203 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002204 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002205 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002206 _PyTime_t timeout, deadline = 0;
2207 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002208
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002209 if (sock != NULL) {
2210 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002211 _setSSLError(get_state_sock(self),
2212 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002213 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2214 return NULL;
2215 }
2216 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002217 }
2218
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002219 if (sock != NULL) {
2220 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002221 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002222 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2223 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2224 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002225
Victor Stinner14690702015-04-06 22:46:13 +02002226 timeout = GET_SOCKET_TIMEOUT(sock);
2227 has_timeout = (timeout > 0);
2228 if (has_timeout)
2229 deadline = _PyTime_GetMonotonicClock() + timeout;
2230
2231 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002232 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002233 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002234 "The write operation timed out");
2235 goto error;
2236 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002237 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002238 "Underlying socket has been closed.");
2239 goto error;
2240 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002241 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002242 "Underlying socket too large for select().");
2243 goto error;
2244 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002245
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002246 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002247 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes89d15502021-04-19 06:55:30 +02002248 retval = SSL_write_ex(self->ssl, b->buf, (int)b->len, &count);
2249 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002250 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002251 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002252
2253 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002254 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002255
Victor Stinner14690702015-04-06 22:46:13 +02002256 if (has_timeout)
2257 timeout = deadline - _PyTime_GetMonotonicClock();
2258
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002259 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002260 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002261 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002262 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002263 } else {
2264 sockstate = SOCKET_OPERATION_OK;
2265 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002266
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002267 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002268 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002269 "The write operation timed out");
2270 goto error;
2271 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002272 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002273 "Underlying socket has been closed.");
2274 goto error;
2275 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2276 break;
2277 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002278 } while (err.ssl == SSL_ERROR_WANT_READ ||
2279 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002280
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002281 Py_XDECREF(sock);
Christian Heimes89d15502021-04-19 06:55:30 +02002282 if (retval == 0)
2283 return PySSL_SetError(self, retval, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002284 if (PySSL_ChainExceptions(self) < 0)
2285 return NULL;
Christian Heimes89d15502021-04-19 06:55:30 +02002286 return PyLong_FromSize_t(count);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002287error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002288 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002289 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002290 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002291}
2292
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002293/*[clinic input]
2294_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002295
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002296Returns the number of already decrypted bytes available for read, pending on the connection.
2297[clinic start generated code]*/
2298
2299static PyObject *
2300_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2301/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002302{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002303 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002304 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002305
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002306 PySSL_BEGIN_ALLOW_THREADS
2307 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002308 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002309 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002310 self->err = err;
2311
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002312 if (count < 0)
2313 return PySSL_SetError(self, count, __FILE__, __LINE__);
2314 else
2315 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002316}
2317
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002318/*[clinic input]
2319_ssl._SSLSocket.read
2320 size as len: int
2321 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002322 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002323 ]
2324 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002325
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002326Read up to size bytes from the SSL socket.
2327[clinic start generated code]*/
2328
2329static PyObject *
2330_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2331 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002332/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002333{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002334 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002335 char *mem;
Christian Heimes89d15502021-04-19 06:55:30 +02002336 size_t count = 0;
2337 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002339 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002340 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002341 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002342 _PyTime_t timeout, deadline = 0;
2343 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002344
Martin Panter5503d472016-03-27 05:35:19 +00002345 if (!group_right_1 && len < 0) {
2346 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2347 return NULL;
2348 }
2349
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002350 if (sock != NULL) {
2351 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002352 _setSSLError(get_state_sock(self),
2353 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002354 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2355 return NULL;
2356 }
2357 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002358 }
2359
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002360 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002361 dest = PyBytes_FromStringAndSize(NULL, len);
2362 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002363 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002364 if (len == 0) {
2365 Py_XDECREF(sock);
2366 return dest;
2367 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002368 mem = PyBytes_AS_STRING(dest);
2369 }
2370 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002371 mem = buffer->buf;
2372 if (len <= 0 || len > buffer->len) {
2373 len = (int) buffer->len;
2374 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002375 PyErr_SetString(PyExc_OverflowError,
2376 "maximum length can't fit in a C 'int'");
2377 goto error;
2378 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002379 if (len == 0) {
2380 count = 0;
2381 goto done;
2382 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002383 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002384 }
2385
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002386 if (sock != NULL) {
2387 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002388 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002389 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2390 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2391 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002392
Victor Stinner14690702015-04-06 22:46:13 +02002393 timeout = GET_SOCKET_TIMEOUT(sock);
2394 has_timeout = (timeout > 0);
2395 if (has_timeout)
2396 deadline = _PyTime_GetMonotonicClock() + timeout;
2397
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002398 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002399 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes89d15502021-04-19 06:55:30 +02002400 retval = SSL_read_ex(self->ssl, mem, len, &count);
2401 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002402 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002403 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002404
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002405 if (PyErr_CheckSignals())
2406 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002407
Victor Stinner14690702015-04-06 22:46:13 +02002408 if (has_timeout)
2409 timeout = deadline - _PyTime_GetMonotonicClock();
2410
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002411 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002412 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002413 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002414 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002415 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002416 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002417 {
2418 count = 0;
2419 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002420 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002421 else
2422 sockstate = SOCKET_OPERATION_OK;
2423
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002424 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002425 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002426 "The read operation timed out");
2427 goto error;
2428 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2429 break;
2430 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002431 } while (err.ssl == SSL_ERROR_WANT_READ ||
2432 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002433
Christian Heimes89d15502021-04-19 06:55:30 +02002434 if (retval == 0) {
2435 PySSL_SetError(self, retval, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002436 goto error;
2437 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002438 if (self->exc_type != NULL)
2439 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002440
2441done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002442 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002443 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002444 _PyBytes_Resize(&dest, count);
2445 return dest;
2446 }
2447 else {
Christian Heimes89d15502021-04-19 06:55:30 +02002448 return PyLong_FromSize_t(count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002449 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002450
2451error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002452 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002453 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002454 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002455 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002456 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002457}
2458
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002459/*[clinic input]
2460_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002461
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002462Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002463[clinic start generated code]*/
2464
2465static PyObject *
2466_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002467/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002468{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002469 _PySSLError err;
2470 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002471 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002472 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002473 _PyTime_t timeout, deadline = 0;
2474 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002475
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002476 if (sock != NULL) {
2477 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002478 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002479 _setSSLError(get_state_sock(self),
2480 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002481 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2482 return NULL;
2483 }
2484 Py_INCREF(sock);
2485
2486 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002487 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002488 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2489 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002490 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002491
Victor Stinner14690702015-04-06 22:46:13 +02002492 timeout = GET_SOCKET_TIMEOUT(sock);
2493 has_timeout = (timeout > 0);
2494 if (has_timeout)
2495 deadline = _PyTime_GetMonotonicClock() + timeout;
2496
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002497 while (1) {
2498 PySSL_BEGIN_ALLOW_THREADS
2499 /* Disable read-ahead so that unwrap can work correctly.
2500 * Otherwise OpenSSL might read in too much data,
2501 * eating clear text data that happens to be
2502 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002503 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002504 * function is used and the shutdown_seen_zero != 0
2505 * condition is met.
2506 */
2507 if (self->shutdown_seen_zero)
2508 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002509 ret = SSL_shutdown(self->ssl);
2510 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002511 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002512 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002513
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002514 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002515 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002516 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002517 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002518 /* Don't loop endlessly; instead preserve legacy
2519 behaviour of trying SSL_shutdown() only twice.
2520 This looks necessary for OpenSSL < 0.9.8m */
2521 if (++zeros > 1)
2522 break;
2523 /* Shutdown was sent, now try receiving */
2524 self->shutdown_seen_zero = 1;
2525 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002526 }
2527
Victor Stinner14690702015-04-06 22:46:13 +02002528 if (has_timeout)
2529 timeout = deadline - _PyTime_GetMonotonicClock();
2530
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002531 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002532 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002533 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002534 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002535 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002536 else
2537 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002538
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002539 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002540 if (err.ssl == SSL_ERROR_WANT_READ)
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002541 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002542 "The read operation timed out");
2543 else
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002544 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002545 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002546 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002547 }
2548 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002549 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002550 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002551 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002552 }
2553 else if (sockstate != SOCKET_OPERATION_OK)
2554 /* Retain the SSL error code */
2555 break;
2556 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002557 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002558 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002559 PySSL_SetError(self, ret, __FILE__, __LINE__);
2560 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002561 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002562 if (self->exc_type != NULL)
2563 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002564 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002565 /* It's already INCREF'ed */
2566 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002567 else
2568 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002569
2570error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002571 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002572 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002573 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002574}
2575
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002576/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002577_ssl._SSLSocket.get_channel_binding
2578 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002579
Christian Heimes141c5e82018-02-24 21:10:57 +01002580Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002581
Christian Heimes141c5e82018-02-24 21:10:57 +01002582Raise ValueError if the requested `cb_type` is not supported. Return bytes
2583of the data or None if the data is not available (e.g. before the handshake).
2584Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002585[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002586
Antoine Pitroud6494802011-07-21 01:11:30 +02002587static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002588_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2589 const char *cb_type)
2590/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002591{
Antoine Pitroud6494802011-07-21 01:11:30 +02002592 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002593 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002594
Christian Heimes141c5e82018-02-24 21:10:57 +01002595 if (strcmp(cb_type, "tls-unique") == 0) {
2596 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2597 /* if session is resumed XOR we are the client */
2598 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2599 }
2600 else {
2601 /* if a new session XOR we are the server */
2602 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2603 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002604 }
2605 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002606 PyErr_Format(
2607 PyExc_ValueError,
2608 "'%s' channel binding type not implemented",
2609 cb_type
2610 );
2611 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002612 }
2613
2614 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002615 if (len == 0)
2616 Py_RETURN_NONE;
2617
Christian Heimes141c5e82018-02-24 21:10:57 +01002618 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002619}
2620
Christian Heimes9fb051f2018-09-23 08:32:31 +02002621/*[clinic input]
2622_ssl._SSLSocket.verify_client_post_handshake
2623
2624Initiate TLS 1.3 post-handshake authentication
2625[clinic start generated code]*/
2626
2627static PyObject *
2628_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2629/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2630{
2631#ifdef TLS1_3_VERSION
2632 int err = SSL_verify_client_post_handshake(self->ssl);
2633 if (err == 0)
Christian Heimes7f1305e2021-04-17 20:06:38 +02002634 return _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes9fb051f2018-09-23 08:32:31 +02002635 else
2636 Py_RETURN_NONE;
2637#else
2638 PyErr_SetString(PyExc_NotImplementedError,
2639 "Post-handshake auth is not supported by your "
2640 "OpenSSL version.");
2641 return NULL;
2642#endif
2643}
2644
Christian Heimes99a65702016-09-10 23:44:53 +02002645static SSL_SESSION*
2646_ssl_session_dup(SSL_SESSION *session) {
2647 SSL_SESSION *newsession = NULL;
2648 int slen;
2649 unsigned char *senc = NULL, *p;
2650 const unsigned char *const_p;
2651
2652 if (session == NULL) {
2653 PyErr_SetString(PyExc_ValueError, "Invalid session");
2654 goto error;
2655 }
2656
2657 /* get length */
2658 slen = i2d_SSL_SESSION(session, NULL);
2659 if (slen == 0 || slen > 0xFF00) {
2660 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2661 goto error;
2662 }
2663 if ((senc = PyMem_Malloc(slen)) == NULL) {
2664 PyErr_NoMemory();
2665 goto error;
2666 }
2667 p = senc;
2668 if (!i2d_SSL_SESSION(session, &p)) {
2669 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2670 goto error;
2671 }
2672 const_p = senc;
2673 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2674 if (session == NULL) {
2675 goto error;
2676 }
2677 PyMem_Free(senc);
2678 return newsession;
2679 error:
2680 if (senc != NULL) {
2681 PyMem_Free(senc);
2682 }
2683 return NULL;
2684}
Christian Heimes99a65702016-09-10 23:44:53 +02002685
2686static PyObject *
2687PySSL_get_session(PySSLSocket *self, void *closure) {
2688 /* get_session can return sessions from a server-side connection,
2689 * it does not check for handshake done or client socket. */
2690 PySSLSession *pysess;
2691 SSL_SESSION *session;
2692
Christian Heimes99a65702016-09-10 23:44:53 +02002693 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2694 * https://github.com/openssl/openssl/issues/1550 */
2695 session = SSL_get0_session(self->ssl); /* borrowed reference */
2696 if (session == NULL) {
2697 Py_RETURN_NONE;
2698 }
2699 if ((session = _ssl_session_dup(session)) == NULL) {
2700 return NULL;
2701 }
Christian Heimes99a65702016-09-10 23:44:53 +02002702 session = SSL_get1_session(self->ssl);
2703 if (session == NULL) {
2704 Py_RETURN_NONE;
2705 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02002706 pysess = PyObject_GC_New(PySSLSession, self->ctx->state->PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002707 if (pysess == NULL) {
2708 SSL_SESSION_free(session);
2709 return NULL;
2710 }
2711
2712 assert(self->ctx);
2713 pysess->ctx = self->ctx;
2714 Py_INCREF(pysess->ctx);
2715 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002716 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002717 return (PyObject *)pysess;
2718}
2719
2720static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2721 void *closure)
2722 {
2723 PySSLSession *pysess;
Christian Heimes99a65702016-09-10 23:44:53 +02002724 SSL_SESSION *session;
Christian Heimes99a65702016-09-10 23:44:53 +02002725 int result;
2726
Christian Heimes7f1305e2021-04-17 20:06:38 +02002727 if (!Py_IS_TYPE(value, get_state_sock(self)->PySSLSession_Type)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002728 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002729 return -1;
2730 }
2731 pysess = (PySSLSession *)value;
2732
2733 if (self->ctx->ctx != pysess->ctx->ctx) {
2734 PyErr_SetString(PyExc_ValueError,
2735 "Session refers to a different SSLContext.");
2736 return -1;
2737 }
2738 if (self->socket_type != PY_SSL_CLIENT) {
2739 PyErr_SetString(PyExc_ValueError,
2740 "Cannot set session for server-side SSLSocket.");
2741 return -1;
2742 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002743 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002744 PyErr_SetString(PyExc_ValueError,
2745 "Cannot set session after handshake.");
2746 return -1;
2747 }
Christian Heimes99a65702016-09-10 23:44:53 +02002748 /* duplicate session */
2749 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2750 return -1;
2751 }
2752 result = SSL_set_session(self->ssl, session);
2753 /* free duplicate, SSL_set_session() bumps ref count */
2754 SSL_SESSION_free(session);
Christian Heimes99a65702016-09-10 23:44:53 +02002755 if (result == 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002756 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes99a65702016-09-10 23:44:53 +02002757 return -1;
2758 }
2759 return 0;
2760}
2761
2762PyDoc_STRVAR(PySSL_set_session_doc,
2763"_setter_session(session)\n\
2764\
2765Get / set SSLSession.");
2766
2767static PyObject *
2768PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2769 if (SSL_session_reused(self->ssl)) {
2770 Py_RETURN_TRUE;
2771 } else {
2772 Py_RETURN_FALSE;
2773 }
2774}
2775
2776PyDoc_STRVAR(PySSL_get_session_reused_doc,
2777"Was the client session reused during handshake?");
2778
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002779static PyGetSetDef ssl_getsetlist[] = {
2780 {"context", (getter) PySSL_get_context,
2781 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002782 {"server_side", (getter) PySSL_get_server_side, NULL,
2783 PySSL_get_server_side_doc},
2784 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2785 PySSL_get_server_hostname_doc},
2786 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2787 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002788 {"session", (getter) PySSL_get_session,
2789 (setter) PySSL_set_session, PySSL_set_session_doc},
2790 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2791 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002792 {NULL}, /* sentinel */
2793};
2794
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002795static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002796 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2797 _SSL__SSLSOCKET_WRITE_METHODDEF
2798 _SSL__SSLSOCKET_READ_METHODDEF
2799 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002800 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2801 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002802 _SSL__SSLSOCKET_CIPHER_METHODDEF
2803 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2804 _SSL__SSLSOCKET_VERSION_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002805 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2806 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2807 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002808 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002809 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002810};
2811
Christian Heimes5c36da72020-11-20 09:40:12 +01002812static PyType_Slot PySSLSocket_slots[] = {
2813 {Py_tp_methods, PySSLMethods},
2814 {Py_tp_getset, ssl_getsetlist},
2815 {Py_tp_dealloc, PySSL_dealloc},
2816 {Py_tp_traverse, PySSL_traverse},
2817 {Py_tp_clear, PySSL_clear},
2818 {0, 0},
2819};
2820
2821static PyType_Spec PySSLSocket_spec = {
2822 "_ssl._SSLSocket",
2823 sizeof(PySSLSocket),
2824 0,
2825 Py_TPFLAGS_DEFAULT,
2826 PySSLSocket_slots,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002827};
2828
Antoine Pitrou152efa22010-05-16 18:19:27 +00002829/*
2830 * _SSLContext objects
2831 */
2832
Christian Heimes5fe668c2016-09-12 00:01:11 +02002833static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02002834_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002835{
2836 int mode;
2837 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2838
2839 switch(n) {
2840 case PY_SSL_CERT_NONE:
2841 mode = SSL_VERIFY_NONE;
2842 break;
2843 case PY_SSL_CERT_OPTIONAL:
2844 mode = SSL_VERIFY_PEER;
2845 break;
2846 case PY_SSL_CERT_REQUIRED:
2847 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2848 break;
2849 default:
2850 PyErr_SetString(PyExc_ValueError,
2851 "invalid value for verify_mode");
2852 return -1;
2853 }
Christian Heimesf0f59302019-07-01 08:29:17 +02002854
2855 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
2856 * server sockets and SSL_set_post_handshake_auth() for client. */
2857
Christian Heimes5fe668c2016-09-12 00:01:11 +02002858 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02002859 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2860 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002861 return 0;
2862}
2863
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002864/*[clinic input]
2865@classmethod
2866_ssl._SSLContext.__new__
2867 protocol as proto_version: int
2868 /
2869[clinic start generated code]*/
2870
Antoine Pitrou152efa22010-05-16 18:19:27 +00002871static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002872_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2873/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002874{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002875 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002876 long options;
Christian Heimes2875c602021-04-19 07:27:10 +02002877 const SSL_METHOD *method = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002878 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002879 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002880 int result;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002881
Christian Heimes7f1305e2021-04-17 20:06:38 +02002882 /* slower approach, walk MRO and get borrowed reference to module.
2883 * _PyType_GetModuleByDef is required for SSLContext subclasses */
2884 PyObject *module = _PyType_GetModuleByDef(type, &_sslmodule_def);
2885 if (module == NULL) {
2886 PyErr_SetString(PyExc_RuntimeError,
2887 "Cannot find internal module state");
2888 return NULL;
2889 }
2890
Christian Heimes6e8cda92020-05-16 03:33:05 +02002891 switch(proto_version) {
2892#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
2893 case PY_SSL_VERSION_SSL3:
Christian Heimes2875c602021-04-19 07:27:10 +02002894 PY_SSL_DEPRECATED("PROTOCOL_SSLv3", 2, NULL);
2895 method = SSLv3_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002896 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05002897#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002898#if (defined(TLS1_VERSION) && \
2899 !defined(OPENSSL_NO_TLS1) && \
2900 !defined(OPENSSL_NO_TLS1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002901 case PY_SSL_VERSION_TLS1:
Christian Heimes2875c602021-04-19 07:27:10 +02002902 PY_SSL_DEPRECATED("PROTOCOL_TLSv1", 2, NULL);
2903 method = TLSv1_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002904 break;
Victor Stinner3de49192011-05-09 00:42:58 +02002905#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002906#if (defined(TLS1_1_VERSION) && \
2907 !defined(OPENSSL_NO_TLS1_1) && \
2908 !defined(OPENSSL_NO_TLS1_1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002909 case PY_SSL_VERSION_TLS1_1:
Christian Heimes2875c602021-04-19 07:27:10 +02002910 PY_SSL_DEPRECATED("PROTOCOL_TLSv1_1", 2, NULL);
2911 method = TLSv1_1_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002912 break;
2913#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002914#if (defined(TLS1_2_VERSION) && \
2915 !defined(OPENSSL_NO_TLS1_2) && \
2916 !defined(OPENSSL_NO_TLS1_2_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002917 case PY_SSL_VERSION_TLS1_2:
Christian Heimes2875c602021-04-19 07:27:10 +02002918 PY_SSL_DEPRECATED("PROTOCOL_TLSv1_2", 2, NULL);
2919 method = TLSv1_2_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002920 break;
2921#endif
2922 case PY_SSL_VERSION_TLS:
Christian Heimes2875c602021-04-19 07:27:10 +02002923 PY_SSL_DEPRECATED("PROTOCOL_TLS", 2, NULL);
2924 method = TLS_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002925 break;
2926 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes2875c602021-04-19 07:27:10 +02002927 method = TLS_client_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002928 break;
2929 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes2875c602021-04-19 07:27:10 +02002930 method = TLS_server_method();
Christian Heimes6e8cda92020-05-16 03:33:05 +02002931 break;
2932 default:
Christian Heimes2875c602021-04-19 07:27:10 +02002933 method = NULL;
Christian Heimes6e8cda92020-05-16 03:33:05 +02002934 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002935
Christian Heimes2875c602021-04-19 07:27:10 +02002936 if (method == NULL) {
2937 PyErr_Format(PyExc_ValueError,
2938 "invalid or unsupported protocol version %i",
2939 proto_version);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002940 return NULL;
2941 }
Christian Heimes2875c602021-04-19 07:27:10 +02002942
2943 PySSL_BEGIN_ALLOW_THREADS
2944 ctx = SSL_CTX_new(method);
2945 PySSL_END_ALLOW_THREADS
2946
Antoine Pitrou152efa22010-05-16 18:19:27 +00002947 if (ctx == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002948 _setSSLError(get_ssl_state(module), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002949 return NULL;
2950 }
2951
2952 assert(type != NULL && type->tp_alloc != NULL);
2953 self = (PySSLContext *) type->tp_alloc(type, 0);
2954 if (self == NULL) {
2955 SSL_CTX_free(ctx);
2956 return NULL;
2957 }
2958 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002959 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01002960 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02002961 self->msg_cb = NULL;
Christian Heimesc7f70692019-05-31 11:44:05 +02002962 self->keylog_filename = NULL;
2963 self->keylog_bio = NULL;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002964 self->alpn_protocols = NULL;
Christian Heimes11a14932018-02-24 02:35:08 +01002965 self->set_sni_cb = NULL;
Christian Heimes7f1305e2021-04-17 20:06:38 +02002966 self->state = get_ssl_state(module);
2967
Christian Heimes1aa9a752013-12-02 02:41:19 +01002968 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002969 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2970 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02002971 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02002972 Py_DECREF(self);
2973 return NULL;
2974 }
2975 } else {
2976 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02002977 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02002978 Py_DECREF(self);
2979 return NULL;
2980 }
2981 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002982 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002983 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2984 if (proto_version != PY_SSL_VERSION_SSL2)
2985 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002986 if (proto_version != PY_SSL_VERSION_SSL3)
2987 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002988 /* Minimal security flags for server and client side context.
2989 * Client sockets ignore server-side parameters. */
2990#ifdef SSL_OP_NO_COMPRESSION
2991 options |= SSL_OP_NO_COMPRESSION;
2992#endif
2993#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2994 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2995#endif
2996#ifdef SSL_OP_SINGLE_DH_USE
2997 options |= SSL_OP_SINGLE_DH_USE;
2998#endif
2999#ifdef SSL_OP_SINGLE_ECDH_USE
3000 options |= SSL_OP_SINGLE_ECDH_USE;
3001#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02003002#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
3003 /* Make OpenSSL 3.0.0 behave like 1.1.1 */
3004 options |= SSL_OP_IGNORE_UNEXPECTED_EOF;
3005#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003006 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003007
Semen Zhydenko1295e112017-10-15 21:28:31 +02003008 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003009 * It's far from perfect but gives users a better head start. */
3010 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003011#if PY_SSL_DEFAULT_CIPHERS == 2
3012 /* stick to OpenSSL's default settings */
3013 result = 1;
3014#else
3015 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3016#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003017 } else {
3018 /* SSLv2 needs MD5 */
3019 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3020 }
3021 if (result == 0) {
3022 Py_DECREF(self);
3023 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003024 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Christian Heimes358cfd42016-09-10 22:43:48 +02003025 "No cipher can be selected.");
3026 return NULL;
3027 }
3028
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003029 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
Christian Heimes39258d32021-04-17 11:36:35 +02003030 usage for no cost at all. */
3031 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003032
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003033#define SID_CTX "Python"
3034 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3035 sizeof(SID_CTX));
3036#undef SID_CTX
3037
Christian Heimes61d478c2018-01-27 15:51:38 +01003038 params = SSL_CTX_get0_param(self->ctx);
Christian Heimes61d478c2018-01-27 15:51:38 +01003039 /* Improve trust chain building when cross-signed intermediate
3040 certificates are present. See https://bugs.python.org/issue23476. */
3041 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Christian Heimes61d478c2018-01-27 15:51:38 +01003042 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003043
Christian Heimes9fb051f2018-09-23 08:32:31 +02003044#ifdef TLS1_3_VERSION
3045 self->post_handshake_auth = 0;
3046 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3047#endif
3048
Antoine Pitrou152efa22010-05-16 18:19:27 +00003049 return (PyObject *)self;
3050}
3051
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003052static int
3053context_traverse(PySSLContext *self, visitproc visit, void *arg)
3054{
Christian Heimes11a14932018-02-24 02:35:08 +01003055 Py_VISIT(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003056 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003057 return 0;
3058}
3059
3060static int
3061context_clear(PySSLContext *self)
3062{
Christian Heimes11a14932018-02-24 02:35:08 +01003063 Py_CLEAR(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003064 Py_CLEAR(self->msg_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003065 Py_CLEAR(self->keylog_filename);
3066 if (self->keylog_bio != NULL) {
3067 PySSL_BEGIN_ALLOW_THREADS
3068 BIO_free_all(self->keylog_bio);
3069 PySSL_END_ALLOW_THREADS
3070 self->keylog_bio = NULL;
3071 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003072 return 0;
3073}
3074
Antoine Pitrou152efa22010-05-16 18:19:27 +00003075static void
3076context_dealloc(PySSLContext *self)
3077{
Christian Heimes5c36da72020-11-20 09:40:12 +01003078 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09003079 /* bpo-31095: UnTrack is needed before calling any callbacks */
3080 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003081 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003082 SSL_CTX_free(self->ctx);
Christian Heimes39258d32021-04-17 11:36:35 +02003083 PyMem_FREE(self->alpn_protocols);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003084 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01003085 Py_DECREF(tp);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003086}
3087
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003088/*[clinic input]
3089_ssl._SSLContext.set_ciphers
3090 cipherlist: str
3091 /
3092[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003093
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003094static PyObject *
3095_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3096/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3097{
3098 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003099 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003100 /* Clearing the error queue is necessary on some OpenSSL versions,
3101 otherwise the error will be reported again when another SSL call
3102 is done. */
3103 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003104 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003105 "No cipher can be selected.");
3106 return NULL;
3107 }
3108 Py_RETURN_NONE;
3109}
3110
Christian Heimes25bfcd52016-09-06 00:04:45 +02003111/*[clinic input]
3112_ssl._SSLContext.get_ciphers
3113[clinic start generated code]*/
3114
3115static PyObject *
3116_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3117/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3118{
3119 SSL *ssl = NULL;
3120 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003121 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003122 int i=0;
3123 PyObject *result = NULL, *dct;
3124
3125 ssl = SSL_new(self->ctx);
3126 if (ssl == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003127 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes25bfcd52016-09-06 00:04:45 +02003128 goto exit;
3129 }
3130 sk = SSL_get_ciphers(ssl);
3131
3132 result = PyList_New(sk_SSL_CIPHER_num(sk));
3133 if (result == NULL) {
3134 goto exit;
3135 }
3136
3137 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3138 cipher = sk_SSL_CIPHER_value(sk, i);
3139 dct = cipher_to_dict(cipher);
3140 if (dct == NULL) {
3141 Py_CLEAR(result);
3142 goto exit;
3143 }
3144 PyList_SET_ITEM(result, i, dct);
3145 }
3146
3147 exit:
3148 if (ssl != NULL)
3149 SSL_free(ssl);
3150 return result;
3151
3152}
Christian Heimes25bfcd52016-09-06 00:04:45 +02003153
3154
Benjamin Petersoncca27322015-01-23 16:35:37 -05003155static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003156do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3157 const unsigned char *server_protocols, unsigned int server_protocols_len,
3158 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003159{
Benjamin Peterson88615022015-01-23 17:30:26 -05003160 int ret;
3161 if (client_protocols == NULL) {
3162 client_protocols = (unsigned char *)"";
3163 client_protocols_len = 0;
3164 }
3165 if (server_protocols == NULL) {
3166 server_protocols = (unsigned char *)"";
3167 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003168 }
3169
Benjamin Peterson88615022015-01-23 17:30:26 -05003170 ret = SSL_select_next_proto(out, outlen,
3171 server_protocols, server_protocols_len,
3172 client_protocols, client_protocols_len);
3173 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3174 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003175
3176 return SSL_TLSEXT_ERR_OK;
3177}
3178
Benjamin Petersoncca27322015-01-23 16:35:37 -05003179static int
3180_selectALPN_cb(SSL *s,
3181 const unsigned char **out, unsigned char *outlen,
3182 const unsigned char *client_protocols, unsigned int client_protocols_len,
3183 void *args)
3184{
3185 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003186 return do_protocol_selection(1, (unsigned char **)out, outlen,
3187 ctx->alpn_protocols, ctx->alpn_protocols_len,
3188 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003189}
Benjamin Petersoncca27322015-01-23 16:35:37 -05003190
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003191/*[clinic input]
3192_ssl._SSLContext._set_alpn_protocols
3193 protos: Py_buffer
3194 /
3195[clinic start generated code]*/
3196
Benjamin Petersoncca27322015-01-23 16:35:37 -05003197static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003198_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3199 Py_buffer *protos)
3200/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003201{
Victor Stinner5a615592017-09-14 01:10:30 -07003202 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003203 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003204 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003205 return NULL;
3206 }
3207
Victor Stinner00d7abd2020-12-01 09:56:42 +01003208 PyMem_Free(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003209 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003210 if (!self->alpn_protocols)
3211 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003212 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003213 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003214
3215 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3216 return PyErr_NoMemory();
3217 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3218
Benjamin Petersoncca27322015-01-23 16:35:37 -05003219 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003220}
3221
Antoine Pitrou152efa22010-05-16 18:19:27 +00003222static PyObject *
3223get_verify_mode(PySSLContext *self, void *c)
3224{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003225 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3226 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3227 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3228 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003229 case SSL_VERIFY_NONE:
3230 return PyLong_FromLong(PY_SSL_CERT_NONE);
3231 case SSL_VERIFY_PEER:
3232 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3233 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3234 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3235 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02003236 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003237 "invalid return value from SSL_CTX_get_verify_mode");
3238 return NULL;
3239}
3240
3241static int
3242set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3243{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003244 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003245 if (!PyArg_Parse(arg, "i", &n))
3246 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003247 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003248 PyErr_SetString(PyExc_ValueError,
3249 "Cannot set verify_mode to CERT_NONE when "
3250 "check_hostname is enabled.");
3251 return -1;
3252 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003253 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003254}
3255
3256static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003257get_verify_flags(PySSLContext *self, void *c)
3258{
Christian Heimes598894f2016-09-05 23:19:05 +02003259 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003260 unsigned long flags;
3261
Christian Heimes61d478c2018-01-27 15:51:38 +01003262 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003263 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003264 return PyLong_FromUnsignedLong(flags);
3265}
3266
3267static int
3268set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3269{
Christian Heimes598894f2016-09-05 23:19:05 +02003270 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003271 unsigned long new_flags, flags, set, clear;
3272
3273 if (!PyArg_Parse(arg, "k", &new_flags))
3274 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003275 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003276 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003277 clear = flags & ~new_flags;
3278 set = ~flags & new_flags;
3279 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003280 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003281 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003282 return -1;
3283 }
3284 }
3285 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003286 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003287 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003288 return -1;
3289 }
3290 }
3291 return 0;
3292}
3293
Christian Heimes698dde12018-02-27 11:54:43 +01003294/* Getter and setter for protocol version */
Christian Heimes698dde12018-02-27 11:54:43 +01003295static int
3296set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3297{
3298 long v;
3299 int result;
3300
3301 if (!PyArg_Parse(arg, "l", &v))
3302 return -1;
3303 if (v > INT_MAX) {
3304 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3305 return -1;
3306 }
3307
3308 switch(self->protocol) {
3309 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3310 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3311 case PY_SSL_VERSION_TLS:
3312 break;
3313 default:
3314 PyErr_SetString(
3315 PyExc_ValueError,
3316 "The context's protocol doesn't support modification of "
3317 "highest and lowest version."
3318 );
3319 return -1;
3320 }
3321
Christian Heimes2875c602021-04-19 07:27:10 +02003322 /* check for deprecations and supported values */
3323 switch(v) {
3324 case PY_PROTO_SSLv3:
3325 PY_SSL_DEPRECATED("TLSVersion.SSLv3", 2, -1);
3326 break;
3327 case PY_PROTO_TLSv1:
3328 PY_SSL_DEPRECATED("TLSVersion.TLSv1", 2, -1);
3329 break;
3330 case PY_PROTO_TLSv1_1:
3331 PY_SSL_DEPRECATED("TLSVersion.TLSv1_1", 2, -1);
3332 break;
3333 case PY_PROTO_MINIMUM_SUPPORTED:
3334 case PY_PROTO_MAXIMUM_SUPPORTED:
3335 case PY_PROTO_TLSv1_2:
3336 case PY_PROTO_TLSv1_3:
3337 /* ok */
3338 break;
3339 default:
3340 PyErr_Format(PyExc_ValueError,
3341 "Unsupported TLS/SSL version 0x%x", v);
3342 return -1;
3343 }
3344
Christian Heimes698dde12018-02-27 11:54:43 +01003345 if (what == 0) {
3346 switch(v) {
3347 case PY_PROTO_MINIMUM_SUPPORTED:
3348 v = 0;
3349 break;
3350 case PY_PROTO_MAXIMUM_SUPPORTED:
3351 /* Emulate max for set_min_proto_version */
3352 v = PY_PROTO_MAXIMUM_AVAILABLE;
3353 break;
3354 default:
3355 break;
3356 }
3357 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3358 }
3359 else {
3360 switch(v) {
3361 case PY_PROTO_MAXIMUM_SUPPORTED:
3362 v = 0;
3363 break;
3364 case PY_PROTO_MINIMUM_SUPPORTED:
3365 /* Emulate max for set_min_proto_version */
3366 v = PY_PROTO_MINIMUM_AVAILABLE;
3367 break;
3368 default:
3369 break;
3370 }
3371 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3372 }
3373 if (result == 0) {
3374 PyErr_Format(PyExc_ValueError,
3375 "Unsupported protocol version 0x%x", v);
3376 return -1;
3377 }
3378 return 0;
3379}
3380
3381static PyObject *
3382get_minimum_version(PySSLContext *self, void *c)
3383{
3384 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3385 if (v == 0) {
3386 v = PY_PROTO_MINIMUM_SUPPORTED;
3387 }
3388 return PyLong_FromLong(v);
3389}
3390
3391static int
3392set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3393{
3394 return set_min_max_proto_version(self, arg, 0);
3395}
3396
3397static PyObject *
3398get_maximum_version(PySSLContext *self, void *c)
3399{
3400 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3401 if (v == 0) {
3402 v = PY_PROTO_MAXIMUM_SUPPORTED;
3403 }
3404 return PyLong_FromLong(v);
3405}
3406
3407static int
3408set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3409{
3410 return set_min_max_proto_version(self, arg, 1);
3411}
Christian Heimes698dde12018-02-27 11:54:43 +01003412
Christian Heimes39258d32021-04-17 11:36:35 +02003413#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02003414static PyObject *
3415get_num_tickets(PySSLContext *self, void *c)
3416{
Victor Stinner76611c72019-07-09 13:30:52 +02003417 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003418}
3419
3420static int
3421set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3422{
3423 long num;
3424 if (!PyArg_Parse(arg, "l", &num))
3425 return -1;
3426 if (num < 0) {
3427 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3428 return -1;
3429 }
3430 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3431 PyErr_SetString(PyExc_ValueError,
3432 "SSLContext is not a server context.");
3433 return -1;
3434 }
3435 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3436 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3437 return -1;
3438 }
3439 return 0;
3440}
3441
3442PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3443"Control the number of TLSv1.3 session tickets");
Christian Heimes39258d32021-04-17 11:36:35 +02003444#endif /* TLS1_3_VERSION */
Christian Heimes78c7d522019-06-03 21:00:10 +02003445
matthewhughes9348e836bb2020-07-17 09:59:15 +01003446static PyObject *
3447get_security_level(PySSLContext *self, void *c)
3448{
3449 return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3450}
3451PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
matthewhughes9348e836bb2020-07-17 09:59:15 +01003452
Christian Heimes22587792013-11-21 23:56:13 +01003453static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003454get_options(PySSLContext *self, void *c)
3455{
3456 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3457}
3458
3459static int
3460set_options(PySSLContext *self, PyObject *arg, void *c)
3461{
3462 long new_opts, opts, set, clear;
Christian Heimes2875c602021-04-19 07:27:10 +02003463 long opt_no = (
3464 SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 |
3465 SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_2
3466 );
3467
Antoine Pitroub5218772010-05-21 09:56:06 +00003468 if (!PyArg_Parse(arg, "l", &new_opts))
3469 return -1;
3470 opts = SSL_CTX_get_options(self->ctx);
3471 clear = opts & ~new_opts;
3472 set = ~opts & new_opts;
Christian Heimes2875c602021-04-19 07:27:10 +02003473
3474 if ((set & opt_no) != 0) {
3475 if (_ssl_deprecated("Setting OP_NO_SSL* or SSL_NO_TLS* options is "
3476 "deprecated", 2) < 0) {
3477 return -1;
3478 }
3479 }
Antoine Pitroub5218772010-05-21 09:56:06 +00003480 if (clear) {
Antoine Pitroub5218772010-05-21 09:56:06 +00003481 SSL_CTX_clear_options(self->ctx, clear);
Antoine Pitroub5218772010-05-21 09:56:06 +00003482 }
3483 if (set)
3484 SSL_CTX_set_options(self->ctx, set);
3485 return 0;
3486}
3487
Christian Heimes1aa9a752013-12-02 02:41:19 +01003488static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003489get_host_flags(PySSLContext *self, void *c)
3490{
3491 return PyLong_FromUnsignedLong(self->hostflags);
3492}
3493
3494static int
3495set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3496{
3497 X509_VERIFY_PARAM *param;
3498 unsigned int new_flags = 0;
3499
3500 if (!PyArg_Parse(arg, "I", &new_flags))
3501 return -1;
3502
3503 param = SSL_CTX_get0_param(self->ctx);
3504 self->hostflags = new_flags;
3505 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3506 return 0;
3507}
3508
3509static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003510get_check_hostname(PySSLContext *self, void *c)
3511{
3512 return PyBool_FromLong(self->check_hostname);
3513}
3514
3515static int
3516set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3517{
3518 int check_hostname;
3519 if (!PyArg_Parse(arg, "p", &check_hostname))
3520 return -1;
3521 if (check_hostname &&
3522 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003523 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003524 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003525 return -1;
3526 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003527 }
3528 self->check_hostname = check_hostname;
3529 return 0;
3530}
3531
Christian Heimes11a14932018-02-24 02:35:08 +01003532static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003533get_post_handshake_auth(PySSLContext *self, void *c) {
3534#if TLS1_3_VERSION
3535 return PyBool_FromLong(self->post_handshake_auth);
3536#else
3537 Py_RETURN_NONE;
3538#endif
3539}
3540
3541#if TLS1_3_VERSION
3542static int
3543set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003544 if (arg == NULL) {
3545 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3546 return -1;
3547 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003548 int pha = PyObject_IsTrue(arg);
3549
3550 if (pha == -1) {
3551 return -1;
3552 }
3553 self->post_handshake_auth = pha;
3554
Christian Heimesf0f59302019-07-01 08:29:17 +02003555 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3556 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003557
3558 return 0;
3559}
3560#endif
3561
3562static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003563get_protocol(PySSLContext *self, void *c) {
3564 return PyLong_FromLong(self->protocol);
3565}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003566
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003567typedef struct {
3568 PyThreadState *thread_state;
3569 PyObject *callable;
3570 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003571 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003572 int error;
3573} _PySSLPasswordInfo;
3574
3575static int
3576_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3577 const char *bad_type_error)
3578{
3579 /* Set the password and size fields of a _PySSLPasswordInfo struct
3580 from a unicode, bytes, or byte array object.
3581 The password field will be dynamically allocated and must be freed
3582 by the caller */
3583 PyObject *password_bytes = NULL;
3584 const char *data = NULL;
3585 Py_ssize_t size;
3586
3587 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003588 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003589 if (!password_bytes) {
3590 goto error;
3591 }
3592 data = PyBytes_AS_STRING(password_bytes);
3593 size = PyBytes_GET_SIZE(password_bytes);
3594 } else if (PyBytes_Check(password)) {
3595 data = PyBytes_AS_STRING(password);
3596 size = PyBytes_GET_SIZE(password);
3597 } else if (PyByteArray_Check(password)) {
3598 data = PyByteArray_AS_STRING(password);
3599 size = PyByteArray_GET_SIZE(password);
3600 } else {
3601 PyErr_SetString(PyExc_TypeError, bad_type_error);
3602 goto error;
3603 }
3604
Victor Stinner9ee02032013-06-23 15:08:23 +02003605 if (size > (Py_ssize_t)INT_MAX) {
3606 PyErr_Format(PyExc_ValueError,
3607 "password cannot be longer than %d bytes", INT_MAX);
3608 goto error;
3609 }
3610
Victor Stinner11ebff22013-07-07 17:07:52 +02003611 PyMem_Free(pw_info->password);
3612 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003613 if (!pw_info->password) {
3614 PyErr_SetString(PyExc_MemoryError,
3615 "unable to allocate password buffer");
3616 goto error;
3617 }
3618 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003619 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003620
3621 Py_XDECREF(password_bytes);
3622 return 1;
3623
3624error:
3625 Py_XDECREF(password_bytes);
3626 return 0;
3627}
3628
3629static int
3630_password_callback(char *buf, int size, int rwflag, void *userdata)
3631{
3632 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3633 PyObject *fn_ret = NULL;
3634
3635 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3636
Christian Heimesd3b73f32021-04-09 15:23:38 +02003637 if (pw_info->error) {
3638 /* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
3639 * callback multiple times which can lead to fatal Python error in
3640 * exception check. */
3641 goto error;
3642 }
3643
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003644 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003645 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003646 if (!fn_ret) {
3647 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3648 core python API, so we could use it to add a frame here */
3649 goto error;
3650 }
3651
3652 if (!_pwinfo_set(pw_info, fn_ret,
3653 "password callback must return a string")) {
3654 goto error;
3655 }
3656 Py_CLEAR(fn_ret);
3657 }
3658
3659 if (pw_info->size > size) {
3660 PyErr_Format(PyExc_ValueError,
3661 "password cannot be longer than %d bytes", size);
3662 goto error;
3663 }
3664
3665 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3666 memcpy(buf, pw_info->password, pw_info->size);
3667 return pw_info->size;
3668
3669error:
3670 Py_XDECREF(fn_ret);
3671 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3672 pw_info->error = 1;
3673 return -1;
3674}
3675
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003676/*[clinic input]
3677_ssl._SSLContext.load_cert_chain
3678 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003679 keyfile: object = None
3680 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003681
3682[clinic start generated code]*/
3683
Antoine Pitroub5218772010-05-21 09:56:06 +00003684static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003685_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3686 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003687/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003688{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003689 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003690 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3691 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003692 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003693 int r;
3694
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003695 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003696 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003697 if (keyfile == Py_None)
3698 keyfile = NULL;
3699 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003700 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3701 PyErr_SetString(PyExc_TypeError,
3702 "certfile should be a valid filesystem path");
3703 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003704 return NULL;
3705 }
3706 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003707 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3708 PyErr_SetString(PyExc_TypeError,
3709 "keyfile should be a valid filesystem path");
3710 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003711 goto error;
3712 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003713 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003714 if (PyCallable_Check(password)) {
3715 pw_info.callable = password;
3716 } else if (!_pwinfo_set(&pw_info, password,
3717 "password should be a string or callable")) {
3718 goto error;
3719 }
3720 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3721 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3722 }
3723 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003724 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3725 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003726 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003727 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003728 if (pw_info.error) {
3729 ERR_clear_error();
3730 /* the password callback has already set the error information */
3731 }
3732 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003733 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003734 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003735 }
3736 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003737 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003738 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003739 goto error;
3740 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003741 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003742 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003743 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3744 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003745 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3746 Py_CLEAR(keyfile_bytes);
3747 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003748 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003749 if (pw_info.error) {
3750 ERR_clear_error();
3751 /* the password callback has already set the error information */
3752 }
3753 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003754 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003755 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003756 }
3757 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003758 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003759 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003760 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003761 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003762 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003763 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003764 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003765 if (r != 1) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003766 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003767 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003768 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003769 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3770 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003771 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003772 Py_RETURN_NONE;
3773
3774error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003775 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3776 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003777 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003778 Py_XDECREF(keyfile_bytes);
3779 Py_XDECREF(certfile_bytes);
3780 return NULL;
3781}
3782
Christian Heimesefff7062013-11-21 03:35:02 +01003783/* internal helper function, returns -1 on error
3784 */
3785static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03003786_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01003787 int filetype)
3788{
3789 BIO *biobuf = NULL;
3790 X509_STORE *store;
3791 int retval = 0, err, loaded = 0;
3792
3793 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3794
3795 if (len <= 0) {
3796 PyErr_SetString(PyExc_ValueError,
3797 "Empty certificate data");
3798 return -1;
3799 } else if (len > INT_MAX) {
3800 PyErr_SetString(PyExc_OverflowError,
3801 "Certificate data is too long.");
3802 return -1;
3803 }
3804
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003805 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003806 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003807 _setSSLError(get_state_ctx(self), "Can't allocate buffer", 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003808 return -1;
3809 }
3810
3811 store = SSL_CTX_get_cert_store(self->ctx);
3812 assert(store != NULL);
3813
3814 while (1) {
3815 X509 *cert = NULL;
3816 int r;
3817
3818 if (filetype == SSL_FILETYPE_ASN1) {
3819 cert = d2i_X509_bio(biobuf, NULL);
3820 } else {
3821 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003822 SSL_CTX_get_default_passwd_cb(self->ctx),
3823 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3824 );
Christian Heimesefff7062013-11-21 03:35:02 +01003825 }
3826 if (cert == NULL) {
3827 break;
3828 }
3829 r = X509_STORE_add_cert(store, cert);
3830 X509_free(cert);
3831 if (!r) {
3832 err = ERR_peek_last_error();
3833 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3834 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3835 /* cert already in hash table, not an error */
3836 ERR_clear_error();
3837 } else {
3838 break;
3839 }
3840 }
3841 loaded++;
3842 }
3843
3844 err = ERR_peek_last_error();
3845 if ((filetype == SSL_FILETYPE_ASN1) &&
3846 (loaded > 0) &&
3847 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3848 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3849 /* EOF ASN1 file, not an error */
3850 ERR_clear_error();
3851 retval = 0;
3852 } else if ((filetype == SSL_FILETYPE_PEM) &&
3853 (loaded > 0) &&
3854 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3855 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3856 /* EOF PEM file, not an error */
3857 ERR_clear_error();
3858 retval = 0;
3859 } else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003860 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003861 retval = -1;
3862 }
3863
3864 BIO_free(biobuf);
3865 return retval;
3866}
3867
3868
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003869/*[clinic input]
3870_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003871 cafile: object = None
3872 capath: object = None
3873 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003874
3875[clinic start generated code]*/
3876
Antoine Pitrou152efa22010-05-16 18:19:27 +00003877static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003878_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3879 PyObject *cafile,
3880 PyObject *capath,
3881 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003882/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003883{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003884 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3885 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003886 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003887
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003888 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003889 if (cafile == Py_None)
3890 cafile = NULL;
3891 if (capath == Py_None)
3892 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003893 if (cadata == Py_None)
3894 cadata = NULL;
3895
3896 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003897 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003898 "cafile, capath and cadata cannot be all omitted");
3899 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003900 }
3901 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003902 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3903 PyErr_SetString(PyExc_TypeError,
3904 "cafile should be a valid filesystem path");
3905 }
Christian Heimesefff7062013-11-21 03:35:02 +01003906 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003907 }
3908 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003909 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3910 PyErr_SetString(PyExc_TypeError,
3911 "capath should be a valid filesystem path");
3912 }
Christian Heimesefff7062013-11-21 03:35:02 +01003913 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003914 }
Christian Heimesefff7062013-11-21 03:35:02 +01003915
3916 /* validata cadata type and load cadata */
3917 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003918 if (PyUnicode_Check(cadata)) {
3919 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
3920 if (cadata_ascii == NULL) {
3921 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
3922 goto invalid_cadata;
3923 }
3924 goto error;
3925 }
3926 r = _add_ca_certs(self,
3927 PyBytes_AS_STRING(cadata_ascii),
3928 PyBytes_GET_SIZE(cadata_ascii),
3929 SSL_FILETYPE_PEM);
3930 Py_DECREF(cadata_ascii);
3931 if (r == -1) {
3932 goto error;
3933 }
3934 }
3935 else if (PyObject_CheckBuffer(cadata)) {
3936 Py_buffer buf;
3937 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
3938 goto error;
3939 }
Christian Heimesefff7062013-11-21 03:35:02 +01003940 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3941 PyBuffer_Release(&buf);
3942 PyErr_SetString(PyExc_TypeError,
3943 "cadata should be a contiguous buffer with "
3944 "a single dimension");
3945 goto error;
3946 }
3947 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3948 PyBuffer_Release(&buf);
3949 if (r == -1) {
3950 goto error;
3951 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003952 }
3953 else {
3954 invalid_cadata:
3955 PyErr_SetString(PyExc_TypeError,
3956 "cadata should be an ASCII string or a "
3957 "bytes-like object");
3958 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01003959 }
3960 }
3961
3962 /* load cafile or capath */
3963 if (cafile || capath) {
3964 if (cafile)
3965 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3966 if (capath)
3967 capath_buf = PyBytes_AS_STRING(capath_bytes);
3968 PySSL_BEGIN_ALLOW_THREADS
3969 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3970 PySSL_END_ALLOW_THREADS
3971 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01003972 if (errno != 0) {
3973 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003974 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003975 }
3976 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003977 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003978 }
3979 goto error;
3980 }
3981 }
3982 goto end;
3983
3984 error:
3985 ok = 0;
3986 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003987 Py_XDECREF(cafile_bytes);
3988 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003989 if (ok) {
3990 Py_RETURN_NONE;
3991 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003992 return NULL;
3993 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003994}
3995
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003996/*[clinic input]
3997_ssl._SSLContext.load_dh_params
3998 path as filepath: object
3999 /
4000
4001[clinic start generated code]*/
4002
Antoine Pitrou152efa22010-05-16 18:19:27 +00004003static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004004_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4005/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004006{
4007 FILE *f;
4008 DH *dh;
4009
Victor Stinnerdaf45552013-08-28 00:53:59 +02004010 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004011 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004012 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004013
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004014 errno = 0;
4015 PySSL_BEGIN_ALLOW_THREADS
4016 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004017 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004018 PySSL_END_ALLOW_THREADS
4019 if (dh == NULL) {
4020 if (errno != 0) {
4021 ERR_clear_error();
4022 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4023 }
4024 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004025 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004026 }
4027 return NULL;
4028 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06004029 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4030 DH_free(dh);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004031 return _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzaebc0492020-07-07 22:21:58 -06004032 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004033 DH_free(dh);
4034 Py_RETURN_NONE;
4035}
4036
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004037/*[clinic input]
4038_ssl._SSLContext._wrap_socket
Christian Heimes7f1305e2021-04-17 20:06:38 +02004039 sock: object(subclass_of="get_state_ctx(self)->Sock_Type")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004040 server_side: int
4041 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004042 *
4043 owner: object = None
4044 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004045
4046[clinic start generated code]*/
4047
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004048static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004049_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004050 int server_side, PyObject *hostname_obj,
4051 PyObject *owner, PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004052/*[clinic end generated code: output=f103f238633940b4 input=f5916eadbc6eae81]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004053{
Antoine Pitroud5323212010-10-22 18:19:07 +00004054 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004055 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004056
Antoine Pitroud5323212010-10-22 18:19:07 +00004057 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004058 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004059 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004060 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004061 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004062 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004063
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004064 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4065 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004066 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004067 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004068 if (hostname != NULL)
4069 PyMem_Free(hostname);
4070 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004071}
4072
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004073/*[clinic input]
4074_ssl._SSLContext._wrap_bio
Christian Heimes7f1305e2021-04-17 20:06:38 +02004075 incoming: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4076 outgoing: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004077 server_side: int
4078 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004079 *
4080 owner: object = None
4081 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004082
4083[clinic start generated code]*/
4084
Antoine Pitroub0182c82010-10-12 20:09:02 +00004085static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004086_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4087 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004088 PyObject *hostname_obj, PyObject *owner,
4089 PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004090/*[clinic end generated code: output=5c5d6d9b41f99332 input=331edeec9c738382]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004091{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004092 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004093 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004094
4095 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004096 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004097 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004098 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004099 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004100 }
4101
4102 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004103 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004104 incoming, outgoing);
4105
4106 PyMem_Free(hostname);
4107 return res;
4108}
4109
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004110/*[clinic input]
4111_ssl._SSLContext.session_stats
4112[clinic start generated code]*/
4113
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004114static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004115_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4116/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004117{
4118 int r;
4119 PyObject *value, *stats = PyDict_New();
4120 if (!stats)
4121 return NULL;
4122
4123#define ADD_STATS(SSL_NAME, KEY_NAME) \
4124 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4125 if (value == NULL) \
4126 goto error; \
4127 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4128 Py_DECREF(value); \
4129 if (r < 0) \
4130 goto error;
4131
4132 ADD_STATS(number, "number");
4133 ADD_STATS(connect, "connect");
4134 ADD_STATS(connect_good, "connect_good");
4135 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4136 ADD_STATS(accept, "accept");
4137 ADD_STATS(accept_good, "accept_good");
4138 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4139 ADD_STATS(accept, "accept");
4140 ADD_STATS(hits, "hits");
4141 ADD_STATS(misses, "misses");
4142 ADD_STATS(timeouts, "timeouts");
4143 ADD_STATS(cache_full, "cache_full");
4144
4145#undef ADD_STATS
4146
4147 return stats;
4148
4149error:
4150 Py_DECREF(stats);
4151 return NULL;
4152}
4153
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004154/*[clinic input]
4155_ssl._SSLContext.set_default_verify_paths
4156[clinic start generated code]*/
4157
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004158static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004159_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4160/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004161{
4162 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004163 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004164 return NULL;
4165 }
4166 Py_RETURN_NONE;
4167}
4168
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004169/*[clinic input]
4170_ssl._SSLContext.set_ecdh_curve
4171 name: object
4172 /
4173
4174[clinic start generated code]*/
4175
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004176static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004177_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4178/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004179{
4180 PyObject *name_bytes;
4181 int nid;
4182 EC_KEY *key;
4183
4184 if (!PyUnicode_FSConverter(name, &name_bytes))
4185 return NULL;
4186 assert(PyBytes_Check(name_bytes));
4187 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4188 Py_DECREF(name_bytes);
4189 if (nid == 0) {
4190 PyErr_Format(PyExc_ValueError,
4191 "unknown elliptic curve name %R", name);
4192 return NULL;
4193 }
4194 key = EC_KEY_new_by_curve_name(nid);
4195 if (key == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004196 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004197 return NULL;
4198 }
4199 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4200 EC_KEY_free(key);
4201 Py_RETURN_NONE;
4202}
4203
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004204static int
4205_servername_callback(SSL *s, int *al, void *args)
4206{
4207 int ret;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004208 PySSLContext *sslctx = (PySSLContext *) args;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004209 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004210 PyObject *result;
4211 /* The high-level ssl.SSLSocket object */
4212 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004213 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004214 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004215
Christian Heimes7f1305e2021-04-17 20:06:38 +02004216 if (sslctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004217 /* remove race condition in this the call back while if removing the
4218 * callback is in progress */
4219 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004220 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004221 }
4222
4223 ssl = SSL_get_app_data(s);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004224 assert(Py_IS_TYPE(ssl, get_state_ctx(sslctx)->PySSLSocket_Type));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004225
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004226 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004227 * SSL connection and that has a .context attribute that can be changed to
4228 * identify the requested hostname. Since the official API is the Python
4229 * level API we want to pass the callback a Python level object rather than
4230 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4231 * SSLObject) that will be passed. Otherwise if there's a socket then that
4232 * will be passed. If both do not exist only then the C-level object is
4233 * passed. */
4234 if (ssl->owner)
4235 ssl_socket = PyWeakref_GetObject(ssl->owner);
4236 else if (ssl->Socket)
4237 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4238 else
4239 ssl_socket = (PyObject *) ssl;
4240
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004241 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004242 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004243 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004244
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004245 if (servername == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004246 result = PyObject_CallFunctionObjArgs(sslctx->set_sni_cb, ssl_socket,
4247 Py_None, sslctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004248 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004249 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004250 PyObject *servername_bytes;
4251 PyObject *servername_str;
4252
4253 servername_bytes = PyBytes_FromString(servername);
4254 if (servername_bytes == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004255 PyErr_WriteUnraisable((PyObject *) sslctx);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004256 goto error;
4257 }
Christian Heimes11a14932018-02-24 02:35:08 +01004258 /* server_hostname was encoded to an A-label by our caller; put it
4259 * back into a str object, but still as an A-label (bpo-28414)
4260 */
4261 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004262 if (servername_str == NULL) {
4263 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004264 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004265 goto error;
4266 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004267 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004268 result = PyObject_CallFunctionObjArgs(
Christian Heimes7f1305e2021-04-17 20:06:38 +02004269 sslctx->set_sni_cb, ssl_socket, servername_str,
4270 sslctx, NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004271 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004272 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004273 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004274
4275 if (result == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004276 PyErr_WriteUnraisable(sslctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004277 *al = SSL_AD_HANDSHAKE_FAILURE;
4278 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4279 }
4280 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004281 /* Result may be None, a SSLContext or an integer
4282 * None and SSLContext are OK, integer or other values are an error.
4283 */
4284 if (result == Py_None) {
4285 ret = SSL_TLSEXT_ERR_OK;
4286 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004287 *al = (int) PyLong_AsLong(result);
4288 if (PyErr_Occurred()) {
4289 PyErr_WriteUnraisable(result);
4290 *al = SSL_AD_INTERNAL_ERROR;
4291 }
4292 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4293 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004294 Py_DECREF(result);
4295 }
4296
4297 PyGILState_Release(gstate);
4298 return ret;
4299
4300error:
4301 Py_DECREF(ssl_socket);
4302 *al = SSL_AD_INTERNAL_ERROR;
4303 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4304 PyGILState_Release(gstate);
4305 return ret;
4306}
4307
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004308static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004309get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004310{
Christian Heimes11a14932018-02-24 02:35:08 +01004311 PyObject *cb = self->set_sni_cb;
4312 if (cb == NULL) {
4313 Py_RETURN_NONE;
4314 }
4315 Py_INCREF(cb);
4316 return cb;
4317}
4318
4319static int
4320set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4321{
4322 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4323 PyErr_SetString(PyExc_ValueError,
4324 "sni_callback cannot be set on TLS_CLIENT context");
4325 return -1;
4326 }
Christian Heimes11a14932018-02-24 02:35:08 +01004327 Py_CLEAR(self->set_sni_cb);
4328 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004329 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4330 }
4331 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004332 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004333 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4334 PyErr_SetString(PyExc_TypeError,
4335 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004336 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004337 }
Christian Heimes11a14932018-02-24 02:35:08 +01004338 Py_INCREF(arg);
4339 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004340 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4341 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4342 }
Christian Heimes11a14932018-02-24 02:35:08 +01004343 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004344}
4345
Christian Heimes11a14932018-02-24 02:35:08 +01004346PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4347"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4348\n\
4349If the argument is None then the callback is disabled. The method is called\n\
4350with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4351See RFC 6066 for details of the SNI extension.");
4352
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004353/*[clinic input]
4354_ssl._SSLContext.cert_store_stats
4355
4356Returns quantities of loaded X.509 certificates.
4357
4358X.509 certificates with a CA extension and certificate revocation lists
4359inside the context's cert store.
4360
4361NOTE: Certificates in a capath directory aren't loaded unless they have
4362been used at least once.
4363[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004364
4365static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004366_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4367/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004368{
4369 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004370 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004371 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004372 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004373
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++) {
4377 obj = sk_X509_OBJECT_value(objs, i);
4378 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004379 case X509_LU_X509:
4380 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004381 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004382 ca++;
4383 }
4384 break;
4385 case X509_LU_CRL:
4386 crl++;
4387 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004388 default:
4389 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4390 * As far as I can tell they are internal states and never
4391 * stored in a cert store */
4392 break;
4393 }
4394 }
4395 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4396 "x509_ca", ca);
4397}
4398
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004399/*[clinic input]
4400_ssl._SSLContext.get_ca_certs
4401 binary_form: bool = False
4402
4403Returns a list of dicts with information of loaded CA certs.
4404
4405If the optional argument is True, returns a DER-encoded copy of the CA
4406certificate.
4407
4408NOTE: Certificates in a capath directory aren't loaded unless they have
4409been used at least once.
4410[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004411
4412static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004413_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4414/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004415{
4416 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004417 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004418 PyObject *ci = NULL, *rlist = NULL;
4419 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004420
4421 if ((rlist = PyList_New(0)) == NULL) {
4422 return NULL;
4423 }
4424
4425 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004426 objs = X509_STORE_get0_objects(store);
4427 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004428 X509_OBJECT *obj;
4429 X509 *cert;
4430
Christian Heimes598894f2016-09-05 23:19:05 +02004431 obj = sk_X509_OBJECT_value(objs, i);
4432 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004433 /* not a x509 cert */
4434 continue;
4435 }
4436 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004437 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004438 if (!X509_check_ca(cert)) {
4439 continue;
4440 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004441 if (binary_form) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004442 ci = _certificate_to_der(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004443 } else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004444 ci = _decode_certificate(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004445 }
4446 if (ci == NULL) {
4447 goto error;
4448 }
4449 if (PyList_Append(rlist, ci) == -1) {
4450 goto error;
4451 }
4452 Py_CLEAR(ci);
4453 }
4454 return rlist;
4455
4456 error:
4457 Py_XDECREF(ci);
4458 Py_XDECREF(rlist);
4459 return NULL;
4460}
4461
4462
Antoine Pitrou152efa22010-05-16 18:19:27 +00004463static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004464 {"check_hostname", (getter) get_check_hostname,
4465 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004466 {"_host_flags", (getter) get_host_flags,
4467 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004468 {"minimum_version", (getter) get_minimum_version,
4469 (setter) set_minimum_version, NULL},
4470 {"maximum_version", (getter) get_maximum_version,
4471 (setter) set_maximum_version, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004472 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4473 (setter) _PySSLContext_set_keylog_filename, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004474 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4475 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004476 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004477 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes39258d32021-04-17 11:36:35 +02004478#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02004479 {"num_tickets", (getter) get_num_tickets,
4480 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4481#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004482 {"options", (getter) get_options,
4483 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004484 {"post_handshake_auth", (getter) get_post_handshake_auth,
4485#ifdef TLS1_3_VERSION
4486 (setter) set_post_handshake_auth,
4487#else
4488 NULL,
4489#endif
4490 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004491 {"protocol", (getter) get_protocol,
4492 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004493 {"verify_flags", (getter) get_verify_flags,
4494 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004495 {"verify_mode", (getter) get_verify_mode,
4496 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004497 {"security_level", (getter) get_security_level,
4498 NULL, PySSLContext_security_level_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004499 {NULL}, /* sentinel */
4500};
4501
4502static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004503 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4504 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4505 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4506 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004507 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4508 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4509 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4510 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4511 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4512 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004513 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4514 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004515 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004516 {NULL, NULL} /* sentinel */
4517};
4518
Christian Heimes5c36da72020-11-20 09:40:12 +01004519static PyType_Slot PySSLContext_slots[] = {
4520 {Py_tp_methods, context_methods},
4521 {Py_tp_getset, context_getsetlist},
4522 {Py_tp_new, _ssl__SSLContext},
4523 {Py_tp_dealloc, context_dealloc},
4524 {Py_tp_traverse, context_traverse},
4525 {Py_tp_clear, context_clear},
4526 {0, 0},
4527};
4528
4529static PyType_Spec PySSLContext_spec = {
4530 "_ssl._SSLContext",
4531 sizeof(PySSLContext),
4532 0,
4533 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
4534 PySSLContext_slots,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004535};
4536
4537
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004538/*
4539 * MemoryBIO objects
4540 */
4541
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004542/*[clinic input]
4543@classmethod
4544_ssl.MemoryBIO.__new__
4545
4546[clinic start generated code]*/
4547
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004548static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004549_ssl_MemoryBIO_impl(PyTypeObject *type)
4550/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004551{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004552 BIO *bio;
4553 PySSLMemoryBIO *self;
4554
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004555 bio = BIO_new(BIO_s_mem());
4556 if (bio == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004557 PyErr_SetString(PyExc_MemoryError, "failed to allocate BIO");
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004558 return NULL;
4559 }
4560 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4561 * just that no data is currently available. The SSL routines should retry
4562 * the read, which we can achieve by calling BIO_set_retry_read(). */
4563 BIO_set_retry_read(bio);
4564 BIO_set_mem_eof_return(bio, -1);
4565
4566 assert(type != NULL && type->tp_alloc != NULL);
4567 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4568 if (self == NULL) {
4569 BIO_free(bio);
4570 return NULL;
4571 }
4572 self->bio = bio;
4573 self->eof_written = 0;
4574
4575 return (PyObject *) self;
4576}
4577
4578static void
4579memory_bio_dealloc(PySSLMemoryBIO *self)
4580{
Christian Heimes5c36da72020-11-20 09:40:12 +01004581 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004582 BIO_free(self->bio);
4583 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004584 Py_DECREF(tp);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004585}
4586
4587static PyObject *
4588memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4589{
Segev Finer5cff6372017-07-27 01:19:17 +03004590 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004591}
4592
4593PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4594"The number of bytes pending in the memory BIO.");
4595
4596static PyObject *
4597memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4598{
4599 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4600 && self->eof_written);
4601}
4602
4603PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4604"Whether the memory BIO is at EOF.");
4605
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004606/*[clinic input]
4607_ssl.MemoryBIO.read
4608 size as len: int = -1
4609 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004610
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004611Read up to size bytes from the memory BIO.
4612
4613If size is not specified, read the entire buffer.
4614If the return value is an empty bytes instance, this means either
4615EOF or that no data is available. Use the "eof" property to
4616distinguish between the two.
4617[clinic start generated code]*/
4618
4619static PyObject *
4620_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4621/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4622{
4623 int avail, nbytes;
4624 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004625
Segev Finer5cff6372017-07-27 01:19:17 +03004626 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004627 if ((len < 0) || (len > avail))
4628 len = avail;
4629
4630 result = PyBytes_FromStringAndSize(NULL, len);
4631 if ((result == NULL) || (len == 0))
4632 return result;
4633
4634 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004635 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004636 _sslmodulestate *state = get_state_mbio(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004637 Py_DECREF(result);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004638 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004639 return NULL;
4640 }
4641
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004642 /* There should never be any short reads but check anyway. */
4643 if (nbytes < len) {
4644 _PyBytes_Resize(&result, nbytes);
4645 }
4646
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004647 return result;
4648}
4649
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004650/*[clinic input]
4651_ssl.MemoryBIO.write
4652 b: Py_buffer
4653 /
4654
4655Writes the bytes b into the memory BIO.
4656
4657Returns the number of bytes written.
4658[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004659
4660static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004661_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4662/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004663{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004664 int nbytes;
4665
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004666 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004667 PyErr_Format(PyExc_OverflowError,
4668 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004669 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004670 }
4671
4672 if (self->eof_written) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004673 PyObject *module = PyType_GetModule(Py_TYPE(self));
4674 if (module == NULL)
4675 return NULL;
4676 PyErr_SetString(get_ssl_state(module)->PySSLErrorObject,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004677 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004678 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004679 }
4680
Segev Finer5cff6372017-07-27 01:19:17 +03004681 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004682 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004683 _sslmodulestate *state = get_state_mbio(self);
4684 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004685 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004686 }
4687
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004688 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004689}
4690
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004691/*[clinic input]
4692_ssl.MemoryBIO.write_eof
4693
4694Write an EOF marker to the memory BIO.
4695
4696When all data has been read, the "eof" property will be True.
4697[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004698
4699static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004700_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4701/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004702{
4703 self->eof_written = 1;
4704 /* After an EOF is written, a zero return from read() should be a real EOF
4705 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4706 BIO_clear_retry_flags(self->bio);
4707 BIO_set_mem_eof_return(self->bio, 0);
4708
4709 Py_RETURN_NONE;
4710}
4711
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004712static PyGetSetDef memory_bio_getsetlist[] = {
4713 {"pending", (getter) memory_bio_get_pending, NULL,
4714 PySSL_memory_bio_pending_doc},
4715 {"eof", (getter) memory_bio_get_eof, NULL,
4716 PySSL_memory_bio_eof_doc},
4717 {NULL}, /* sentinel */
4718};
4719
4720static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004721 _SSL_MEMORYBIO_READ_METHODDEF
4722 _SSL_MEMORYBIO_WRITE_METHODDEF
4723 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004724 {NULL, NULL} /* sentinel */
4725};
4726
Christian Heimes5c36da72020-11-20 09:40:12 +01004727static PyType_Slot PySSLMemoryBIO_slots[] = {
4728 {Py_tp_methods, memory_bio_methods},
4729 {Py_tp_getset, memory_bio_getsetlist},
4730 {Py_tp_new, _ssl_MemoryBIO},
4731 {Py_tp_dealloc, memory_bio_dealloc},
4732 {0, 0},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004733};
4734
Christian Heimes5c36da72020-11-20 09:40:12 +01004735static PyType_Spec PySSLMemoryBIO_spec = {
4736 "_ssl.MemoryBIO",
4737 sizeof(PySSLMemoryBIO),
4738 0,
4739 Py_TPFLAGS_DEFAULT,
4740 PySSLMemoryBIO_slots,
4741};
Antoine Pitrou152efa22010-05-16 18:19:27 +00004742
Christian Heimes99a65702016-09-10 23:44:53 +02004743/*
4744 * SSL Session object
4745 */
4746
4747static void
4748PySSLSession_dealloc(PySSLSession *self)
4749{
Christian Heimes5c36da72020-11-20 09:40:12 +01004750 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09004751 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004752 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004753 Py_XDECREF(self->ctx);
4754 if (self->session != NULL) {
4755 SSL_SESSION_free(self->session);
4756 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004757 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004758 Py_DECREF(tp);
Christian Heimes99a65702016-09-10 23:44:53 +02004759}
4760
4761static PyObject *
4762PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4763{
4764 int result;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004765 PyTypeObject *sesstype = ((PySSLSession*)left)->ctx->state->PySSLSession_Type;
Christian Heimes99a65702016-09-10 23:44:53 +02004766
4767 if (left == NULL || right == NULL) {
4768 PyErr_BadInternalCall();
4769 return NULL;
4770 }
4771
Christian Heimes7f1305e2021-04-17 20:06:38 +02004772 if (!Py_IS_TYPE(left, sesstype) || !Py_IS_TYPE(right, sesstype)) {
Christian Heimes99a65702016-09-10 23:44:53 +02004773 Py_RETURN_NOTIMPLEMENTED;
4774 }
4775
4776 if (left == right) {
4777 result = 0;
4778 } else {
4779 const unsigned char *left_id, *right_id;
4780 unsigned int left_len, right_len;
4781 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4782 &left_len);
4783 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4784 &right_len);
4785 if (left_len == right_len) {
4786 result = memcmp(left_id, right_id, left_len);
4787 } else {
4788 result = 1;
4789 }
4790 }
4791
4792 switch (op) {
4793 case Py_EQ:
4794 if (result == 0) {
4795 Py_RETURN_TRUE;
4796 } else {
4797 Py_RETURN_FALSE;
4798 }
4799 break;
4800 case Py_NE:
4801 if (result != 0) {
4802 Py_RETURN_TRUE;
4803 } else {
4804 Py_RETURN_FALSE;
4805 }
4806 break;
4807 case Py_LT:
4808 case Py_LE:
4809 case Py_GT:
4810 case Py_GE:
4811 Py_RETURN_NOTIMPLEMENTED;
4812 break;
4813 default:
4814 PyErr_BadArgument();
4815 return NULL;
4816 }
4817}
4818
4819static int
4820PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4821{
4822 Py_VISIT(self->ctx);
4823 return 0;
4824}
4825
4826static int
4827PySSLSession_clear(PySSLSession *self)
4828{
4829 Py_CLEAR(self->ctx);
4830 return 0;
4831}
4832
4833
4834static PyObject *
4835PySSLSession_get_time(PySSLSession *self, void *closure) {
4836 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4837}
4838
4839PyDoc_STRVAR(PySSLSession_get_time_doc,
4840"Session creation time (seconds since epoch).");
4841
4842
4843static PyObject *
4844PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4845 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4846}
4847
4848PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4849"Session timeout (delta in seconds).");
4850
4851
4852static PyObject *
4853PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4854 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4855 return PyLong_FromUnsignedLong(hint);
4856}
4857
4858PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4859"Ticket life time hint.");
4860
4861
4862static PyObject *
4863PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4864 const unsigned char *id;
4865 unsigned int len;
4866 id = SSL_SESSION_get_id(self->session, &len);
4867 return PyBytes_FromStringAndSize((const char *)id, len);
4868}
4869
4870PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4871"Session id");
4872
4873
4874static PyObject *
4875PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4876 if (SSL_SESSION_has_ticket(self->session)) {
4877 Py_RETURN_TRUE;
4878 } else {
4879 Py_RETURN_FALSE;
4880 }
4881}
4882
4883PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4884"Does the session contain a ticket?");
4885
4886
4887static PyGetSetDef PySSLSession_getsetlist[] = {
4888 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4889 PySSLSession_get_has_ticket_doc},
4890 {"id", (getter) PySSLSession_get_session_id, NULL,
4891 PySSLSession_get_session_id_doc},
4892 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4893 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4894 {"time", (getter) PySSLSession_get_time, NULL,
4895 PySSLSession_get_time_doc},
4896 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4897 PySSLSession_get_timeout_doc},
4898 {NULL}, /* sentinel */
4899};
4900
Christian Heimes5c36da72020-11-20 09:40:12 +01004901static PyType_Slot PySSLSession_slots[] = {
4902 {Py_tp_getset,PySSLSession_getsetlist},
4903 {Py_tp_richcompare, PySSLSession_richcompare},
4904 {Py_tp_dealloc, PySSLSession_dealloc},
4905 {Py_tp_traverse, PySSLSession_traverse},
4906 {Py_tp_clear, PySSLSession_clear},
4907 {0, 0},
4908};
4909
4910static PyType_Spec PySSLSession_spec = {
4911 "_ssl.SSLSession",
4912 sizeof(PySSLSession),
4913 0,
4914 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
4915 PySSLSession_slots,
Christian Heimes99a65702016-09-10 23:44:53 +02004916};
4917
4918
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004919/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004920/*[clinic input]
4921_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004922 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004923 entropy: double
4924 /
4925
4926Mix string into the OpenSSL PRNG state.
4927
4928entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304929string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004930[clinic start generated code]*/
4931
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004932static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004933_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004934/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004935{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004936 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004937 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004938
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004939 buf = (const char *)view->buf;
4940 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004941 do {
4942 written = Py_MIN(len, INT_MAX);
4943 RAND_add(buf, (int)written, entropy);
4944 buf += written;
4945 len -= written;
4946 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004947 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004948}
4949
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004950static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02004951PySSL_RAND(PyObject *module, int len, int pseudo)
Victor Stinner99c8b162011-05-24 12:05:19 +02004952{
4953 int ok;
4954 PyObject *bytes;
4955 unsigned long err;
4956 const char *errstr;
4957 PyObject *v;
4958
Victor Stinner1e81a392013-12-19 16:47:04 +01004959 if (len < 0) {
4960 PyErr_SetString(PyExc_ValueError, "num must be positive");
4961 return NULL;
4962 }
4963
Victor Stinner99c8b162011-05-24 12:05:19 +02004964 bytes = PyBytes_FromStringAndSize(NULL, len);
4965 if (bytes == NULL)
4966 return NULL;
4967 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02004968 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Victor Stinner99c8b162011-05-24 12:05:19 +02004969 if (ok == 0 || ok == 1)
4970 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4971 }
4972 else {
4973 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4974 if (ok == 1)
4975 return bytes;
4976 }
4977 Py_DECREF(bytes);
4978
4979 err = ERR_get_error();
4980 errstr = ERR_reason_error_string(err);
4981 v = Py_BuildValue("(ks)", err, errstr);
4982 if (v != NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004983 PyErr_SetObject(get_ssl_state(module)->PySSLErrorObject, v);
Victor Stinner99c8b162011-05-24 12:05:19 +02004984 Py_DECREF(v);
4985 }
4986 return NULL;
4987}
4988
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004989/*[clinic input]
4990_ssl.RAND_bytes
4991 n: int
4992 /
4993
4994Generate n cryptographically strong pseudo-random bytes.
4995[clinic start generated code]*/
4996
Victor Stinner99c8b162011-05-24 12:05:19 +02004997static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004998_ssl_RAND_bytes_impl(PyObject *module, int n)
4999/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005000{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005001 return PySSL_RAND(module, n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005002}
5003
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005004/*[clinic input]
5005_ssl.RAND_pseudo_bytes
5006 n: int
5007 /
5008
5009Generate n pseudo-random bytes.
5010
5011Return a pair (bytes, is_cryptographic). is_cryptographic is True
5012if the bytes generated are cryptographically strong.
5013[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005014
5015static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005016_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5017/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005018{
Christian Heimes2875c602021-04-19 07:27:10 +02005019 PY_SSL_DEPRECATED("RAND_pseudo_bytes", 1, NULL);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005020 return PySSL_RAND(module, n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005021}
5022
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005023/*[clinic input]
5024_ssl.RAND_status
5025
5026Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5027
5028It is necessary to seed the PRNG with RAND_add() on some platforms before
5029using the ssl() function.
5030[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005031
5032static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005033_ssl_RAND_status_impl(PyObject *module)
5034/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005035{
Christian Heimes217cfd12007-12-02 14:31:20 +00005036 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005037}
5038
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005039/*[clinic input]
5040_ssl.get_default_verify_paths
5041
5042Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5043
5044The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5045[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005046
5047static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005048_ssl_get_default_verify_paths_impl(PyObject *module)
5049/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005050{
5051 PyObject *ofile_env = NULL;
5052 PyObject *ofile = NULL;
5053 PyObject *odir_env = NULL;
5054 PyObject *odir = NULL;
5055
Benjamin Petersond113c962015-07-18 10:59:13 -07005056#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005057 const char *tmp = (info); \
5058 target = NULL; \
5059 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5060 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5061 target = PyBytes_FromString(tmp); } \
5062 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005063 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005064
Benjamin Petersond113c962015-07-18 10:59:13 -07005065 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5066 CONVERT(X509_get_default_cert_file(), ofile);
5067 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5068 CONVERT(X509_get_default_cert_dir(), odir);
5069#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005070
Christian Heimes200bb1b2013-06-14 15:14:29 +02005071 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005072
5073 error:
5074 Py_XDECREF(ofile_env);
5075 Py_XDECREF(ofile);
5076 Py_XDECREF(odir_env);
5077 Py_XDECREF(odir);
5078 return NULL;
5079}
5080
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005081static PyObject*
Christian Heimes7f1305e2021-04-17 20:06:38 +02005082asn1obj2py(_sslmodulestate *state, ASN1_OBJECT *obj)
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005083{
5084 int nid;
5085 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005086
5087 nid = OBJ_obj2nid(obj);
5088 if (nid == NID_undef) {
5089 PyErr_Format(PyExc_ValueError, "Unknown object");
5090 return NULL;
5091 }
5092 sn = OBJ_nid2sn(nid);
5093 ln = OBJ_nid2ln(nid);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005094 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(state, obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005095}
5096
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005097/*[clinic input]
5098_ssl.txt2obj
5099 txt: str
5100 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005101
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005102Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5103
5104By default objects are looked up by OID. With name=True short and
5105long name are also matched.
5106[clinic start generated code]*/
5107
5108static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005109_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5110/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005111{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005112 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005113 ASN1_OBJECT *obj;
5114
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005115 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5116 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005117 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005118 return NULL;
5119 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005120 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005121 ASN1_OBJECT_free(obj);
5122 return result;
5123}
5124
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005125/*[clinic input]
5126_ssl.nid2obj
5127 nid: int
5128 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005129
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005130Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5131[clinic start generated code]*/
5132
5133static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005134_ssl_nid2obj_impl(PyObject *module, int nid)
5135/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005136{
5137 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005138 ASN1_OBJECT *obj;
5139
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005140 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005141 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005142 return NULL;
5143 }
5144 obj = OBJ_nid2obj(nid);
5145 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005146 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005147 return NULL;
5148 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005149 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005150 ASN1_OBJECT_free(obj);
5151 return result;
5152}
5153
Christian Heimes46bebee2013-06-09 19:03:31 +02005154#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005155
5156static PyObject*
5157certEncodingType(DWORD encodingType)
5158{
5159 static PyObject *x509_asn = NULL;
5160 static PyObject *pkcs_7_asn = NULL;
5161
5162 if (x509_asn == NULL) {
5163 x509_asn = PyUnicode_InternFromString("x509_asn");
5164 if (x509_asn == NULL)
5165 return NULL;
5166 }
5167 if (pkcs_7_asn == NULL) {
5168 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5169 if (pkcs_7_asn == NULL)
5170 return NULL;
5171 }
5172 switch(encodingType) {
5173 case X509_ASN_ENCODING:
5174 Py_INCREF(x509_asn);
5175 return x509_asn;
5176 case PKCS_7_ASN_ENCODING:
5177 Py_INCREF(pkcs_7_asn);
5178 return pkcs_7_asn;
5179 default:
5180 return PyLong_FromLong(encodingType);
5181 }
5182}
5183
5184static PyObject*
5185parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5186{
5187 CERT_ENHKEY_USAGE *usage;
5188 DWORD size, error, i;
5189 PyObject *retval;
5190
5191 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5192 error = GetLastError();
5193 if (error == CRYPT_E_NOT_FOUND) {
5194 Py_RETURN_TRUE;
5195 }
5196 return PyErr_SetFromWindowsErr(error);
5197 }
5198
5199 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5200 if (usage == NULL) {
5201 return PyErr_NoMemory();
5202 }
5203
5204 /* Now get the actual enhanced usage property */
5205 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5206 PyMem_Free(usage);
5207 error = GetLastError();
5208 if (error == CRYPT_E_NOT_FOUND) {
5209 Py_RETURN_TRUE;
5210 }
5211 return PyErr_SetFromWindowsErr(error);
5212 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005213 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005214 if (retval == NULL) {
5215 goto error;
5216 }
5217 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5218 if (usage->rgpszUsageIdentifier[i]) {
5219 PyObject *oid;
5220 int err;
5221 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5222 if (oid == NULL) {
5223 Py_CLEAR(retval);
5224 goto error;
5225 }
5226 err = PySet_Add(retval, oid);
5227 Py_DECREF(oid);
5228 if (err == -1) {
5229 Py_CLEAR(retval);
5230 goto error;
5231 }
5232 }
5233 }
5234 error:
5235 PyMem_Free(usage);
5236 return retval;
5237}
5238
kctherookied93fbbf2019-03-29 00:59:06 +07005239static HCERTSTORE
5240ssl_collect_certificates(const char *store_name)
5241{
5242/* this function collects the system certificate stores listed in
5243 * system_stores into a collection certificate store for being
5244 * enumerated. The store must be readable to be added to the
5245 * store collection.
5246 */
5247
5248 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5249 static DWORD system_stores[] = {
5250 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5251 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5252 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5253 CERT_SYSTEM_STORE_CURRENT_USER,
5254 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5255 CERT_SYSTEM_STORE_SERVICES,
5256 CERT_SYSTEM_STORE_USERS};
5257 size_t i, storesAdded;
5258 BOOL result;
5259
5260 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5261 (HCRYPTPROV)NULL, 0, NULL);
5262 if (!hCollectionStore) {
5263 return NULL;
5264 }
5265 storesAdded = 0;
5266 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5267 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5268 (HCRYPTPROV)NULL,
5269 CERT_STORE_READONLY_FLAG |
5270 system_stores[i], store_name);
5271 if (hSystemStore) {
5272 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5273 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5274 if (result) {
5275 ++storesAdded;
5276 }
neoneneed701292019-09-09 21:33:43 +09005277 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005278 }
5279 }
5280 if (storesAdded == 0) {
5281 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5282 return NULL;
5283 }
5284
5285 return hCollectionStore;
5286}
5287
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005288/*[clinic input]
5289_ssl.enum_certificates
5290 store_name: str
5291
5292Retrieve certificates from Windows' cert store.
5293
5294store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5295more cert storages, too. The function returns a list of (bytes,
5296encoding_type, trust) tuples. The encoding_type flag can be interpreted
5297with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5298a set of OIDs or the boolean True.
5299[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005300
Christian Heimes46bebee2013-06-09 19:03:31 +02005301static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005302_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5303/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005304{
kctherookied93fbbf2019-03-29 00:59:06 +07005305 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005306 PCCERT_CONTEXT pCertCtx = NULL;
5307 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005308 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005309
Christian Heimes915cd3f2019-09-09 18:06:55 +02005310 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005311 if (result == NULL) {
5312 return NULL;
5313 }
kctherookied93fbbf2019-03-29 00:59:06 +07005314 hCollectionStore = ssl_collect_certificates(store_name);
5315 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005316 Py_DECREF(result);
5317 return PyErr_SetFromWindowsErr(GetLastError());
5318 }
5319
kctherookied93fbbf2019-03-29 00:59:06 +07005320 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005321 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5322 pCertCtx->cbCertEncoded);
5323 if (!cert) {
5324 Py_CLEAR(result);
5325 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005326 }
Christian Heimes44109d72013-11-22 01:51:30 +01005327 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5328 Py_CLEAR(result);
5329 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005330 }
Christian Heimes44109d72013-11-22 01:51:30 +01005331 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5332 if (keyusage == Py_True) {
5333 Py_DECREF(keyusage);
5334 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005335 }
Christian Heimes44109d72013-11-22 01:51:30 +01005336 if (keyusage == NULL) {
5337 Py_CLEAR(result);
5338 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005339 }
Christian Heimes44109d72013-11-22 01:51:30 +01005340 if ((tup = PyTuple_New(3)) == NULL) {
5341 Py_CLEAR(result);
5342 break;
5343 }
5344 PyTuple_SET_ITEM(tup, 0, cert);
5345 cert = NULL;
5346 PyTuple_SET_ITEM(tup, 1, enc);
5347 enc = NULL;
5348 PyTuple_SET_ITEM(tup, 2, keyusage);
5349 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005350 if (PySet_Add(result, tup) == -1) {
5351 Py_CLEAR(result);
5352 Py_CLEAR(tup);
5353 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005354 }
5355 Py_CLEAR(tup);
5356 }
5357 if (pCertCtx) {
5358 /* loop ended with an error, need to clean up context manually */
5359 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005360 }
5361
5362 /* In error cases cert, enc and tup may not be NULL */
5363 Py_XDECREF(cert);
5364 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005365 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005366 Py_XDECREF(tup);
5367
kctherookied93fbbf2019-03-29 00:59:06 +07005368 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5369 associated with the store, in this case our collection store and the
5370 associated system stores. */
5371 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005372 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005373 Py_XDECREF(result);
5374 return PyErr_SetFromWindowsErr(GetLastError());
5375 }
kctherookied93fbbf2019-03-29 00:59:06 +07005376
Christian Heimes915cd3f2019-09-09 18:06:55 +02005377 /* convert set to list */
5378 if (result == NULL) {
5379 return NULL;
5380 } else {
5381 PyObject *lst = PySequence_List(result);
5382 Py_DECREF(result);
5383 return lst;
5384 }
Christian Heimes44109d72013-11-22 01:51:30 +01005385}
5386
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005387/*[clinic input]
5388_ssl.enum_crls
5389 store_name: str
5390
5391Retrieve CRLs from Windows' cert store.
5392
5393store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5394more cert storages, too. The function returns a list of (bytes,
5395encoding_type) tuples. The encoding_type flag can be interpreted with
5396X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5397[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005398
5399static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005400_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5401/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005402{
kctherookied93fbbf2019-03-29 00:59:06 +07005403 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005404 PCCRL_CONTEXT pCrlCtx = NULL;
5405 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5406 PyObject *result = NULL;
5407
Christian Heimes915cd3f2019-09-09 18:06:55 +02005408 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005409 if (result == NULL) {
5410 return NULL;
5411 }
kctherookied93fbbf2019-03-29 00:59:06 +07005412 hCollectionStore = ssl_collect_certificates(store_name);
5413 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005414 Py_DECREF(result);
5415 return PyErr_SetFromWindowsErr(GetLastError());
5416 }
Christian Heimes44109d72013-11-22 01:51:30 +01005417
kctherookied93fbbf2019-03-29 00:59:06 +07005418 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005419 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5420 pCrlCtx->cbCrlEncoded);
5421 if (!crl) {
5422 Py_CLEAR(result);
5423 break;
5424 }
5425 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5426 Py_CLEAR(result);
5427 break;
5428 }
5429 if ((tup = PyTuple_New(2)) == NULL) {
5430 Py_CLEAR(result);
5431 break;
5432 }
5433 PyTuple_SET_ITEM(tup, 0, crl);
5434 crl = NULL;
5435 PyTuple_SET_ITEM(tup, 1, enc);
5436 enc = NULL;
5437
Christian Heimes915cd3f2019-09-09 18:06:55 +02005438 if (PySet_Add(result, tup) == -1) {
5439 Py_CLEAR(result);
5440 Py_CLEAR(tup);
5441 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005442 }
5443 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005444 }
Christian Heimes44109d72013-11-22 01:51:30 +01005445 if (pCrlCtx) {
5446 /* loop ended with an error, need to clean up context manually */
5447 CertFreeCRLContext(pCrlCtx);
5448 }
5449
5450 /* In error cases cert, enc and tup may not be NULL */
5451 Py_XDECREF(crl);
5452 Py_XDECREF(enc);
5453 Py_XDECREF(tup);
5454
kctherookied93fbbf2019-03-29 00:59:06 +07005455 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5456 associated with the store, in this case our collection store and the
5457 associated system stores. */
5458 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005459 /* This error case might shadow another exception.*/
5460 Py_XDECREF(result);
5461 return PyErr_SetFromWindowsErr(GetLastError());
5462 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005463 /* convert set to list */
5464 if (result == NULL) {
5465 return NULL;
5466 } else {
5467 PyObject *lst = PySequence_List(result);
5468 Py_DECREF(result);
5469 return lst;
5470 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005471}
Christian Heimes44109d72013-11-22 01:51:30 +01005472
5473#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005474
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005475/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005476static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005477 _SSL__TEST_DECODE_CERT_METHODDEF
5478 _SSL_RAND_ADD_METHODDEF
5479 _SSL_RAND_BYTES_METHODDEF
5480 _SSL_RAND_PSEUDO_BYTES_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005481 _SSL_RAND_STATUS_METHODDEF
5482 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5483 _SSL_ENUM_CERTIFICATES_METHODDEF
5484 _SSL_ENUM_CRLS_METHODDEF
5485 _SSL_TXT2OBJ_METHODDEF
5486 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005487 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005488};
5489
5490
Christian Heimes7f1305e2021-04-17 20:06:38 +02005491PyDoc_STRVAR(module_doc,
5492"Implementation module for SSL socket operations. See the socket module\n\
5493for documentation.");
Christian Heimes5c36da72020-11-20 09:40:12 +01005494
5495static int
5496sslmodule_init_exceptions(PyObject *module)
5497{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005498 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005499 PyObject *bases = NULL;
5500
Christian Heimes7f1305e2021-04-17 20:06:38 +02005501#define add_exception(exc, name, doc, base) \
5502do { \
5503 (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5504 if ((state) == NULL) goto error; \
5505 if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
Christian Heimes5c36da72020-11-20 09:40:12 +01005506} while(0)
5507
Christian Heimes7f1305e2021-04-17 20:06:38 +02005508 state->PySSLErrorObject = PyType_FromSpecWithBases(
5509 &sslerror_type_spec, PyExc_OSError);
5510 if (state->PySSLErrorObject == NULL) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005511 goto error;
5512 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005513 if (PyModule_AddObjectRef(module, "SSLError", state->PySSLErrorObject) < 0) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005514 goto error;
5515 }
5516
5517 /* ssl.CertificateError used to be a subclass of ValueError */
Christian Heimes7f1305e2021-04-17 20:06:38 +02005518 bases = PyTuple_Pack(2, state->PySSLErrorObject, PyExc_ValueError);
Christian Heimes5c36da72020-11-20 09:40:12 +01005519 if (bases == NULL) {
5520 goto error;
5521 }
5522 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005523 state->PySSLCertVerificationErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005524 "SSLCertVerificationError",
5525 SSLCertVerificationError_doc,
5526 bases
5527 );
5528 Py_CLEAR(bases);
5529
5530 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005531 state->PySSLZeroReturnErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005532 "SSLZeroReturnError",
5533 SSLZeroReturnError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005534 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005535 );
5536
5537 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005538 state->PySSLWantWriteErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005539 "SSLWantWriteError",
5540 SSLWantWriteError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005541 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005542 );
5543
5544 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005545 state->PySSLWantReadErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005546 "SSLWantReadError",
5547 SSLWantReadError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005548 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005549 );
5550
5551 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005552 state->PySSLSyscallErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005553 "SSLSyscallError",
5554 SSLSyscallError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005555 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005556 );
5557
5558 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005559 state->PySSLEOFErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005560 "SSLEOFError",
5561 SSLEOFError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005562 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005563 );
5564#undef add_exception
5565
5566 return 0;
5567 error:
5568 Py_XDECREF(bases);
5569 return -1;
5570}
5571
5572static int
5573sslmodule_init_socketapi(PyObject *module)
5574{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005575 _sslmodulestate *state = get_ssl_state(module);
5576 PySocketModule_APIObject *sockmod = PySocketModule_ImportModuleAndAPI();
Christian Heimes5c36da72020-11-20 09:40:12 +01005577
Christian Heimes7f1305e2021-04-17 20:06:38 +02005578 if ((sockmod == NULL) || (sockmod->Sock_Type == NULL)) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005579 return -1;
Christian Heimes5c36da72020-11-20 09:40:12 +01005580 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005581 state->Sock_Type = sockmod->Sock_Type;
5582 Py_INCREF(state->Sock_Type);
Christian Heimes5c36da72020-11-20 09:40:12 +01005583 return 0;
5584}
Christian Heimesc941e622017-09-05 15:47:11 +02005585
Christian Heimes5c36da72020-11-20 09:40:12 +01005586static int
5587sslmodule_init_constants(PyObject *m)
5588{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005589
Christian Heimes892d66e2018-01-29 14:10:18 +01005590 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5591 PY_SSL_DEFAULT_CIPHER_STRING);
5592
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005593 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5594 PY_SSL_ERROR_ZERO_RETURN);
5595 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5596 PY_SSL_ERROR_WANT_READ);
5597 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5598 PY_SSL_ERROR_WANT_WRITE);
5599 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5600 PY_SSL_ERROR_WANT_X509_LOOKUP);
5601 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5602 PY_SSL_ERROR_SYSCALL);
5603 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5604 PY_SSL_ERROR_SSL);
5605 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5606 PY_SSL_ERROR_WANT_CONNECT);
5607 /* non ssl.h errorcodes */
5608 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5609 PY_SSL_ERROR_EOF);
5610 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5611 PY_SSL_ERROR_INVALID_ERROR_CODE);
5612 /* cert requirements */
5613 PyModule_AddIntConstant(m, "CERT_NONE",
5614 PY_SSL_CERT_NONE);
5615 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5616 PY_SSL_CERT_OPTIONAL);
5617 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5618 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005619 /* CRL verification for verification_flags */
5620 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5621 0);
5622 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5623 X509_V_FLAG_CRL_CHECK);
5624 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5625 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5626 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5627 X509_V_FLAG_X509_STRICT);
Chris Burre0b4aa02021-03-18 09:24:01 +01005628 PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
5629 X509_V_FLAG_ALLOW_PROXY_CERTS);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005630 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5631 X509_V_FLAG_TRUSTED_FIRST);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005632
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005633 /* Alert Descriptions from ssl.h */
5634 /* note RESERVED constants no longer intended for use have been removed */
5635 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5636
5637#define ADD_AD_CONSTANT(s) \
5638 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5639 SSL_AD_##s)
5640
5641 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5642 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5643 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5644 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5645 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5646 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5647 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5648 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5649 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5650 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5651 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5652 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5653 ADD_AD_CONSTANT(UNKNOWN_CA);
5654 ADD_AD_CONSTANT(ACCESS_DENIED);
5655 ADD_AD_CONSTANT(DECODE_ERROR);
5656 ADD_AD_CONSTANT(DECRYPT_ERROR);
5657 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5658 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5659 ADD_AD_CONSTANT(INTERNAL_ERROR);
5660 ADD_AD_CONSTANT(USER_CANCELLED);
5661 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005662 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005663#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5664 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5665#endif
5666#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5667 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5668#endif
5669#ifdef SSL_AD_UNRECOGNIZED_NAME
5670 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5671#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005672#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5673 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5674#endif
5675#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5676 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5677#endif
5678#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5679 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5680#endif
5681
5682#undef ADD_AD_CONSTANT
5683
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005684 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005685#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005686 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5687 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005688#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005689#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005690 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5691 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005692#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005693 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005694 PY_SSL_VERSION_TLS);
5695 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5696 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005697 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5698 PY_SSL_VERSION_TLS_CLIENT);
5699 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5700 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005701 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5702 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005703 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5704 PY_SSL_VERSION_TLS1_1);
5705 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5706 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005707
Antoine Pitroub5218772010-05-21 09:56:06 +00005708 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005709 PyModule_AddIntConstant(m, "OP_ALL",
5710 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005711 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5712 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5713 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005714 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5715 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005716#ifdef SSL_OP_NO_TLSv1_3
5717 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5718#else
5719 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5720#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005721 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5722 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005723 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005724 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005725#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005726 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005727#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005728#ifdef SSL_OP_NO_COMPRESSION
5729 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5730 SSL_OP_NO_COMPRESSION);
5731#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005732#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5733 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5734 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5735#endif
Christian Heimes67c48012018-05-15 16:25:40 -04005736#ifdef SSL_OP_NO_RENEGOTIATION
5737 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5738 SSL_OP_NO_RENEGOTIATION);
5739#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02005740#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
5741 PyModule_AddIntConstant(m, "OP_IGNORE_UNEXPECTED_EOF",
5742 SSL_OP_IGNORE_UNEXPECTED_EOF);
5743#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005744
Christian Heimes61d478c2018-01-27 15:51:38 +01005745#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5746 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5747 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5748#endif
5749#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5750 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5751 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5752#endif
5753#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5754 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5755 X509_CHECK_FLAG_NO_WILDCARDS);
5756#endif
5757#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5758 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5759 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5760#endif
5761#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5762 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5763 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5764#endif
5765#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5766 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5767 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5768#endif
5769
Christian Heimes698dde12018-02-27 11:54:43 +01005770 /* protocol versions */
5771 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5772 PY_PROTO_MINIMUM_SUPPORTED);
5773 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5774 PY_PROTO_MAXIMUM_SUPPORTED);
5775 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5776 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5777 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5778 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5779 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005780
Victor Stinnerb37672d2018-11-22 03:37:50 +01005781#define addbool(m, key, value) \
5782 do { \
5783 PyObject *bool_obj = (value) ? Py_True : Py_False; \
5784 Py_INCREF(bool_obj); \
5785 PyModule_AddObject((m), (key), bool_obj); \
5786 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01005787
Christian Heimes698dde12018-02-27 11:54:43 +01005788 addbool(m, "HAS_SNI", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005789 addbool(m, "HAS_TLS_UNIQUE", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005790 addbool(m, "HAS_ECDH", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005791 addbool(m, "HAS_NPN", 0);
Christian Heimes698dde12018-02-27 11:54:43 +01005792 addbool(m, "HAS_ALPN", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005793
5794#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5795 addbool(m, "HAS_SSLv2", 1);
5796#else
5797 addbool(m, "HAS_SSLv2", 0);
5798#endif
5799
5800#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5801 addbool(m, "HAS_SSLv3", 1);
5802#else
5803 addbool(m, "HAS_SSLv3", 0);
5804#endif
5805
5806#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5807 addbool(m, "HAS_TLSv1", 1);
5808#else
5809 addbool(m, "HAS_TLSv1", 0);
5810#endif
5811
5812#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5813 addbool(m, "HAS_TLSv1_1", 1);
5814#else
5815 addbool(m, "HAS_TLSv1_1", 0);
5816#endif
5817
5818#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5819 addbool(m, "HAS_TLSv1_2", 1);
5820#else
5821 addbool(m, "HAS_TLSv1_2", 0);
5822#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005823
Christian Heimescb5b68a2017-09-07 18:07:00 -07005824#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005825 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005826#else
Christian Heimes698dde12018-02-27 11:54:43 +01005827 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005828#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005829
Christian Heimes5c36da72020-11-20 09:40:12 +01005830 return 0;
5831}
5832
Christian Heimes7f1305e2021-04-17 20:06:38 +02005833static int
5834sslmodule_init_errorcodes(PyObject *module)
5835{
5836 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005837
Christian Heimes7f1305e2021-04-17 20:06:38 +02005838 struct py_ssl_error_code *errcode;
5839 struct py_ssl_library_code *libcode;
Christian Heimes5c36da72020-11-20 09:40:12 +01005840
Christian Heimes7f1305e2021-04-17 20:06:38 +02005841 /* Mappings for error codes */
5842 state->err_codes_to_names = PyDict_New();
5843 if (state->err_codes_to_names == NULL)
5844 return -1;
5845 state->err_names_to_codes = PyDict_New();
5846 if (state->err_names_to_codes == NULL)
5847 return -1;
5848 state->lib_codes_to_names = PyDict_New();
5849 if (state->lib_codes_to_names == NULL)
5850 return -1;
5851
5852 errcode = error_codes;
5853 while (errcode->mnemonic != NULL) {
5854 PyObject *mnemo, *key;
5855 mnemo = PyUnicode_FromString(errcode->mnemonic);
5856 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5857 if (mnemo == NULL || key == NULL)
5858 return -1;
5859 if (PyDict_SetItem(state->err_codes_to_names, key, mnemo))
5860 return -1;
5861 if (PyDict_SetItem(state->err_names_to_codes, mnemo, key))
5862 return -1;
5863 Py_DECREF(key);
5864 Py_DECREF(mnemo);
5865 errcode++;
5866 }
5867
5868 libcode = library_codes;
5869 while (libcode->library != NULL) {
5870 PyObject *mnemo, *key;
5871 key = PyLong_FromLong(libcode->code);
5872 mnemo = PyUnicode_FromString(libcode->library);
5873 if (key == NULL || mnemo == NULL)
5874 return -1;
5875 if (PyDict_SetItem(state->lib_codes_to_names, key, mnemo))
5876 return -1;
5877 Py_DECREF(key);
5878 Py_DECREF(mnemo);
5879 libcode++;
5880 }
5881
5882 if (PyModule_AddObjectRef(module, "err_codes_to_names", state->err_codes_to_names))
5883 return -1;
5884 if (PyModule_AddObjectRef(module, "err_names_to_codes", state->err_names_to_codes))
5885 return -1;
5886 if (PyModule_AddObjectRef(module, "lib_codes_to_names", state->lib_codes_to_names))
5887 return -1;
5888
5889 return 0;
5890}
5891
5892static void
5893parse_openssl_version(unsigned long libver,
5894 unsigned int *major, unsigned int *minor,
5895 unsigned int *fix, unsigned int *patch,
5896 unsigned int *status)
5897{
5898 *status = libver & 0xF;
5899 libver >>= 4;
5900 *patch = libver & 0xFF;
5901 libver >>= 8;
5902 *fix = libver & 0xFF;
5903 libver >>= 8;
5904 *minor = libver & 0xFF;
5905 libver >>= 8;
5906 *major = libver & 0xFF;
5907}
5908
5909static int
5910sslmodule_init_versioninfo(PyObject *m)
5911{
5912 PyObject *r;
5913 unsigned long libver;
5914 unsigned int major, minor, fix, patch, status;
5915
5916 /* OpenSSL version */
5917 /* SSLeay() gives us the version of the library linked against,
5918 which could be different from the headers version.
5919 */
5920 libver = OpenSSL_version_num();
5921 r = PyLong_FromUnsignedLong(libver);
5922 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5923 return -1;
5924
5925 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5926 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5927 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5928 return -1;
5929
5930 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
5931 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5932 return -1;
5933
5934 libver = OPENSSL_VERSION_NUMBER;
5935 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5936 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5937 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5938 return -1;
5939
5940 return 0;
5941}
5942
5943static int
5944sslmodule_init_types(PyObject *module)
5945{
5946 _sslmodulestate *state = get_ssl_state(module);
5947
5948 state->PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5949 module, &PySSLContext_spec, NULL
5950 );
5951 if (state->PySSLContext_Type == NULL)
5952 return -1;
5953
5954 state->PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5955 module, &PySSLSocket_spec, NULL
5956 );
5957 if (state->PySSLSocket_Type == NULL)
5958 return -1;
5959
5960 state->PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5961 module, &PySSLMemoryBIO_spec, NULL
5962 );
5963 if (state->PySSLMemoryBIO_Type == NULL)
5964 return -1;
5965
5966 state->PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5967 module, &PySSLSession_spec, NULL
5968 );
5969 if (state->PySSLSession_Type == NULL)
5970 return -1;
5971
5972 if (PyModule_AddType(module, state->PySSLContext_Type))
5973 return -1;
5974 if (PyModule_AddType(module, state->PySSLSocket_Type))
5975 return -1;
5976 if (PyModule_AddType(module, state->PySSLMemoryBIO_Type))
5977 return -1;
5978 if (PyModule_AddType(module, state->PySSLSession_Type))
5979 return -1;
5980
5981 return 0;
5982}
5983
5984static PyModuleDef_Slot sslmodule_slots[] = {
5985 {Py_mod_exec, sslmodule_init_types},
5986 {Py_mod_exec, sslmodule_init_exceptions},
5987 {Py_mod_exec, sslmodule_init_socketapi},
5988 {Py_mod_exec, sslmodule_init_errorcodes},
5989 {Py_mod_exec, sslmodule_init_constants},
5990 {Py_mod_exec, sslmodule_init_versioninfo},
5991 {0, NULL}
5992};
5993
5994static int
5995sslmodule_traverse(PyObject *m, visitproc visit, void *arg)
5996{
5997 _sslmodulestate *state = get_ssl_state(m);
5998
5999 Py_VISIT(state->PySSLContext_Type);
6000 Py_VISIT(state->PySSLSocket_Type);
6001 Py_VISIT(state->PySSLMemoryBIO_Type);
6002 Py_VISIT(state->PySSLSession_Type);
6003 Py_VISIT(state->PySSLErrorObject);
6004 Py_VISIT(state->PySSLCertVerificationErrorObject);
6005 Py_VISIT(state->PySSLZeroReturnErrorObject);
6006 Py_VISIT(state->PySSLWantReadErrorObject);
6007 Py_VISIT(state->PySSLWantWriteErrorObject);
6008 Py_VISIT(state->PySSLSyscallErrorObject);
6009 Py_VISIT(state->PySSLEOFErrorObject);
6010 Py_VISIT(state->err_codes_to_names);
6011 Py_VISIT(state->err_names_to_codes);
6012 Py_VISIT(state->lib_codes_to_names);
6013 Py_VISIT(state->Sock_Type);
6014
6015 return 0;
6016}
6017
6018static int
6019sslmodule_clear(PyObject *m)
6020{
6021 _sslmodulestate *state = get_ssl_state(m);
6022
6023 Py_CLEAR(state->PySSLContext_Type);
6024 Py_CLEAR(state->PySSLSocket_Type);
6025 Py_CLEAR(state->PySSLMemoryBIO_Type);
6026 Py_CLEAR(state->PySSLSession_Type);
6027 Py_CLEAR(state->PySSLErrorObject);
6028 Py_CLEAR(state->PySSLCertVerificationErrorObject);
6029 Py_CLEAR(state->PySSLZeroReturnErrorObject);
6030 Py_CLEAR(state->PySSLWantReadErrorObject);
6031 Py_CLEAR(state->PySSLWantWriteErrorObject);
6032 Py_CLEAR(state->PySSLSyscallErrorObject);
6033 Py_CLEAR(state->PySSLEOFErrorObject);
6034 Py_CLEAR(state->err_codes_to_names);
6035 Py_CLEAR(state->err_names_to_codes);
6036 Py_CLEAR(state->lib_codes_to_names);
6037 Py_CLEAR(state->Sock_Type);
6038
6039 return 0;
6040}
6041
6042static void
6043sslmodule_free(void *m)
6044{
6045 sslmodule_clear((PyObject *)m);
6046}
6047
6048static struct PyModuleDef _sslmodule_def = {
Christian Heimes5c36da72020-11-20 09:40:12 +01006049 PyModuleDef_HEAD_INIT,
Christian Heimes7f1305e2021-04-17 20:06:38 +02006050 .m_name = "_ssl",
6051 .m_doc = module_doc,
6052 .m_size = sizeof(_sslmodulestate),
6053 .m_methods = PySSL_methods,
6054 .m_slots = sslmodule_slots,
6055 .m_traverse = sslmodule_traverse,
6056 .m_clear = sslmodule_clear,
6057 .m_free = sslmodule_free
Christian Heimes5c36da72020-11-20 09:40:12 +01006058};
6059
6060PyMODINIT_FUNC
6061PyInit__ssl(void)
6062{
Christian Heimes7f1305e2021-04-17 20:06:38 +02006063 return PyModuleDef_Init(&_sslmodule_def);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006064}