blob: f371d4210a488951a4dba834bdd0be26210f00e8 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Christian Heimesa4833882021-04-13 08:17:26 +020017/* Don't warn about deprecated functions, */
18#ifndef OPENSSL_API_COMPAT
19 // 0x10101000L == 1.1.1, 30000 == 3.0.0
20 #define OPENSSL_API_COMPAT 0x10101000L
21#endif
22#define OPENSSL_NO_DEPRECATED 1
23
Victor Stinner2e57b4e2014-07-01 16:37:17 +020024#define PY_SSIZE_T_CLEAN
25
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000026#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000027
Christian Heimes7f1305e2021-04-17 20:06:38 +020028/* Include symbols from _socket module */
29#include "socketmodule.h"
30
31#include "_ssl.h"
32
Steve Dower68d663c2017-07-17 11:15:48 +020033/* Redefined below for Windows debug builds after important #includes */
34#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020035
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020036#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
Christian Heimes39258d32021-04-17 11:36:35 +020037 do { (save) = PyEval_SaveThread(); } while(0)
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020038#define PySSL_END_ALLOW_THREADS_S(save) \
Christian Heimes39258d32021-04-17 11:36:35 +020039 do { PyEval_RestoreThread(save); _PySSL_FIX_ERRNO; } while(0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000040#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000041 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020042 PySSL_BEGIN_ALLOW_THREADS_S(_save);
43#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
44#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
45#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000046
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010047
48#if defined(HAVE_POLL_H)
49#include <poll.h>
50#elif defined(HAVE_SYS_POLL_H)
51#include <sys/poll.h>
52#endif
53
54/* Include OpenSSL header files */
55#include "openssl/rsa.h"
56#include "openssl/crypto.h"
57#include "openssl/x509.h"
58#include "openssl/x509v3.h"
59#include "openssl/pem.h"
60#include "openssl/ssl.h"
61#include "openssl/err.h"
62#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020063#include "openssl/bio.h"
Alexandru Ardeleanb3a271f2018-09-17 14:53:31 +030064#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010065
Christian Heimesc087a262020-05-15 20:55:25 +020066#ifndef OPENSSL_THREADS
67# error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
68#endif
69
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010070
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010071
72struct py_ssl_error_code {
73 const char *mnemonic;
74 int library, reason;
75};
Christian Heimes7f1305e2021-04-17 20:06:38 +020076
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010077struct py_ssl_library_code {
78 const char *library;
79 int code;
80};
81
Steve Dower68d663c2017-07-17 11:15:48 +020082#if defined(MS_WINDOWS) && defined(Py_DEBUG)
83/* Debug builds on Windows rely on getting errno directly from OpenSSL.
84 * However, because it uses a different CRT, we need to transfer the
85 * value of errno from OpenSSL into our debug CRT.
86 *
87 * Don't be fooled - this is horribly ugly code. The only reasonable
88 * alternative is to do both debug and release builds of OpenSSL, which
89 * requires much uglier code to transform their automatically generated
90 * makefile. This is the lesser of all the evils.
91 */
92
93static void _PySSLFixErrno(void) {
94 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
95 if (!ucrtbase) {
96 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
97 * have a catastrophic failure, but this function is not the
98 * place to raise it. */
99 return;
100 }
101
102 typedef int *(__stdcall *errno_func)(void);
103 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
104 if (ssl_errno) {
105 errno = *ssl_errno();
106 *ssl_errno() = 0;
107 } else {
108 errno = ENOTRECOVERABLE;
109 }
110}
111
112#undef _PySSL_FIX_ERRNO
113#define _PySSL_FIX_ERRNO _PySSLFixErrno()
114#endif
115
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100116/* Include generated data (error codes) */
Christian Heimes150af752021-04-09 17:02:00 +0200117#if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
118#include "_ssl_data_300.h"
119#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
120#include "_ssl_data_111.h"
121#else
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100122#include "_ssl_data.h"
Christian Heimes150af752021-04-09 17:02:00 +0200123#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100124
Christian Heimes39258d32021-04-17 11:36:35 +0200125/* OpenSSL API 1.1.0+ does not include version methods */
Christian Heimesa871f692020-06-01 08:58:14 +0200126#ifndef OPENSSL_NO_TLS1_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200127extern const SSL_METHOD *TLSv1_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200128#endif
129#ifndef OPENSSL_NO_TLS1_1_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200130extern const SSL_METHOD *TLSv1_1_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200131#endif
132#ifndef OPENSSL_NO_TLS1_2_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200133extern const SSL_METHOD *TLSv1_2_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200134#endif
135
Victor Stinner524714e2016-07-22 17:43:59 +0200136#ifndef INVALID_SOCKET /* MS defines this */
137#define INVALID_SOCKET (-1)
138#endif
139
Christian Heimes39258d32021-04-17 11:36:35 +0200140/* OpenSSL 1.1 does not have SSL 2.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200141#define OPENSSL_NO_SSL2
Christian Heimes598894f2016-09-05 23:19:05 +0200142
Christian Heimes892d66e2018-01-29 14:10:18 +0100143/* Default cipher suites */
144#ifndef PY_SSL_DEFAULT_CIPHERS
145#define PY_SSL_DEFAULT_CIPHERS 1
146#endif
147
148#if PY_SSL_DEFAULT_CIPHERS == 0
149 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
150 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
151 #endif
152#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200153/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100154 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
155 * !aNULL:!eNULL: really no NULL ciphers
156 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
157 * !aDSS: no authentication with discrete logarithm DSA algorithm
158 * !SRP:!PSK: no secure remote password or pre-shared key authentication
159 */
160 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
161#elif PY_SSL_DEFAULT_CIPHERS == 2
162/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
163 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
164#else
165 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
166#endif
167
Christian Heimes598894f2016-09-05 23:19:05 +0200168
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000169enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000170 /* these mirror ssl.h */
171 PY_SSL_ERROR_NONE,
172 PY_SSL_ERROR_SSL,
173 PY_SSL_ERROR_WANT_READ,
174 PY_SSL_ERROR_WANT_WRITE,
175 PY_SSL_ERROR_WANT_X509_LOOKUP,
176 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
177 PY_SSL_ERROR_ZERO_RETURN,
178 PY_SSL_ERROR_WANT_CONNECT,
179 /* start of non ssl.h errorcodes */
180 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
181 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
182 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000183};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000184
Thomas Woutersed03b412007-08-28 21:37:11 +0000185enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000186 PY_SSL_CLIENT,
187 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000188};
189
190enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000191 PY_SSL_CERT_NONE,
192 PY_SSL_CERT_OPTIONAL,
193 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000194};
195
196enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000197 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200198 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200199 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100200 PY_SSL_VERSION_TLS1,
201 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200202 PY_SSL_VERSION_TLS1_2,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200203 PY_SSL_VERSION_TLS_CLIENT=0x10,
204 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100205};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200206
Christian Heimes698dde12018-02-27 11:54:43 +0100207enum py_proto_version {
208 PY_PROTO_MINIMUM_SUPPORTED = -2,
209 PY_PROTO_SSLv3 = SSL3_VERSION,
210 PY_PROTO_TLSv1 = TLS1_VERSION,
211 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
212 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
213#ifdef TLS1_3_VERSION
214 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
215#else
216 PY_PROTO_TLSv1_3 = 0x304,
217#endif
218 PY_PROTO_MAXIMUM_SUPPORTED = -1,
219
220/* OpenSSL has no dedicated API to set the minimum version to the maximum
221 * available version, and the other way around. We have to figure out the
222 * minimum and maximum available version on our own and hope for the best.
223 */
224#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
225 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
226#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
227 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
228#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
229 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
230#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
231 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
232#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
233 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
234#else
235 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
236#endif
237
238#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
239 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
240#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
241 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
242#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
243 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
244#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
245 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
246#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
247 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
248#else
249 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
250#endif
251};
252
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000253/* SSL socket object */
254
255#define X509_NAME_MAXLEN 256
256
Antoine Pitroub5218772010-05-21 09:56:06 +0000257
Antoine Pitroud6494802011-07-21 01:11:30 +0200258/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
259 * older SSL, but let's be safe */
260#define PySSL_CB_MAXLEN 128
261
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100262
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000263typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000264 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000265 SSL_CTX *ctx;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500266 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300267 unsigned int alpn_protocols_len;
Christian Heimes11a14932018-02-24 02:35:08 +0100268 PyObject *set_sni_cb;
Christian Heimes1aa9a752013-12-02 02:41:19 +0100269 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100270 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
271 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
272 */
273 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100274 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200275#ifdef TLS1_3_VERSION
276 int post_handshake_auth;
277#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200278 PyObject *msg_cb;
Christian Heimesc7f70692019-05-31 11:44:05 +0200279 PyObject *keylog_filename;
280 BIO *keylog_bio;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200281 /* Cached module state, also used in SSLSocket and SSLSession code. */
282 _sslmodulestate *state;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000283} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000284
Antoine Pitrou152efa22010-05-16 18:19:27 +0000285typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700286 int ssl; /* last seen error from SSL */
287 int c; /* last seen error from libc */
288#ifdef MS_WINDOWS
289 int ws; /* last seen error from winsock */
290#endif
291} _PySSLError;
292
293typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000294 PyObject_HEAD
295 PyObject *Socket; /* weakref to socket on which we're layered */
296 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100297 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200298 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200299 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200300 PyObject *owner; /* Python level "owner" passed to servername callback */
301 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700302 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200303 /* Some SSL callbacks don't have error reporting. Callback wrappers
304 * store exception information on the socket. The handshake, read, write,
305 * and shutdown methods check for chained exceptions.
306 */
307 PyObject *exc_type;
308 PyObject *exc_value;
309 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000310} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000311
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200312typedef struct {
313 PyObject_HEAD
314 BIO *bio;
315 int eof_written;
316} PySSLMemoryBIO;
317
Christian Heimes99a65702016-09-10 23:44:53 +0200318typedef struct {
319 PyObject_HEAD
320 SSL_SESSION *session;
321 PySSLContext *ctx;
322} PySSLSession;
323
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700324static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
325{
326 _PySSLError err = { 0 };
327 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700328#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700329 err.ws = WSAGetLastError();
330 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700331#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700332 err.c = errno;
333 err.ssl = SSL_get_error(ssl, retcode);
334 }
335 return err;
336}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700337
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300338/*[clinic input]
339module _ssl
Christian Heimes7f1305e2021-04-17 20:06:38 +0200340class _ssl._SSLContext "PySSLContext *" "get_state_type(type)->PySSLContext_Type"
341class _ssl._SSLSocket "PySSLSocket *" "get_state_type(type)->PySSLSocket_Type"
342class _ssl.MemoryBIO "PySSLMemoryBIO *" "get_state_type(type)->PySSLMemoryBIO_Type"
343class _ssl.SSLSession "PySSLSession *" "get_state_type(type)->PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300344[clinic start generated code]*/
Christian Heimes7f1305e2021-04-17 20:06:38 +0200345/*[clinic end generated code: output=da39a3ee5e6b4b0d input=d293bed8bae240fd]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300346
347#include "clinic/_ssl.c.h"
348
Victor Stinner14690702015-04-06 22:46:13 +0200349static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000350
Christian Heimes141c5e82018-02-24 21:10:57 +0100351static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
352static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000353
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000354typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000355 SOCKET_IS_NONBLOCKING,
356 SOCKET_IS_BLOCKING,
357 SOCKET_HAS_TIMED_OUT,
358 SOCKET_HAS_BEEN_CLOSED,
359 SOCKET_TOO_LARGE_FOR_SELECT,
360 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000361} timeout_state;
362
Thomas Woutersed03b412007-08-28 21:37:11 +0000363/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000364#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200365#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000366
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200367/* Get the socket from a PySSLSocket, if it has one */
368#define GET_SOCKET(obj) ((obj)->Socket ? \
369 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200370
Victor Stinner14690702015-04-06 22:46:13 +0200371/* If sock is NULL, use a timeout of 0 second */
372#define GET_SOCKET_TIMEOUT(sock) \
373 ((sock != NULL) ? (sock)->sock_timeout : 0)
374
Christian Heimesc7f70692019-05-31 11:44:05 +0200375#include "_ssl/debughelpers.c"
376
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200377/*
378 * SSL errors.
379 */
380
381PyDoc_STRVAR(SSLError_doc,
382"An error occurred in the SSL implementation.");
383
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700384PyDoc_STRVAR(SSLCertVerificationError_doc,
385"A certificate could not be verified.");
386
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200387PyDoc_STRVAR(SSLZeroReturnError_doc,
388"SSL/TLS session closed cleanly.");
389
390PyDoc_STRVAR(SSLWantReadError_doc,
391"Non-blocking SSL socket needs to read more data\n"
392"before the requested operation can be completed.");
393
394PyDoc_STRVAR(SSLWantWriteError_doc,
395"Non-blocking SSL socket needs to write more data\n"
396"before the requested operation can be completed.");
397
398PyDoc_STRVAR(SSLSyscallError_doc,
399"System error when attempting SSL operation.");
400
401PyDoc_STRVAR(SSLEOFError_doc,
402"SSL/TLS connection terminated abruptly.");
403
404static PyObject *
405SSLError_str(PyOSErrorObject *self)
406{
407 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
408 Py_INCREF(self->strerror);
409 return self->strerror;
410 }
411 else
412 return PyObject_Str(self->args);
413}
414
415static PyType_Slot sslerror_type_slots[] = {
Inada Naoki926b0cb2019-04-17 08:39:46 +0900416 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200417 {Py_tp_str, SSLError_str},
418 {0, 0},
419};
420
421static PyType_Spec sslerror_type_spec = {
422 "ssl.SSLError",
423 sizeof(PyOSErrorObject),
424 0,
425 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
426 sslerror_type_slots
427};
428
429static void
Christian Heimes7f1305e2021-04-17 20:06:38 +0200430fill_and_set_sslerror(_sslmodulestate *state,
431 PySSLSocket *sslsock, PyObject *type, int ssl_errno,
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700432 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200433{
434 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700435 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200436 PyObject *init_value, *msg, *key;
437 _Py_IDENTIFIER(reason);
438 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700439 _Py_IDENTIFIER(verify_message);
440 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200441
442 if (errcode != 0) {
443 int lib, reason;
444
445 lib = ERR_GET_LIB(errcode);
446 reason = ERR_GET_REASON(errcode);
447 key = Py_BuildValue("ii", lib, reason);
448 if (key == NULL)
449 goto fail;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200450 reason_obj = PyDict_GetItemWithError(state->err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200451 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300452 if (reason_obj == NULL && PyErr_Occurred()) {
453 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200454 }
455 key = PyLong_FromLong(lib);
456 if (key == NULL)
457 goto fail;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200458 lib_obj = PyDict_GetItemWithError(state->lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200459 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300460 if (lib_obj == NULL && PyErr_Occurred()) {
461 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200462 }
463 if (errstr == NULL)
464 errstr = ERR_reason_error_string(errcode);
465 }
466 if (errstr == NULL)
467 errstr = "unknown error";
468
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700469 /* verify code for cert validation error */
Christian Heimes7f1305e2021-04-17 20:06:38 +0200470 if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700471 const char *verify_str = NULL;
472 long verify_code;
473
474 verify_code = SSL_get_verify_result(sslsock->ssl);
475 verify_code_obj = PyLong_FromLong(verify_code);
476 if (verify_code_obj == NULL) {
477 goto fail;
478 }
479
480 switch (verify_code) {
481 case X509_V_ERR_HOSTNAME_MISMATCH:
482 verify_obj = PyUnicode_FromFormat(
483 "Hostname mismatch, certificate is not valid for '%S'.",
484 sslsock->server_hostname
485 );
486 break;
487 case X509_V_ERR_IP_ADDRESS_MISMATCH:
488 verify_obj = PyUnicode_FromFormat(
489 "IP address mismatch, certificate is not valid for '%S'.",
490 sslsock->server_hostname
491 );
492 break;
493 default:
494 verify_str = X509_verify_cert_error_string(verify_code);
495 if (verify_str != NULL) {
496 verify_obj = PyUnicode_FromString(verify_str);
497 } else {
498 verify_obj = Py_None;
499 Py_INCREF(verify_obj);
500 }
501 break;
502 }
503 if (verify_obj == NULL) {
504 goto fail;
505 }
506 }
507
508 if (verify_obj && reason_obj && lib_obj)
509 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
510 lib_obj, reason_obj, errstr, verify_obj,
511 lineno);
512 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200513 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
514 lib_obj, reason_obj, errstr, lineno);
515 else if (lib_obj)
516 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
517 lib_obj, errstr, lineno);
518 else
519 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200520 if (msg == NULL)
521 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100522
Paul Monsonfb7e7502019-05-15 15:38:55 -0700523 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100524 if (init_value == NULL)
525 goto fail;
526
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200527 err_value = PyObject_CallObject(type, init_value);
528 Py_DECREF(init_value);
529 if (err_value == NULL)
530 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100531
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200532 if (reason_obj == NULL)
533 reason_obj = Py_None;
534 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
535 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700536
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200537 if (lib_obj == NULL)
538 lib_obj = Py_None;
539 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
540 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700541
Christian Heimes7f1305e2021-04-17 20:06:38 +0200542 if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700543 /* Only set verify code / message for SSLCertVerificationError */
544 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
545 verify_code_obj))
546 goto fail;
547 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
548 goto fail;
549 }
550
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200551 PyErr_SetObject(type, err_value);
552fail:
553 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700554 Py_XDECREF(verify_code_obj);
555 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200556}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000557
Christian Heimesc7f70692019-05-31 11:44:05 +0200558static int
559PySSL_ChainExceptions(PySSLSocket *sslsock) {
560 if (sslsock->exc_type == NULL)
561 return 0;
562
563 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
564 sslsock->exc_type = NULL;
565 sslsock->exc_value = NULL;
566 sslsock->exc_tb = NULL;
567 return -1;
568}
569
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000570static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700571PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000572{
Christian Heimes7f1305e2021-04-17 20:06:38 +0200573 PyObject *type;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200574 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700575 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000576 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200577 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000578
Christian Heimes7f1305e2021-04-17 20:06:38 +0200579 assert(sslsock != NULL);
580
581 _sslmodulestate *state = get_state_sock(sslsock);
582 type = state->PySSLErrorObject;
583
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000584 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200585 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000586
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700587 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700588 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000589
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700590 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000591 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200592 errstr = "TLS/SSL connection has been closed (EOF)";
Christian Heimes7f1305e2021-04-17 20:06:38 +0200593 type = state->PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000594 p = PY_SSL_ERROR_ZERO_RETURN;
595 break;
596 case SSL_ERROR_WANT_READ:
597 errstr = "The operation did not complete (read)";
Christian Heimes7f1305e2021-04-17 20:06:38 +0200598 type = state->PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000599 p = PY_SSL_ERROR_WANT_READ;
600 break;
601 case SSL_ERROR_WANT_WRITE:
602 p = PY_SSL_ERROR_WANT_WRITE;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200603 type = state->PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000604 errstr = "The operation did not complete (write)";
605 break;
606 case SSL_ERROR_WANT_X509_LOOKUP:
607 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000608 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000609 break;
610 case SSL_ERROR_WANT_CONNECT:
611 p = PY_SSL_ERROR_WANT_CONNECT;
612 errstr = "The operation did not complete (connect)";
613 break;
614 case SSL_ERROR_SYSCALL:
615 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000616 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700617 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000619 p = PY_SSL_ERROR_EOF;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200620 type = state->PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000621 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200622 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000623 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000624 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700625#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700626 if (err.ws) {
627 return PyErr_SetFromWindowsErr(err.ws);
628 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700629#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700630 if (err.c) {
631 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700632 return PyErr_SetFromErrno(PyExc_OSError);
633 }
Dima Tisnek495bd032020-08-16 02:01:19 +0900634 else {
635 p = PY_SSL_ERROR_EOF;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200636 type = state->PySSLEOFErrorObject;
Dima Tisnek495bd032020-08-16 02:01:19 +0900637 errstr = "EOF occurred in violation of protocol";
638 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000639 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000640 p = PY_SSL_ERROR_SYSCALL;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200641 type = state->PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000642 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000643 }
644 } else {
645 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000646 }
647 break;
648 }
649 case SSL_ERROR_SSL:
650 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000651 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700652 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200653 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000654 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700655 }
656 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
657 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200658 type = state->PySSLCertVerificationErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700659 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000660 break;
661 }
662 default:
663 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
664 errstr = "Invalid error code";
665 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 }
Christian Heimes7f1305e2021-04-17 20:06:38 +0200667 fill_and_set_sslerror(state, sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000668 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200669 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000670 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000671}
672
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000673static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +0200674_setSSLError (_sslmodulestate *state, const char *errstr, int errcode, const char *filename, int lineno)
675{
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200676 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000677 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200678 else
679 errcode = 0;
Christian Heimes7f1305e2021-04-17 20:06:38 +0200680 fill_and_set_sslerror(state, NULL, state->PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000681 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000682 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000683}
684
Christian Heimes61d478c2018-01-27 15:51:38 +0100685/*
686 * SSL objects
687 */
688
689static int
690_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
691{
692 int retval = -1;
693 ASN1_OCTET_STRING *ip;
694 PyObject *hostname;
695 size_t len;
696
697 assert(server_hostname);
698
699 /* Disable OpenSSL's special mode with leading dot in hostname:
700 * When name starts with a dot (e.g ".example.com"), it will be
701 * matched by a certificate valid for any sub-domain of name.
702 */
703 len = strlen(server_hostname);
704 if (len == 0 || *server_hostname == '.') {
705 PyErr_SetString(
706 PyExc_ValueError,
707 "server_hostname cannot be an empty string or start with a "
708 "leading dot.");
709 return retval;
710 }
711
712 /* inet_pton is not available on all platforms. */
713 ip = a2i_IPADDRESS(server_hostname);
714 if (ip == NULL) {
715 ERR_clear_error();
716 }
717
Christian Heimes11a14932018-02-24 02:35:08 +0100718 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100719 if (hostname == NULL) {
720 goto error;
721 }
722 self->server_hostname = hostname;
723
724 /* Only send SNI extension for non-IP hostnames */
725 if (ip == NULL) {
726 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200727 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzc32f2972020-10-25 12:02:30 -0600728 goto error;
Christian Heimes61d478c2018-01-27 15:51:38 +0100729 }
730 }
731 if (self->ctx->check_hostname) {
732 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
733 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200734 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
735 strlen(server_hostname))) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200736 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes61d478c2018-01-27 15:51:38 +0100737 goto error;
738 }
739 } else {
Christian Heimesa871f692020-06-01 08:58:14 +0200740 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
Christian Heimes61d478c2018-01-27 15:51:38 +0100741 ASN1_STRING_length(ip))) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200742 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes61d478c2018-01-27 15:51:38 +0100743 goto error;
744 }
745 }
746 }
747 retval = 0;
748 error:
749 if (ip != NULL) {
750 ASN1_OCTET_STRING_free(ip);
751 }
752 return retval;
753}
754
Antoine Pitrou152efa22010-05-16 18:19:27 +0000755static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100756newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000757 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200758 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100759 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200760 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000761{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000762 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100763 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700764 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000765
Christian Heimes7f1305e2021-04-17 20:06:38 +0200766 self = PyObject_New(PySSLSocket, get_state_ctx(sslctx)->PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000767 if (self == NULL)
768 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000769
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000771 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100772 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700773 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200774 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200775 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700776 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700777 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200778 self->exc_type = NULL;
779 self->exc_value = NULL;
780 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200781
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000782 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000784
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000786 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000787 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700788 if (self->ssl == NULL) {
789 Py_DECREF(self);
Christian Heimes7f1305e2021-04-17 20:06:38 +0200790 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytz4c49da02018-12-07 03:11:30 -0700791 return NULL;
792 }
Christian Heimesb467d9a2021-04-17 10:07:19 +0200793 /* bpo43522 and OpenSSL < 1.1.1l: copy hostflags manually */
794#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION < 0x101010cf
795 X509_VERIFY_PARAM *ssl_params = SSL_get0_param(self->ssl);
796 X509_VERIFY_PARAM_set_hostflags(ssl_params, sslctx->hostflags);
797#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200798 SSL_set_app_data(self->ssl, self);
799 if (sock) {
800 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
801 } else {
802 /* BIOs are reference counted and SSL_set_bio borrows our reference.
803 * To prevent a double free in memory_bio_dealloc() we need to take an
804 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200805 BIO_up_ref(inbio->bio);
806 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200807 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
808 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400809 SSL_set_mode(self->ssl,
810 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000811
Christian Heimesf0f59302019-07-01 08:29:17 +0200812#ifdef TLS1_3_VERSION
813 if (sslctx->post_handshake_auth == 1) {
814 if (socket_type == PY_SSL_SERVER) {
815 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
816 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
817 * only in combination with SSL_VERIFY_PEER flag. */
818 int mode = SSL_get_verify_mode(self->ssl);
819 if (mode & SSL_VERIFY_PEER) {
820 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
821 verify_cb = SSL_get_verify_callback(self->ssl);
822 mode |= SSL_VERIFY_POST_HANDSHAKE;
823 SSL_set_verify(self->ssl, mode, verify_cb);
824 }
825 } else {
826 /* client socket */
827 SSL_set_post_handshake_auth(self->ssl, 1);
828 }
829 }
830#endif
831
Christian Heimes61d478c2018-01-27 15:51:38 +0100832 if (server_hostname != NULL) {
833 if (_ssl_configure_hostname(self, server_hostname) < 0) {
834 Py_DECREF(self);
835 return NULL;
836 }
837 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 /* If the socket is in non-blocking mode or timeout mode, set the BIO
839 * to non-blocking mode (blocking is the default)
840 */
Victor Stinnere2452312015-03-28 03:00:46 +0100841 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000842 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
843 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
844 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000845
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000846 PySSL_BEGIN_ALLOW_THREADS
847 if (socket_type == PY_SSL_CLIENT)
848 SSL_set_connect_state(self->ssl);
849 else
850 SSL_set_accept_state(self->ssl);
851 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000852
Antoine Pitroud6494802011-07-21 01:11:30 +0200853 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200854 if (sock != NULL) {
855 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
856 if (self->Socket == NULL) {
857 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200858 return NULL;
859 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100860 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100861 if (owner && owner != Py_None) {
862 if (PySSL_set_owner(self, owner, NULL) == -1) {
863 Py_DECREF(self);
864 return NULL;
865 }
866 }
867 if (session && session != Py_None) {
868 if (PySSL_set_session(self, session, NULL) == -1) {
869 Py_DECREF(self);
870 return NULL;
871 }
872 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000873 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000874}
875
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000876/* SSL object methods */
877
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300878/*[clinic input]
879_ssl._SSLSocket.do_handshake
880[clinic start generated code]*/
881
882static PyObject *
883_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
884/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000885{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000886 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700887 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000888 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200889 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200890 _PyTime_t timeout, deadline = 0;
891 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000892
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200893 if (sock) {
894 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200895 _setSSLError(get_state_sock(self),
896 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200897 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
898 return NULL;
899 }
900 Py_INCREF(sock);
901
902 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100903 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200904 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
905 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000906 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000907
Victor Stinner14690702015-04-06 22:46:13 +0200908 timeout = GET_SOCKET_TIMEOUT(sock);
909 has_timeout = (timeout > 0);
910 if (has_timeout)
911 deadline = _PyTime_GetMonotonicClock() + timeout;
912
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000913 /* Actually negotiate SSL connection */
914 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000915 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000916 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000917 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700918 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000919 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700920 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200921
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000922 if (PyErr_CheckSignals())
923 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200924
Victor Stinner14690702015-04-06 22:46:13 +0200925 if (has_timeout)
926 timeout = deadline - _PyTime_GetMonotonicClock();
927
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700928 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200929 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700930 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200931 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 } else {
933 sockstate = SOCKET_OPERATION_OK;
934 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200935
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +0100937 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000938 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000939 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200941 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000942 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000943 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200945 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000946 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000947 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
949 break;
950 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700951 } while (err.ssl == SSL_ERROR_WANT_READ ||
952 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200953 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000954 if (ret < 1)
955 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +0200956 if (PySSL_ChainExceptions(self) < 0)
957 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200958 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000959error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200960 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +0200961 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000962 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000963}
964
Thomas Woutersed03b412007-08-28 21:37:11 +0000965static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +0200966_asn1obj2py(_sslmodulestate *state, const ASN1_OBJECT *name, int no_name)
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300967{
968 char buf[X509_NAME_MAXLEN];
969 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300971 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000972
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300973 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200975 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300976 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000977 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300978 /* initial buffer is too small for oid + terminating null byte */
979 if (buflen > X509_NAME_MAXLEN - 1) {
980 /* make OBJ_obj2txt() calculate the required buflen */
981 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
982 /* allocate len + 1 for terminating NULL byte */
983 namebuf = PyMem_Malloc(buflen + 1);
984 if (namebuf == NULL) {
985 PyErr_NoMemory();
986 return NULL;
987 }
988 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
989 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +0200990 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300991 goto done;
992 }
993 }
994 if (!buflen && no_name) {
995 Py_INCREF(Py_None);
996 name_obj = Py_None;
997 }
998 else {
999 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1000 }
1001
1002 done:
1003 if (buf != namebuf) {
1004 PyMem_Free(namebuf);
1005 }
1006 return name_obj;
1007}
1008
1009static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001010_create_tuple_for_attribute(_sslmodulestate *state,
1011 ASN1_OBJECT *name, ASN1_STRING *value)
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001012{
1013 Py_ssize_t buflen;
1014 unsigned char *valuebuf = NULL;
1015 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001016
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001017 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1018 if (buflen < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001019 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001020 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001021 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02001022 attr = Py_BuildValue("Ns#", _asn1obj2py(state, name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001023 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001024 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001025}
1026
1027static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001028_create_tuple_for_X509_NAME (_sslmodulestate *state, X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001029{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001030 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1031 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1032 PyObject *rdnt;
1033 PyObject *attr = NULL; /* tuple to hold an attribute */
1034 int entry_count = X509_NAME_entry_count(xname);
1035 X509_NAME_ENTRY *entry;
1036 ASN1_OBJECT *name;
1037 ASN1_STRING *value;
1038 int index_counter;
1039 int rdn_level = -1;
1040 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001041
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001042 dn = PyList_New(0);
1043 if (dn == NULL)
1044 return NULL;
1045 /* now create another tuple to hold the top-level RDN */
1046 rdn = PyList_New(0);
1047 if (rdn == NULL)
1048 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001049
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 for (index_counter = 0;
1051 index_counter < entry_count;
1052 index_counter++)
1053 {
1054 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001055
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001056 /* check to see if we've gotten to a new RDN */
1057 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001058 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 /* yes, new RDN */
1060 /* add old RDN to DN */
1061 rdnt = PyList_AsTuple(rdn);
1062 Py_DECREF(rdn);
1063 if (rdnt == NULL)
1064 goto fail0;
1065 retcode = PyList_Append(dn, rdnt);
1066 Py_DECREF(rdnt);
1067 if (retcode < 0)
1068 goto fail0;
1069 /* create new RDN */
1070 rdn = PyList_New(0);
1071 if (rdn == NULL)
1072 goto fail0;
1073 }
1074 }
Christian Heimes598894f2016-09-05 23:19:05 +02001075 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001076
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001077 /* now add this attribute to the current RDN */
1078 name = X509_NAME_ENTRY_get_object(entry);
1079 value = X509_NAME_ENTRY_get_data(entry);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001080 attr = _create_tuple_for_attribute(state, name, value);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081 /*
1082 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1083 entry->set,
1084 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1085 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1086 */
1087 if (attr == NULL)
1088 goto fail1;
1089 retcode = PyList_Append(rdn, attr);
1090 Py_DECREF(attr);
1091 if (retcode < 0)
1092 goto fail1;
1093 }
1094 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001095 if (rdn != NULL) {
1096 if (PyList_GET_SIZE(rdn) > 0) {
1097 rdnt = PyList_AsTuple(rdn);
1098 Py_DECREF(rdn);
1099 if (rdnt == NULL)
1100 goto fail0;
1101 retcode = PyList_Append(dn, rdnt);
1102 Py_DECREF(rdnt);
1103 if (retcode < 0)
1104 goto fail0;
1105 }
1106 else {
1107 Py_DECREF(rdn);
1108 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001110
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 /* convert list to tuple */
1112 rdnt = PyList_AsTuple(dn);
1113 Py_DECREF(dn);
1114 if (rdnt == NULL)
1115 return NULL;
1116 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001117
1118 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001119 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001120
1121 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001122 Py_XDECREF(dn);
1123 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001124}
1125
1126static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001127_get_peer_alt_names (_sslmodulestate *state, X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001128
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 /* this code follows the procedure outlined in
1130 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1131 function to extract the STACK_OF(GENERAL_NAME),
1132 then iterates through the stack to add the
1133 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001134
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001135 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001136 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001137 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001138 GENERAL_NAMES *names = NULL;
1139 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 BIO *biobuf = NULL;
1141 char buf[2048];
1142 char *vptr;
1143 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001144
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 if (certificate == NULL)
1146 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001147
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 /* get a memory buffer */
1149 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001150 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001151 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001152 return NULL;
1153 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001154
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001155 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1156 certificate, NID_subject_alt_name, NULL, NULL);
1157 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001158 if (peer_alt_names == Py_None) {
1159 peer_alt_names = PyList_New(0);
1160 if (peer_alt_names == NULL)
1161 goto fail;
1162 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001163
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001165 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001166 int gntype;
1167 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001168
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001169 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001170 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001171 switch (gntype) {
1172 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001173 /* we special-case DirName as a tuple of
1174 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001175
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001176 t = PyTuple_New(2);
1177 if (t == NULL) {
1178 goto fail;
1179 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001180
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001181 v = PyUnicode_FromString("DirName");
1182 if (v == NULL) {
1183 Py_DECREF(t);
1184 goto fail;
1185 }
1186 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001187
Christian Heimes7f1305e2021-04-17 20:06:38 +02001188 v = _create_tuple_for_X509_NAME(state, name->d.dirn);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001189 if (v == NULL) {
1190 Py_DECREF(t);
1191 goto fail;
1192 }
1193 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001194 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001195
Christian Heimes824f7f32013-08-17 00:54:47 +02001196 case GEN_EMAIL:
1197 case GEN_DNS:
1198 case GEN_URI:
1199 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1200 correctly, CVE-2013-4238 */
1201 t = PyTuple_New(2);
1202 if (t == NULL)
1203 goto fail;
1204 switch (gntype) {
1205 case GEN_EMAIL:
1206 v = PyUnicode_FromString("email");
1207 as = name->d.rfc822Name;
1208 break;
1209 case GEN_DNS:
1210 v = PyUnicode_FromString("DNS");
1211 as = name->d.dNSName;
1212 break;
1213 case GEN_URI:
1214 v = PyUnicode_FromString("URI");
1215 as = name->d.uniformResourceIdentifier;
1216 break;
1217 }
1218 if (v == NULL) {
1219 Py_DECREF(t);
1220 goto fail;
1221 }
1222 PyTuple_SET_ITEM(t, 0, v);
Christian Heimesa871f692020-06-01 08:58:14 +02001223 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
Christian Heimes824f7f32013-08-17 00:54:47 +02001224 ASN1_STRING_length(as));
1225 if (v == NULL) {
1226 Py_DECREF(t);
1227 goto fail;
1228 }
1229 PyTuple_SET_ITEM(t, 1, v);
1230 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001231
Christian Heimes1c03abd2016-09-06 23:25:35 +02001232 case GEN_RID:
1233 t = PyTuple_New(2);
1234 if (t == NULL)
1235 goto fail;
1236
1237 v = PyUnicode_FromString("Registered ID");
1238 if (v == NULL) {
1239 Py_DECREF(t);
1240 goto fail;
1241 }
1242 PyTuple_SET_ITEM(t, 0, v);
1243
1244 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1245 if (len < 0) {
1246 Py_DECREF(t);
Christian Heimes7f1305e2021-04-17 20:06:38 +02001247 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes1c03abd2016-09-06 23:25:35 +02001248 goto fail;
1249 } else if (len >= (int)sizeof(buf)) {
1250 v = PyUnicode_FromString("<INVALID>");
1251 } else {
1252 v = PyUnicode_FromStringAndSize(buf, len);
1253 }
1254 if (v == NULL) {
1255 Py_DECREF(t);
1256 goto fail;
1257 }
1258 PyTuple_SET_ITEM(t, 1, v);
1259 break;
1260
Christian Heimes2b7de662019-12-07 17:59:36 +01001261 case GEN_IPADD:
1262 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1263 * the trailing newline. Remove it in all versions
1264 */
1265 t = PyTuple_New(2);
1266 if (t == NULL)
1267 goto fail;
1268
1269 v = PyUnicode_FromString("IP Address");
1270 if (v == NULL) {
1271 Py_DECREF(t);
1272 goto fail;
1273 }
1274 PyTuple_SET_ITEM(t, 0, v);
1275
1276 if (name->d.ip->length == 4) {
1277 unsigned char *p = name->d.ip->data;
1278 v = PyUnicode_FromFormat(
1279 "%d.%d.%d.%d",
1280 p[0], p[1], p[2], p[3]
1281 );
1282 } else if (name->d.ip->length == 16) {
1283 /* PyUnicode_FromFormat() does not support %X */
1284 unsigned char *p = name->d.ip->data;
1285 len = sprintf(
1286 buf,
1287 "%X:%X:%X:%X:%X:%X:%X:%X",
1288 p[0] << 8 | p[1],
1289 p[2] << 8 | p[3],
1290 p[4] << 8 | p[5],
1291 p[6] << 8 | p[7],
1292 p[8] << 8 | p[9],
1293 p[10] << 8 | p[11],
1294 p[12] << 8 | p[13],
1295 p[14] << 8 | p[15]
1296 );
1297 v = PyUnicode_FromStringAndSize(buf, len);
1298 } else {
1299 v = PyUnicode_FromString("<invalid>");
1300 }
1301
1302 if (v == NULL) {
1303 Py_DECREF(t);
1304 goto fail;
1305 }
1306 PyTuple_SET_ITEM(t, 1, v);
1307 break;
1308
Christian Heimes824f7f32013-08-17 00:54:47 +02001309 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001310 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001311 switch (gntype) {
1312 /* check for new general name type */
1313 case GEN_OTHERNAME:
1314 case GEN_X400:
1315 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001316 case GEN_RID:
1317 break;
1318 default:
1319 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1320 "Unknown general name type %d",
1321 gntype) == -1) {
1322 goto fail;
1323 }
1324 break;
1325 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001326 (void) BIO_reset(biobuf);
1327 GENERAL_NAME_print(biobuf, name);
1328 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1329 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001330 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001331 goto fail;
1332 }
1333 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001334 if (vptr == NULL) {
1335 PyErr_Format(PyExc_ValueError,
1336 "Invalid value %.200s",
1337 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001339 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 t = PyTuple_New(2);
1341 if (t == NULL)
1342 goto fail;
1343 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1344 if (v == NULL) {
1345 Py_DECREF(t);
1346 goto fail;
1347 }
1348 PyTuple_SET_ITEM(t, 0, v);
1349 v = PyUnicode_FromStringAndSize((vptr + 1),
1350 (len - (vptr - buf + 1)));
1351 if (v == NULL) {
1352 Py_DECREF(t);
1353 goto fail;
1354 }
1355 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001356 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001357 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001358
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001360
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 if (PyList_Append(peer_alt_names, t) < 0) {
1362 Py_DECREF(t);
1363 goto fail;
1364 }
1365 Py_DECREF(t);
1366 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001367 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 }
1369 BIO_free(biobuf);
1370 if (peer_alt_names != Py_None) {
1371 v = PyList_AsTuple(peer_alt_names);
1372 Py_DECREF(peer_alt_names);
1373 return v;
1374 } else {
1375 return peer_alt_names;
1376 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001377
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001378
1379 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001380 if (biobuf != NULL)
1381 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001382
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001383 if (peer_alt_names != Py_None) {
1384 Py_XDECREF(peer_alt_names);
1385 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001386
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001387 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001388}
1389
1390static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001391_get_aia_uri(X509 *certificate, int nid) {
1392 PyObject *lst = NULL, *ostr = NULL;
1393 int i, result;
1394 AUTHORITY_INFO_ACCESS *info;
1395
1396 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001397 if (info == NULL)
1398 return Py_None;
1399 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1400 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001401 return Py_None;
1402 }
1403
1404 if ((lst = PyList_New(0)) == NULL) {
1405 goto fail;
1406 }
1407
1408 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1409 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1410 ASN1_IA5STRING *uri;
1411
1412 if ((OBJ_obj2nid(ad->method) != nid) ||
1413 (ad->location->type != GEN_URI)) {
1414 continue;
1415 }
1416 uri = ad->location->d.uniformResourceIdentifier;
1417 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1418 uri->length);
1419 if (ostr == NULL) {
1420 goto fail;
1421 }
1422 result = PyList_Append(lst, ostr);
1423 Py_DECREF(ostr);
1424 if (result < 0) {
1425 goto fail;
1426 }
1427 }
1428 AUTHORITY_INFO_ACCESS_free(info);
1429
1430 /* convert to tuple or None */
1431 if (PyList_Size(lst) == 0) {
1432 Py_DECREF(lst);
1433 return Py_None;
1434 } else {
1435 PyObject *tup;
1436 tup = PyList_AsTuple(lst);
1437 Py_DECREF(lst);
1438 return tup;
1439 }
1440
1441 fail:
1442 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001443 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001444 return NULL;
1445}
1446
1447static PyObject *
1448_get_crl_dp(X509 *certificate) {
1449 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001450 int i, j;
1451 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001452
Christian Heimes598894f2016-09-05 23:19:05 +02001453 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001454
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001455 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001456 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001457
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001458 lst = PyList_New(0);
1459 if (lst == NULL)
1460 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001461
1462 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1463 DIST_POINT *dp;
1464 STACK_OF(GENERAL_NAME) *gns;
1465
1466 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001467 if (dp->distpoint == NULL) {
1468 /* Ignore empty DP value, CVE-2019-5010 */
1469 continue;
1470 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001471 gns = dp->distpoint->name.fullname;
1472
1473 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1474 GENERAL_NAME *gn;
1475 ASN1_IA5STRING *uri;
1476 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001477 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001478
1479 gn = sk_GENERAL_NAME_value(gns, j);
1480 if (gn->type != GEN_URI) {
1481 continue;
1482 }
1483 uri = gn->d.uniformResourceIdentifier;
1484 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1485 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001486 if (ouri == NULL)
1487 goto done;
1488
1489 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001490 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001491 if (err < 0)
1492 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001493 }
1494 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001495
1496 /* Convert to tuple. */
1497 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1498
1499 done:
1500 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001501 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001502 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001503}
1504
1505static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001506_decode_certificate(_sslmodulestate *state, X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001507
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001508 PyObject *retval = NULL;
1509 BIO *biobuf = NULL;
1510 PyObject *peer;
1511 PyObject *peer_alt_names = NULL;
1512 PyObject *issuer;
1513 PyObject *version;
1514 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001515 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001516 ASN1_INTEGER *serialNumber;
1517 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001518 int len, result;
Christian Heimesa871f692020-06-01 08:58:14 +02001519 const ASN1_TIME *notBefore, *notAfter;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001520 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001521
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522 retval = PyDict_New();
1523 if (retval == NULL)
1524 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001526 peer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001527 state,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 X509_get_subject_name(certificate));
1529 if (peer == NULL)
1530 goto fail0;
1531 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1532 Py_DECREF(peer);
1533 goto fail0;
1534 }
1535 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001536
Antoine Pitroufb046912010-11-09 20:21:19 +00001537 issuer = _create_tuple_for_X509_NAME(
Christian Heimes7f1305e2021-04-17 20:06:38 +02001538 state,
Antoine Pitroufb046912010-11-09 20:21:19 +00001539 X509_get_issuer_name(certificate));
1540 if (issuer == NULL)
1541 goto fail0;
1542 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001543 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001544 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001545 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001546 Py_DECREF(issuer);
1547
1548 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001549 if (version == NULL)
1550 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001551 if (PyDict_SetItemString(retval, "version", version) < 0) {
1552 Py_DECREF(version);
1553 goto fail0;
1554 }
1555 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001556
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001557 /* get a memory buffer */
1558 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001559 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001560 PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
Zackery Spytz4c49da02018-12-07 03:11:30 -07001561 goto fail0;
1562 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001563
Antoine Pitroufb046912010-11-09 20:21:19 +00001564 (void) BIO_reset(biobuf);
1565 serialNumber = X509_get_serialNumber(certificate);
1566 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1567 i2a_ASN1_INTEGER(biobuf, serialNumber);
1568 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1569 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001570 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001571 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001572 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001573 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1574 if (sn_obj == NULL)
1575 goto fail1;
1576 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1577 Py_DECREF(sn_obj);
1578 goto fail1;
1579 }
1580 Py_DECREF(sn_obj);
1581
1582 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001583 notBefore = X509_get0_notBefore(certificate);
Antoine Pitroufb046912010-11-09 20:21:19 +00001584 ASN1_TIME_print(biobuf, notBefore);
1585 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1586 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001587 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroufb046912010-11-09 20:21:19 +00001588 goto fail1;
1589 }
1590 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1591 if (pnotBefore == NULL)
1592 goto fail1;
1593 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1594 Py_DECREF(pnotBefore);
1595 goto fail1;
1596 }
1597 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001598
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001599 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001600 notAfter = X509_get0_notAfter(certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001601 ASN1_TIME_print(biobuf, notAfter);
1602 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1603 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001604 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001605 goto fail1;
1606 }
1607 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1608 if (pnotAfter == NULL)
1609 goto fail1;
1610 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1611 Py_DECREF(pnotAfter);
1612 goto fail1;
1613 }
1614 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001615
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001616 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001617
Christian Heimes7f1305e2021-04-17 20:06:38 +02001618 peer_alt_names = _get_peer_alt_names(state, certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001619 if (peer_alt_names == NULL)
1620 goto fail1;
1621 else if (peer_alt_names != Py_None) {
1622 if (PyDict_SetItemString(retval, "subjectAltName",
1623 peer_alt_names) < 0) {
1624 Py_DECREF(peer_alt_names);
1625 goto fail1;
1626 }
1627 Py_DECREF(peer_alt_names);
1628 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001629
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001630 /* Authority Information Access: OCSP URIs */
1631 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1632 if (obj == NULL) {
1633 goto fail1;
1634 } else if (obj != Py_None) {
1635 result = PyDict_SetItemString(retval, "OCSP", obj);
1636 Py_DECREF(obj);
1637 if (result < 0) {
1638 goto fail1;
1639 }
1640 }
1641
1642 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1643 if (obj == NULL) {
1644 goto fail1;
1645 } else if (obj != Py_None) {
1646 result = PyDict_SetItemString(retval, "caIssuers", obj);
1647 Py_DECREF(obj);
1648 if (result < 0) {
1649 goto fail1;
1650 }
1651 }
1652
1653 /* CDP (CRL distribution points) */
1654 obj = _get_crl_dp(certificate);
1655 if (obj == NULL) {
1656 goto fail1;
1657 } else if (obj != Py_None) {
1658 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1659 Py_DECREF(obj);
1660 if (result < 0) {
1661 goto fail1;
1662 }
1663 }
1664
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001665 BIO_free(biobuf);
1666 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001667
1668 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001669 if (biobuf != NULL)
1670 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001671 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001672 Py_XDECREF(retval);
1673 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001674}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001675
Christian Heimes9a5395a2013-06-17 15:44:12 +02001676static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02001677_certificate_to_der(_sslmodulestate *state, X509 *certificate)
Christian Heimes9a5395a2013-06-17 15:44:12 +02001678{
1679 unsigned char *bytes_buf = NULL;
1680 int len;
1681 PyObject *retval;
1682
1683 bytes_buf = NULL;
1684 len = i2d_X509(certificate, &bytes_buf);
1685 if (len < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001686 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Christian Heimes9a5395a2013-06-17 15:44:12 +02001687 return NULL;
1688 }
1689 /* this is actually an immutable bytes sequence */
1690 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1691 OPENSSL_free(bytes_buf);
1692 return retval;
1693}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001694
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001695/*[clinic input]
1696_ssl._test_decode_cert
1697 path: object(converter="PyUnicode_FSConverter")
1698 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001699
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001700[clinic start generated code]*/
1701
1702static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001703_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1704/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001705{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001706 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001707 X509 *x=NULL;
1708 BIO *cert;
Christian Heimes7f1305e2021-04-17 20:06:38 +02001709 _sslmodulestate *state = get_ssl_state(module);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001710
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001711 if ((cert=BIO_new(BIO_s_file())) == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001712 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001713 "Can't malloc memory to read file");
1714 goto fail0;
1715 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001716
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001717 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001718 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001719 "Can't open file");
1720 goto fail0;
1721 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001722
Alex Gaynor40dad952019-08-15 08:31:28 -04001723 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001724 if (x == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02001725 PyErr_SetString(state->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001726 "Error decoding PEM-encoded file");
1727 goto fail0;
1728 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001729
Christian Heimes7f1305e2021-04-17 20:06:38 +02001730 retval = _decode_certificate(state, x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001731 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001732
1733 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001734 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001735 if (cert != NULL) BIO_free(cert);
1736 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001737}
1738
1739
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001740/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001741_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001742 der as binary_mode: bool = False
1743 /
1744
1745Returns the certificate for the peer.
1746
1747If no certificate was provided, returns None. If a certificate was
1748provided, but not validated, returns an empty dictionary. Otherwise
1749returns a dict containing information about the peer certificate.
1750
1751If the optional argument is True, returns a DER-encoded copy of the
1752peer certificate, or None if no certificate was provided. This will
1753return the certificate even if it wasn't validated.
1754[clinic start generated code]*/
1755
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001756static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001757_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1758/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001759{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001760 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001761 X509 *peer_cert;
1762 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001763
Christian Heimes66dc33b2017-05-23 16:02:02 -07001764 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001765 PyErr_SetString(PyExc_ValueError,
1766 "handshake not done yet");
1767 return NULL;
1768 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001769 peer_cert = SSL_get_peer_certificate(self->ssl);
1770 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001771 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001772
Antoine Pitrou721738f2012-08-15 23:20:39 +02001773 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001774 /* return cert in DER-encoded format */
Christian Heimes7f1305e2021-04-17 20:06:38 +02001775 result = _certificate_to_der(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001776 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001777 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001778 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001779 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001780 else
Christian Heimes7f1305e2021-04-17 20:06:38 +02001781 result = _decode_certificate(get_state_sock(self), peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001782 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001783 X509_free(peer_cert);
1784 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001785}
1786
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001787static PyObject *
1788cipher_to_tuple(const SSL_CIPHER *cipher)
1789{
1790 const char *cipher_name, *cipher_protocol;
1791 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001792 if (retval == NULL)
1793 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001794
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001795 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001796 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001797 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001798 PyTuple_SET_ITEM(retval, 0, Py_None);
1799 } else {
1800 v = PyUnicode_FromString(cipher_name);
1801 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001802 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001803 PyTuple_SET_ITEM(retval, 0, v);
1804 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001805
1806 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001807 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001808 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001809 PyTuple_SET_ITEM(retval, 1, Py_None);
1810 } else {
1811 v = PyUnicode_FromString(cipher_protocol);
1812 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001813 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001814 PyTuple_SET_ITEM(retval, 1, v);
1815 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001816
1817 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001818 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001819 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001820 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001821
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001822 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001823
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001824 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 Py_DECREF(retval);
1826 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001827}
1828
Christian Heimes25bfcd52016-09-06 00:04:45 +02001829static PyObject *
1830cipher_to_dict(const SSL_CIPHER *cipher)
1831{
1832 const char *cipher_name, *cipher_protocol;
1833
1834 unsigned long cipher_id;
1835 int alg_bits, strength_bits, len;
1836 char buf[512] = {0};
Christian Heimes25bfcd52016-09-06 00:04:45 +02001837 int aead, nid;
1838 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001839
1840 /* can be NULL */
1841 cipher_name = SSL_CIPHER_get_name(cipher);
1842 cipher_protocol = SSL_CIPHER_get_version(cipher);
1843 cipher_id = SSL_CIPHER_get_id(cipher);
1844 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001845 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1846 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001847 if (len > 1 && buf[len-1] == '\n')
1848 buf[len-1] = '\0';
1849 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1850
Christian Heimes25bfcd52016-09-06 00:04:45 +02001851 aead = SSL_CIPHER_is_aead(cipher);
1852 nid = SSL_CIPHER_get_cipher_nid(cipher);
1853 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1854 nid = SSL_CIPHER_get_digest_nid(cipher);
1855 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1856 nid = SSL_CIPHER_get_kx_nid(cipher);
1857 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1858 nid = SSL_CIPHER_get_auth_nid(cipher);
1859 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001860
Victor Stinner410b9882016-09-12 12:00:23 +02001861 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001862 "{sksssssssisi"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001863 "sOssssssss"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001864 "}",
1865 "id", cipher_id,
1866 "name", cipher_name,
1867 "protocol", cipher_protocol,
1868 "description", buf,
1869 "strength_bits", strength_bits,
1870 "alg_bits", alg_bits
Christian Heimes25bfcd52016-09-06 00:04:45 +02001871 ,"aead", aead ? Py_True : Py_False,
1872 "symmetric", skcipher,
1873 "digest", digest,
1874 "kea", kx,
1875 "auth", auth
Christian Heimes25bfcd52016-09-06 00:04:45 +02001876 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001877}
Christian Heimes25bfcd52016-09-06 00:04:45 +02001878
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001879/*[clinic input]
1880_ssl._SSLSocket.shared_ciphers
1881[clinic start generated code]*/
1882
1883static PyObject *
1884_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1885/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001886{
1887 STACK_OF(SSL_CIPHER) *ciphers;
1888 int i;
1889 PyObject *res;
1890
Christian Heimes598894f2016-09-05 23:19:05 +02001891 ciphers = SSL_get_ciphers(self->ssl);
1892 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001893 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001894 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1895 if (!res)
1896 return NULL;
1897 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1898 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1899 if (!tup) {
1900 Py_DECREF(res);
1901 return NULL;
1902 }
1903 PyList_SET_ITEM(res, i, tup);
1904 }
1905 return res;
1906}
1907
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001908/*[clinic input]
1909_ssl._SSLSocket.cipher
1910[clinic start generated code]*/
1911
1912static PyObject *
1913_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1914/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001915{
1916 const SSL_CIPHER *current;
1917
1918 if (self->ssl == NULL)
1919 Py_RETURN_NONE;
1920 current = SSL_get_current_cipher(self->ssl);
1921 if (current == NULL)
1922 Py_RETURN_NONE;
1923 return cipher_to_tuple(current);
1924}
1925
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001926/*[clinic input]
1927_ssl._SSLSocket.version
1928[clinic start generated code]*/
1929
1930static PyObject *
1931_ssl__SSLSocket_version_impl(PySSLSocket *self)
1932/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001933{
1934 const char *version;
1935
1936 if (self->ssl == NULL)
1937 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001938 if (!SSL_is_init_finished(self->ssl)) {
1939 /* handshake not finished */
1940 Py_RETURN_NONE;
1941 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001942 version = SSL_get_version(self->ssl);
1943 if (!strcmp(version, "unknown"))
1944 Py_RETURN_NONE;
1945 return PyUnicode_FromString(version);
1946}
1947
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001948/*[clinic input]
1949_ssl._SSLSocket.selected_alpn_protocol
1950[clinic start generated code]*/
1951
1952static PyObject *
1953_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1954/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1955{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001956 const unsigned char *out;
1957 unsigned int outlen;
1958
1959 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1960
1961 if (out == NULL)
1962 Py_RETURN_NONE;
1963 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001964}
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001965
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001966/*[clinic input]
1967_ssl._SSLSocket.compression
1968[clinic start generated code]*/
1969
1970static PyObject *
1971_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1972/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1973{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001974#ifdef OPENSSL_NO_COMP
1975 Py_RETURN_NONE;
1976#else
1977 const COMP_METHOD *comp_method;
1978 const char *short_name;
1979
1980 if (self->ssl == NULL)
1981 Py_RETURN_NONE;
1982 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001983 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001984 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001985 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001986 if (short_name == NULL)
1987 Py_RETURN_NONE;
1988 return PyUnicode_DecodeFSDefault(short_name);
1989#endif
1990}
1991
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001992static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1993 Py_INCREF(self->ctx);
1994 return self->ctx;
1995}
1996
1997static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1998 void *closure) {
1999
Christian Heimes7f1305e2021-04-17 20:06:38 +02002000 if (PyObject_TypeCheck(value, self->ctx->state->PySSLContext_Type)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002001 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002002 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002003 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Christian Heimes77cde502021-03-21 16:13:09 +01002004 /* Set SSL* internal msg_callback to state of new context's state */
2005 SSL_set_msg_callback(
2006 self->ssl,
2007 self->ctx->msg_cb ? _PySSL_msg_callback : NULL
2008 );
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002009 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002010 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002011 return -1;
2012 }
2013
2014 return 0;
2015}
2016
2017PyDoc_STRVAR(PySSL_set_context_doc,
2018"_setter_context(ctx)\n\
2019\
2020This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002021used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002022on the SSLContext to change the certificate information associated with the\n\
2023SSLSocket before the cryptographic exchange handshake messages\n");
2024
2025
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002026static PyObject *
2027PySSL_get_server_side(PySSLSocket *self, void *c)
2028{
2029 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2030}
2031
2032PyDoc_STRVAR(PySSL_get_server_side_doc,
2033"Whether this is a server-side socket.");
2034
2035static PyObject *
2036PySSL_get_server_hostname(PySSLSocket *self, void *c)
2037{
2038 if (self->server_hostname == NULL)
2039 Py_RETURN_NONE;
2040 Py_INCREF(self->server_hostname);
2041 return self->server_hostname;
2042}
2043
2044PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2045"The currently set server hostname (for SNI).");
2046
2047static PyObject *
2048PySSL_get_owner(PySSLSocket *self, void *c)
2049{
2050 PyObject *owner;
2051
2052 if (self->owner == NULL)
2053 Py_RETURN_NONE;
2054
2055 owner = PyWeakref_GetObject(self->owner);
2056 Py_INCREF(owner);
2057 return owner;
2058}
2059
2060static int
2061PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2062{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002063 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002064 if (self->owner == NULL)
2065 return -1;
2066 return 0;
2067}
2068
2069PyDoc_STRVAR(PySSL_get_owner_doc,
2070"The Python-level owner of this object.\
2071Passed as \"self\" in servername callback.");
2072
Christian Heimesc7f70692019-05-31 11:44:05 +02002073static int
2074PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2075{
2076 Py_VISIT(self->exc_type);
2077 Py_VISIT(self->exc_value);
2078 Py_VISIT(self->exc_tb);
2079 return 0;
2080}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002081
Christian Heimesc7f70692019-05-31 11:44:05 +02002082static int
2083PySSL_clear(PySSLSocket *self)
2084{
2085 Py_CLEAR(self->exc_type);
2086 Py_CLEAR(self->exc_value);
2087 Py_CLEAR(self->exc_tb);
2088 return 0;
2089}
2090
2091static void
2092PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002093{
Christian Heimes5c36da72020-11-20 09:40:12 +01002094 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002095 if (self->ssl)
2096 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002097 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002098 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002099 Py_XDECREF(self->server_hostname);
2100 Py_XDECREF(self->owner);
Victor Stinner32bd68c2020-12-01 10:37:39 +01002101 PyObject_Free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01002102 Py_DECREF(tp);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002103}
2104
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002105/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002106 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002107 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002108 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002109
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002110static int
Victor Stinner14690702015-04-06 22:46:13 +02002111PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002112{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002113 int rc;
2114#ifdef HAVE_POLL
2115 struct pollfd pollfd;
2116 _PyTime_t ms;
2117#else
2118 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002119 fd_set fds;
2120 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002121#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002122
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002123 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002124 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002125 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002126 else if (timeout < 0) {
2127 if (s->sock_timeout > 0)
2128 return SOCKET_HAS_TIMED_OUT;
2129 else
2130 return SOCKET_IS_BLOCKING;
2131 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002132
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002133 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002134 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002135 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002137 /* Prefer poll, if available, since you can poll() any fd
2138 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002139#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002140 pollfd.fd = s->sock_fd;
2141 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002142
Victor Stinner14690702015-04-06 22:46:13 +02002143 /* timeout is in seconds, poll() uses milliseconds */
2144 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002145 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002146
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002147 PySSL_BEGIN_ALLOW_THREADS
2148 rc = poll(&pollfd, 1, (int)ms);
2149 PySSL_END_ALLOW_THREADS
2150#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002151 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002152 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002153 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002154
Victor Stinner14690702015-04-06 22:46:13 +02002155 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002156
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002157 FD_ZERO(&fds);
2158 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002159
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002160 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002161 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002162 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002163 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002164 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002165 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002166 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002167 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002168#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002169
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002170 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2171 (when we are able to write or when there's something to read) */
2172 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002173}
2174
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002175/*[clinic input]
2176_ssl._SSLSocket.write
2177 b: Py_buffer
2178 /
2179
2180Writes the bytes-like object b into the SSL object.
2181
2182Returns the number of bytes written.
2183[clinic start generated code]*/
2184
2185static PyObject *
2186_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2187/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002188{
Christian Heimes89d15502021-04-19 06:55:30 +02002189 size_t count = 0;
2190 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002191 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002192 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002193 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002194 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002195 _PyTime_t timeout, deadline = 0;
2196 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002197
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002198 if (sock != NULL) {
2199 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002200 _setSSLError(get_state_sock(self),
2201 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002202 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2203 return NULL;
2204 }
2205 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002206 }
2207
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002208 if (sock != NULL) {
2209 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002210 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002211 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2212 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2213 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002214
Victor Stinner14690702015-04-06 22:46:13 +02002215 timeout = GET_SOCKET_TIMEOUT(sock);
2216 has_timeout = (timeout > 0);
2217 if (has_timeout)
2218 deadline = _PyTime_GetMonotonicClock() + timeout;
2219
2220 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002221 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002222 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002223 "The write operation timed out");
2224 goto error;
2225 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002226 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002227 "Underlying socket has been closed.");
2228 goto error;
2229 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002230 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002231 "Underlying socket too large for select().");
2232 goto error;
2233 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002234
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002235 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002236 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes89d15502021-04-19 06:55:30 +02002237 retval = SSL_write_ex(self->ssl, b->buf, (int)b->len, &count);
2238 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002239 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002240 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002241
2242 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002243 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002244
Victor Stinner14690702015-04-06 22:46:13 +02002245 if (has_timeout)
2246 timeout = deadline - _PyTime_GetMonotonicClock();
2247
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002248 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002249 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002250 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002251 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002252 } else {
2253 sockstate = SOCKET_OPERATION_OK;
2254 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002255
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002256 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002257 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002258 "The write operation timed out");
2259 goto error;
2260 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002261 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002262 "Underlying socket has been closed.");
2263 goto error;
2264 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2265 break;
2266 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002267 } while (err.ssl == SSL_ERROR_WANT_READ ||
2268 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002269
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002270 Py_XDECREF(sock);
Christian Heimes89d15502021-04-19 06:55:30 +02002271 if (retval == 0)
2272 return PySSL_SetError(self, retval, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002273 if (PySSL_ChainExceptions(self) < 0)
2274 return NULL;
Christian Heimes89d15502021-04-19 06:55:30 +02002275 return PyLong_FromSize_t(count);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002276error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002277 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002278 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002279 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002280}
2281
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002282/*[clinic input]
2283_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002284
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002285Returns the number of already decrypted bytes available for read, pending on the connection.
2286[clinic start generated code]*/
2287
2288static PyObject *
2289_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2290/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002291{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002292 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002293 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002294
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002295 PySSL_BEGIN_ALLOW_THREADS
2296 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002297 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002298 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002299 self->err = err;
2300
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002301 if (count < 0)
2302 return PySSL_SetError(self, count, __FILE__, __LINE__);
2303 else
2304 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002305}
2306
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002307/*[clinic input]
2308_ssl._SSLSocket.read
2309 size as len: int
2310 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002311 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002312 ]
2313 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002314
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002315Read up to size bytes from the SSL socket.
2316[clinic start generated code]*/
2317
2318static PyObject *
2319_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2320 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002321/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002322{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002323 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002324 char *mem;
Christian Heimes89d15502021-04-19 06:55:30 +02002325 size_t count = 0;
2326 int retval;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002327 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002328 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002329 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002330 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002331 _PyTime_t timeout, deadline = 0;
2332 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002333
Martin Panter5503d472016-03-27 05:35:19 +00002334 if (!group_right_1 && len < 0) {
2335 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2336 return NULL;
2337 }
2338
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002339 if (sock != NULL) {
2340 if (((PyObject*)sock) == Py_None) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002341 _setSSLError(get_state_sock(self),
2342 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002343 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2344 return NULL;
2345 }
2346 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002347 }
2348
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002349 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002350 dest = PyBytes_FromStringAndSize(NULL, len);
2351 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002352 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002353 if (len == 0) {
2354 Py_XDECREF(sock);
2355 return dest;
2356 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002357 mem = PyBytes_AS_STRING(dest);
2358 }
2359 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002360 mem = buffer->buf;
2361 if (len <= 0 || len > buffer->len) {
2362 len = (int) buffer->len;
2363 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002364 PyErr_SetString(PyExc_OverflowError,
2365 "maximum length can't fit in a C 'int'");
2366 goto error;
2367 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002368 if (len == 0) {
2369 count = 0;
2370 goto done;
2371 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002372 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002373 }
2374
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002375 if (sock != NULL) {
2376 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002377 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002378 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2379 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2380 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002381
Victor Stinner14690702015-04-06 22:46:13 +02002382 timeout = GET_SOCKET_TIMEOUT(sock);
2383 has_timeout = (timeout > 0);
2384 if (has_timeout)
2385 deadline = _PyTime_GetMonotonicClock() + timeout;
2386
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002387 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002388 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes89d15502021-04-19 06:55:30 +02002389 retval = SSL_read_ex(self->ssl, mem, len, &count);
2390 err = _PySSL_errno(retval == 0, self->ssl, retval);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002391 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002392 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002393
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002394 if (PyErr_CheckSignals())
2395 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002396
Victor Stinner14690702015-04-06 22:46:13 +02002397 if (has_timeout)
2398 timeout = deadline - _PyTime_GetMonotonicClock();
2399
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002400 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002401 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002402 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002403 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002404 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002405 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002406 {
2407 count = 0;
2408 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002409 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002410 else
2411 sockstate = SOCKET_OPERATION_OK;
2412
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002413 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002414 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002415 "The read operation timed out");
2416 goto error;
2417 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2418 break;
2419 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002420 } while (err.ssl == SSL_ERROR_WANT_READ ||
2421 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002422
Christian Heimes89d15502021-04-19 06:55:30 +02002423 if (retval == 0) {
2424 PySSL_SetError(self, retval, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002425 goto error;
2426 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002427 if (self->exc_type != NULL)
2428 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002429
2430done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002431 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002432 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002433 _PyBytes_Resize(&dest, count);
2434 return dest;
2435 }
2436 else {
Christian Heimes89d15502021-04-19 06:55:30 +02002437 return PyLong_FromSize_t(count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002438 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002439
2440error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002441 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002442 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002443 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002444 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002445 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002446}
2447
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002448/*[clinic input]
2449_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002450
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002451Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002452[clinic start generated code]*/
2453
2454static PyObject *
2455_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002456/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002457{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002458 _PySSLError err;
2459 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002460 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002461 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002462 _PyTime_t timeout, deadline = 0;
2463 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002464
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002465 if (sock != NULL) {
2466 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002467 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002468 _setSSLError(get_state_sock(self),
2469 "Underlying socket connection gone",
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002470 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2471 return NULL;
2472 }
2473 Py_INCREF(sock);
2474
2475 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002476 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002477 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2478 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002479 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002480
Victor Stinner14690702015-04-06 22:46:13 +02002481 timeout = GET_SOCKET_TIMEOUT(sock);
2482 has_timeout = (timeout > 0);
2483 if (has_timeout)
2484 deadline = _PyTime_GetMonotonicClock() + timeout;
2485
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002486 while (1) {
2487 PySSL_BEGIN_ALLOW_THREADS
2488 /* Disable read-ahead so that unwrap can work correctly.
2489 * Otherwise OpenSSL might read in too much data,
2490 * eating clear text data that happens to be
2491 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002492 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002493 * function is used and the shutdown_seen_zero != 0
2494 * condition is met.
2495 */
2496 if (self->shutdown_seen_zero)
2497 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002498 ret = SSL_shutdown(self->ssl);
2499 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002500 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002501 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002502
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002503 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002504 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002505 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002506 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002507 /* Don't loop endlessly; instead preserve legacy
2508 behaviour of trying SSL_shutdown() only twice.
2509 This looks necessary for OpenSSL < 0.9.8m */
2510 if (++zeros > 1)
2511 break;
2512 /* Shutdown was sent, now try receiving */
2513 self->shutdown_seen_zero = 1;
2514 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002515 }
2516
Victor Stinner14690702015-04-06 22:46:13 +02002517 if (has_timeout)
2518 timeout = deadline - _PyTime_GetMonotonicClock();
2519
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002520 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002521 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002522 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002523 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002524 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002525 else
2526 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002527
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002528 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002529 if (err.ssl == SSL_ERROR_WANT_READ)
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002530 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002531 "The read operation timed out");
2532 else
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002533 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002534 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002535 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002536 }
2537 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002538 PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002539 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002540 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002541 }
2542 else if (sockstate != SOCKET_OPERATION_OK)
2543 /* Retain the SSL error code */
2544 break;
2545 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002546 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002547 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002548 PySSL_SetError(self, ret, __FILE__, __LINE__);
2549 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002550 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002551 if (self->exc_type != NULL)
2552 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002553 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002554 /* It's already INCREF'ed */
2555 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002556 else
2557 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002558
2559error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002560 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002561 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002562 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002563}
2564
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002565/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002566_ssl._SSLSocket.get_channel_binding
2567 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002568
Christian Heimes141c5e82018-02-24 21:10:57 +01002569Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002570
Christian Heimes141c5e82018-02-24 21:10:57 +01002571Raise ValueError if the requested `cb_type` is not supported. Return bytes
2572of the data or None if the data is not available (e.g. before the handshake).
2573Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002574[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002575
Antoine Pitroud6494802011-07-21 01:11:30 +02002576static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002577_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2578 const char *cb_type)
2579/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002580{
Antoine Pitroud6494802011-07-21 01:11:30 +02002581 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002582 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002583
Christian Heimes141c5e82018-02-24 21:10:57 +01002584 if (strcmp(cb_type, "tls-unique") == 0) {
2585 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2586 /* if session is resumed XOR we are the client */
2587 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2588 }
2589 else {
2590 /* if a new session XOR we are the server */
2591 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2592 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002593 }
2594 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002595 PyErr_Format(
2596 PyExc_ValueError,
2597 "'%s' channel binding type not implemented",
2598 cb_type
2599 );
2600 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002601 }
2602
2603 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002604 if (len == 0)
2605 Py_RETURN_NONE;
2606
Christian Heimes141c5e82018-02-24 21:10:57 +01002607 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002608}
2609
Christian Heimes9fb051f2018-09-23 08:32:31 +02002610/*[clinic input]
2611_ssl._SSLSocket.verify_client_post_handshake
2612
2613Initiate TLS 1.3 post-handshake authentication
2614[clinic start generated code]*/
2615
2616static PyObject *
2617_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2618/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2619{
2620#ifdef TLS1_3_VERSION
2621 int err = SSL_verify_client_post_handshake(self->ssl);
2622 if (err == 0)
Christian Heimes7f1305e2021-04-17 20:06:38 +02002623 return _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes9fb051f2018-09-23 08:32:31 +02002624 else
2625 Py_RETURN_NONE;
2626#else
2627 PyErr_SetString(PyExc_NotImplementedError,
2628 "Post-handshake auth is not supported by your "
2629 "OpenSSL version.");
2630 return NULL;
2631#endif
2632}
2633
Christian Heimes99a65702016-09-10 23:44:53 +02002634static SSL_SESSION*
2635_ssl_session_dup(SSL_SESSION *session) {
2636 SSL_SESSION *newsession = NULL;
2637 int slen;
2638 unsigned char *senc = NULL, *p;
2639 const unsigned char *const_p;
2640
2641 if (session == NULL) {
2642 PyErr_SetString(PyExc_ValueError, "Invalid session");
2643 goto error;
2644 }
2645
2646 /* get length */
2647 slen = i2d_SSL_SESSION(session, NULL);
2648 if (slen == 0 || slen > 0xFF00) {
2649 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2650 goto error;
2651 }
2652 if ((senc = PyMem_Malloc(slen)) == NULL) {
2653 PyErr_NoMemory();
2654 goto error;
2655 }
2656 p = senc;
2657 if (!i2d_SSL_SESSION(session, &p)) {
2658 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2659 goto error;
2660 }
2661 const_p = senc;
2662 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2663 if (session == NULL) {
2664 goto error;
2665 }
2666 PyMem_Free(senc);
2667 return newsession;
2668 error:
2669 if (senc != NULL) {
2670 PyMem_Free(senc);
2671 }
2672 return NULL;
2673}
Christian Heimes99a65702016-09-10 23:44:53 +02002674
2675static PyObject *
2676PySSL_get_session(PySSLSocket *self, void *closure) {
2677 /* get_session can return sessions from a server-side connection,
2678 * it does not check for handshake done or client socket. */
2679 PySSLSession *pysess;
2680 SSL_SESSION *session;
2681
Christian Heimes99a65702016-09-10 23:44:53 +02002682 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2683 * https://github.com/openssl/openssl/issues/1550 */
2684 session = SSL_get0_session(self->ssl); /* borrowed reference */
2685 if (session == NULL) {
2686 Py_RETURN_NONE;
2687 }
2688 if ((session = _ssl_session_dup(session)) == NULL) {
2689 return NULL;
2690 }
Christian Heimes99a65702016-09-10 23:44:53 +02002691 session = SSL_get1_session(self->ssl);
2692 if (session == NULL) {
2693 Py_RETURN_NONE;
2694 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02002695 pysess = PyObject_GC_New(PySSLSession, self->ctx->state->PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002696 if (pysess == NULL) {
2697 SSL_SESSION_free(session);
2698 return NULL;
2699 }
2700
2701 assert(self->ctx);
2702 pysess->ctx = self->ctx;
2703 Py_INCREF(pysess->ctx);
2704 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002705 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002706 return (PyObject *)pysess;
2707}
2708
2709static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2710 void *closure)
2711 {
2712 PySSLSession *pysess;
Christian Heimes99a65702016-09-10 23:44:53 +02002713 SSL_SESSION *session;
Christian Heimes99a65702016-09-10 23:44:53 +02002714 int result;
2715
Christian Heimes7f1305e2021-04-17 20:06:38 +02002716 if (!Py_IS_TYPE(value, get_state_sock(self)->PySSLSession_Type)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002717 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002718 return -1;
2719 }
2720 pysess = (PySSLSession *)value;
2721
2722 if (self->ctx->ctx != pysess->ctx->ctx) {
2723 PyErr_SetString(PyExc_ValueError,
2724 "Session refers to a different SSLContext.");
2725 return -1;
2726 }
2727 if (self->socket_type != PY_SSL_CLIENT) {
2728 PyErr_SetString(PyExc_ValueError,
2729 "Cannot set session for server-side SSLSocket.");
2730 return -1;
2731 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002732 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002733 PyErr_SetString(PyExc_ValueError,
2734 "Cannot set session after handshake.");
2735 return -1;
2736 }
Christian Heimes99a65702016-09-10 23:44:53 +02002737 /* duplicate session */
2738 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2739 return -1;
2740 }
2741 result = SSL_set_session(self->ssl, session);
2742 /* free duplicate, SSL_set_session() bumps ref count */
2743 SSL_SESSION_free(session);
Christian Heimes99a65702016-09-10 23:44:53 +02002744 if (result == 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002745 _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes99a65702016-09-10 23:44:53 +02002746 return -1;
2747 }
2748 return 0;
2749}
2750
2751PyDoc_STRVAR(PySSL_set_session_doc,
2752"_setter_session(session)\n\
2753\
2754Get / set SSLSession.");
2755
2756static PyObject *
2757PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2758 if (SSL_session_reused(self->ssl)) {
2759 Py_RETURN_TRUE;
2760 } else {
2761 Py_RETURN_FALSE;
2762 }
2763}
2764
2765PyDoc_STRVAR(PySSL_get_session_reused_doc,
2766"Was the client session reused during handshake?");
2767
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002768static PyGetSetDef ssl_getsetlist[] = {
2769 {"context", (getter) PySSL_get_context,
2770 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002771 {"server_side", (getter) PySSL_get_server_side, NULL,
2772 PySSL_get_server_side_doc},
2773 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2774 PySSL_get_server_hostname_doc},
2775 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2776 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002777 {"session", (getter) PySSL_get_session,
2778 (setter) PySSL_set_session, PySSL_set_session_doc},
2779 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2780 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002781 {NULL}, /* sentinel */
2782};
2783
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002784static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002785 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2786 _SSL__SSLSOCKET_WRITE_METHODDEF
2787 _SSL__SSLSOCKET_READ_METHODDEF
2788 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002789 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2790 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002791 _SSL__SSLSOCKET_CIPHER_METHODDEF
2792 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2793 _SSL__SSLSOCKET_VERSION_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002794 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2795 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2796 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002797 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002798 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002799};
2800
Christian Heimes5c36da72020-11-20 09:40:12 +01002801static PyType_Slot PySSLSocket_slots[] = {
2802 {Py_tp_methods, PySSLMethods},
2803 {Py_tp_getset, ssl_getsetlist},
2804 {Py_tp_dealloc, PySSL_dealloc},
2805 {Py_tp_traverse, PySSL_traverse},
2806 {Py_tp_clear, PySSL_clear},
2807 {0, 0},
2808};
2809
2810static PyType_Spec PySSLSocket_spec = {
2811 "_ssl._SSLSocket",
2812 sizeof(PySSLSocket),
2813 0,
2814 Py_TPFLAGS_DEFAULT,
2815 PySSLSocket_slots,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002816};
2817
Antoine Pitrou152efa22010-05-16 18:19:27 +00002818/*
2819 * _SSLContext objects
2820 */
2821
Christian Heimes5fe668c2016-09-12 00:01:11 +02002822static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02002823_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002824{
2825 int mode;
2826 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2827
2828 switch(n) {
2829 case PY_SSL_CERT_NONE:
2830 mode = SSL_VERIFY_NONE;
2831 break;
2832 case PY_SSL_CERT_OPTIONAL:
2833 mode = SSL_VERIFY_PEER;
2834 break;
2835 case PY_SSL_CERT_REQUIRED:
2836 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2837 break;
2838 default:
2839 PyErr_SetString(PyExc_ValueError,
2840 "invalid value for verify_mode");
2841 return -1;
2842 }
Christian Heimesf0f59302019-07-01 08:29:17 +02002843
2844 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
2845 * server sockets and SSL_set_post_handshake_auth() for client. */
2846
Christian Heimes5fe668c2016-09-12 00:01:11 +02002847 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02002848 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2849 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002850 return 0;
2851}
2852
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002853/*[clinic input]
2854@classmethod
2855_ssl._SSLContext.__new__
2856 protocol as proto_version: int
2857 /
2858[clinic start generated code]*/
2859
Antoine Pitrou152efa22010-05-16 18:19:27 +00002860static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002861_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2862/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002863{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002864 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002865 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002866 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002867 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002868 int result;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002869
Christian Heimes7f1305e2021-04-17 20:06:38 +02002870 /* slower approach, walk MRO and get borrowed reference to module.
2871 * _PyType_GetModuleByDef is required for SSLContext subclasses */
2872 PyObject *module = _PyType_GetModuleByDef(type, &_sslmodule_def);
2873 if (module == NULL) {
2874 PyErr_SetString(PyExc_RuntimeError,
2875 "Cannot find internal module state");
2876 return NULL;
2877 }
2878
Antoine Pitrou152efa22010-05-16 18:19:27 +00002879 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes6e8cda92020-05-16 03:33:05 +02002880 switch(proto_version) {
2881#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
2882 case PY_SSL_VERSION_SSL3:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002883 ctx = SSL_CTX_new(SSLv3_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02002884 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05002885#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002886#if (defined(TLS1_VERSION) && \
2887 !defined(OPENSSL_NO_TLS1) && \
2888 !defined(OPENSSL_NO_TLS1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002889 case PY_SSL_VERSION_TLS1:
2890 ctx = SSL_CTX_new(TLSv1_method());
2891 break;
Victor Stinner3de49192011-05-09 00:42:58 +02002892#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002893#if (defined(TLS1_1_VERSION) && \
2894 !defined(OPENSSL_NO_TLS1_1) && \
2895 !defined(OPENSSL_NO_TLS1_1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002896 case PY_SSL_VERSION_TLS1_1:
2897 ctx = SSL_CTX_new(TLSv1_1_method());
2898 break;
2899#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002900#if (defined(TLS1_2_VERSION) && \
2901 !defined(OPENSSL_NO_TLS1_2) && \
2902 !defined(OPENSSL_NO_TLS1_2_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002903 case PY_SSL_VERSION_TLS1_2:
2904 ctx = SSL_CTX_new(TLSv1_2_method());
2905 break;
2906#endif
2907 case PY_SSL_VERSION_TLS:
2908 /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002909 ctx = SSL_CTX_new(TLS_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02002910 break;
2911 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes5fe668c2016-09-12 00:01:11 +02002912 ctx = SSL_CTX_new(TLS_client_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02002913 break;
2914 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes5fe668c2016-09-12 00:01:11 +02002915 ctx = SSL_CTX_new(TLS_server_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02002916 break;
2917 default:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002918 proto_version = -1;
Christian Heimes6e8cda92020-05-16 03:33:05 +02002919 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002920 PySSL_END_ALLOW_THREADS
2921
2922 if (proto_version == -1) {
2923 PyErr_SetString(PyExc_ValueError,
Christian Heimes6e8cda92020-05-16 03:33:05 +02002924 "invalid or unsupported protocol version");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002925 return NULL;
2926 }
2927 if (ctx == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02002928 _setSSLError(get_ssl_state(module), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002929 return NULL;
2930 }
2931
2932 assert(type != NULL && type->tp_alloc != NULL);
2933 self = (PySSLContext *) type->tp_alloc(type, 0);
2934 if (self == NULL) {
2935 SSL_CTX_free(ctx);
2936 return NULL;
2937 }
2938 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002939 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01002940 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02002941 self->msg_cb = NULL;
Christian Heimesc7f70692019-05-31 11:44:05 +02002942 self->keylog_filename = NULL;
2943 self->keylog_bio = NULL;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002944 self->alpn_protocols = NULL;
Christian Heimes11a14932018-02-24 02:35:08 +01002945 self->set_sni_cb = NULL;
Christian Heimes7f1305e2021-04-17 20:06:38 +02002946 self->state = get_ssl_state(module);
2947
Christian Heimes1aa9a752013-12-02 02:41:19 +01002948 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002949 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2950 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02002951 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02002952 Py_DECREF(self);
2953 return NULL;
2954 }
2955 } else {
2956 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02002957 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02002958 Py_DECREF(self);
2959 return NULL;
2960 }
2961 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002962 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002963 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2964 if (proto_version != PY_SSL_VERSION_SSL2)
2965 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002966 if (proto_version != PY_SSL_VERSION_SSL3)
2967 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002968 /* Minimal security flags for server and client side context.
2969 * Client sockets ignore server-side parameters. */
2970#ifdef SSL_OP_NO_COMPRESSION
2971 options |= SSL_OP_NO_COMPRESSION;
2972#endif
2973#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2974 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2975#endif
2976#ifdef SSL_OP_SINGLE_DH_USE
2977 options |= SSL_OP_SINGLE_DH_USE;
2978#endif
2979#ifdef SSL_OP_SINGLE_ECDH_USE
2980 options |= SSL_OP_SINGLE_ECDH_USE;
2981#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02002982#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
2983 /* Make OpenSSL 3.0.0 behave like 1.1.1 */
2984 options |= SSL_OP_IGNORE_UNEXPECTED_EOF;
2985#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002986 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002987
Semen Zhydenko1295e112017-10-15 21:28:31 +02002988 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02002989 * It's far from perfect but gives users a better head start. */
2990 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01002991#if PY_SSL_DEFAULT_CIPHERS == 2
2992 /* stick to OpenSSL's default settings */
2993 result = 1;
2994#else
2995 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
2996#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02002997 } else {
2998 /* SSLv2 needs MD5 */
2999 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3000 }
3001 if (result == 0) {
3002 Py_DECREF(self);
3003 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003004 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Christian Heimes358cfd42016-09-10 22:43:48 +02003005 "No cipher can be selected.");
3006 return NULL;
3007 }
3008
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003009 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
Christian Heimes39258d32021-04-17 11:36:35 +02003010 usage for no cost at all. */
3011 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003012
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003013#define SID_CTX "Python"
3014 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3015 sizeof(SID_CTX));
3016#undef SID_CTX
3017
Christian Heimes61d478c2018-01-27 15:51:38 +01003018 params = SSL_CTX_get0_param(self->ctx);
Christian Heimes61d478c2018-01-27 15:51:38 +01003019 /* Improve trust chain building when cross-signed intermediate
3020 certificates are present. See https://bugs.python.org/issue23476. */
3021 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Christian Heimes61d478c2018-01-27 15:51:38 +01003022 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003023
Christian Heimes9fb051f2018-09-23 08:32:31 +02003024#ifdef TLS1_3_VERSION
3025 self->post_handshake_auth = 0;
3026 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3027#endif
3028
Antoine Pitrou152efa22010-05-16 18:19:27 +00003029 return (PyObject *)self;
3030}
3031
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003032static int
3033context_traverse(PySSLContext *self, visitproc visit, void *arg)
3034{
Christian Heimes11a14932018-02-24 02:35:08 +01003035 Py_VISIT(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003036 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003037 return 0;
3038}
3039
3040static int
3041context_clear(PySSLContext *self)
3042{
Christian Heimes11a14932018-02-24 02:35:08 +01003043 Py_CLEAR(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003044 Py_CLEAR(self->msg_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003045 Py_CLEAR(self->keylog_filename);
3046 if (self->keylog_bio != NULL) {
3047 PySSL_BEGIN_ALLOW_THREADS
3048 BIO_free_all(self->keylog_bio);
3049 PySSL_END_ALLOW_THREADS
3050 self->keylog_bio = NULL;
3051 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003052 return 0;
3053}
3054
Antoine Pitrou152efa22010-05-16 18:19:27 +00003055static void
3056context_dealloc(PySSLContext *self)
3057{
Christian Heimes5c36da72020-11-20 09:40:12 +01003058 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09003059 /* bpo-31095: UnTrack is needed before calling any callbacks */
3060 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003061 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003062 SSL_CTX_free(self->ctx);
Christian Heimes39258d32021-04-17 11:36:35 +02003063 PyMem_FREE(self->alpn_protocols);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003064 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01003065 Py_DECREF(tp);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003066}
3067
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003068/*[clinic input]
3069_ssl._SSLContext.set_ciphers
3070 cipherlist: str
3071 /
3072[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003073
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003074static PyObject *
3075_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3076/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3077{
3078 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003079 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003080 /* Clearing the error queue is necessary on some OpenSSL versions,
3081 otherwise the error will be reported again when another SSL call
3082 is done. */
3083 ERR_clear_error();
Christian Heimes7f1305e2021-04-17 20:06:38 +02003084 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003085 "No cipher can be selected.");
3086 return NULL;
3087 }
3088 Py_RETURN_NONE;
3089}
3090
Christian Heimes25bfcd52016-09-06 00:04:45 +02003091/*[clinic input]
3092_ssl._SSLContext.get_ciphers
3093[clinic start generated code]*/
3094
3095static PyObject *
3096_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3097/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3098{
3099 SSL *ssl = NULL;
3100 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003101 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003102 int i=0;
3103 PyObject *result = NULL, *dct;
3104
3105 ssl = SSL_new(self->ctx);
3106 if (ssl == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003107 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes25bfcd52016-09-06 00:04:45 +02003108 goto exit;
3109 }
3110 sk = SSL_get_ciphers(ssl);
3111
3112 result = PyList_New(sk_SSL_CIPHER_num(sk));
3113 if (result == NULL) {
3114 goto exit;
3115 }
3116
3117 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3118 cipher = sk_SSL_CIPHER_value(sk, i);
3119 dct = cipher_to_dict(cipher);
3120 if (dct == NULL) {
3121 Py_CLEAR(result);
3122 goto exit;
3123 }
3124 PyList_SET_ITEM(result, i, dct);
3125 }
3126
3127 exit:
3128 if (ssl != NULL)
3129 SSL_free(ssl);
3130 return result;
3131
3132}
Christian Heimes25bfcd52016-09-06 00:04:45 +02003133
3134
Benjamin Petersoncca27322015-01-23 16:35:37 -05003135static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003136do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3137 const unsigned char *server_protocols, unsigned int server_protocols_len,
3138 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003139{
Benjamin Peterson88615022015-01-23 17:30:26 -05003140 int ret;
3141 if (client_protocols == NULL) {
3142 client_protocols = (unsigned char *)"";
3143 client_protocols_len = 0;
3144 }
3145 if (server_protocols == NULL) {
3146 server_protocols = (unsigned char *)"";
3147 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003148 }
3149
Benjamin Peterson88615022015-01-23 17:30:26 -05003150 ret = SSL_select_next_proto(out, outlen,
3151 server_protocols, server_protocols_len,
3152 client_protocols, client_protocols_len);
3153 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3154 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003155
3156 return SSL_TLSEXT_ERR_OK;
3157}
3158
Benjamin Petersoncca27322015-01-23 16:35:37 -05003159static int
3160_selectALPN_cb(SSL *s,
3161 const unsigned char **out, unsigned char *outlen,
3162 const unsigned char *client_protocols, unsigned int client_protocols_len,
3163 void *args)
3164{
3165 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003166 return do_protocol_selection(1, (unsigned char **)out, outlen,
3167 ctx->alpn_protocols, ctx->alpn_protocols_len,
3168 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003169}
Benjamin Petersoncca27322015-01-23 16:35:37 -05003170
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003171/*[clinic input]
3172_ssl._SSLContext._set_alpn_protocols
3173 protos: Py_buffer
3174 /
3175[clinic start generated code]*/
3176
Benjamin Petersoncca27322015-01-23 16:35:37 -05003177static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003178_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3179 Py_buffer *protos)
3180/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003181{
Victor Stinner5a615592017-09-14 01:10:30 -07003182 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003183 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003184 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003185 return NULL;
3186 }
3187
Victor Stinner00d7abd2020-12-01 09:56:42 +01003188 PyMem_Free(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003189 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003190 if (!self->alpn_protocols)
3191 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003192 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003193 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003194
3195 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3196 return PyErr_NoMemory();
3197 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3198
Benjamin Petersoncca27322015-01-23 16:35:37 -05003199 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003200}
3201
Antoine Pitrou152efa22010-05-16 18:19:27 +00003202static PyObject *
3203get_verify_mode(PySSLContext *self, void *c)
3204{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003205 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3206 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3207 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3208 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003209 case SSL_VERIFY_NONE:
3210 return PyLong_FromLong(PY_SSL_CERT_NONE);
3211 case SSL_VERIFY_PEER:
3212 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3213 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3214 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3215 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02003216 PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003217 "invalid return value from SSL_CTX_get_verify_mode");
3218 return NULL;
3219}
3220
3221static int
3222set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3223{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003224 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003225 if (!PyArg_Parse(arg, "i", &n))
3226 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003227 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003228 PyErr_SetString(PyExc_ValueError,
3229 "Cannot set verify_mode to CERT_NONE when "
3230 "check_hostname is enabled.");
3231 return -1;
3232 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003233 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003234}
3235
3236static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003237get_verify_flags(PySSLContext *self, void *c)
3238{
Christian Heimes598894f2016-09-05 23:19:05 +02003239 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003240 unsigned long flags;
3241
Christian Heimes61d478c2018-01-27 15:51:38 +01003242 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003243 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003244 return PyLong_FromUnsignedLong(flags);
3245}
3246
3247static int
3248set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3249{
Christian Heimes598894f2016-09-05 23:19:05 +02003250 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003251 unsigned long new_flags, flags, set, clear;
3252
3253 if (!PyArg_Parse(arg, "k", &new_flags))
3254 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003255 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003256 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003257 clear = flags & ~new_flags;
3258 set = ~flags & new_flags;
3259 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003260 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003261 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003262 return -1;
3263 }
3264 }
3265 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003266 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003267 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimes22587792013-11-21 23:56:13 +01003268 return -1;
3269 }
3270 }
3271 return 0;
3272}
3273
Christian Heimes698dde12018-02-27 11:54:43 +01003274/* Getter and setter for protocol version */
Christian Heimes698dde12018-02-27 11:54:43 +01003275static int
3276set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3277{
3278 long v;
3279 int result;
3280
3281 if (!PyArg_Parse(arg, "l", &v))
3282 return -1;
3283 if (v > INT_MAX) {
3284 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3285 return -1;
3286 }
3287
3288 switch(self->protocol) {
3289 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3290 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3291 case PY_SSL_VERSION_TLS:
3292 break;
3293 default:
3294 PyErr_SetString(
3295 PyExc_ValueError,
3296 "The context's protocol doesn't support modification of "
3297 "highest and lowest version."
3298 );
3299 return -1;
3300 }
3301
3302 if (what == 0) {
3303 switch(v) {
3304 case PY_PROTO_MINIMUM_SUPPORTED:
3305 v = 0;
3306 break;
3307 case PY_PROTO_MAXIMUM_SUPPORTED:
3308 /* Emulate max for set_min_proto_version */
3309 v = PY_PROTO_MAXIMUM_AVAILABLE;
3310 break;
3311 default:
3312 break;
3313 }
3314 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3315 }
3316 else {
3317 switch(v) {
3318 case PY_PROTO_MAXIMUM_SUPPORTED:
3319 v = 0;
3320 break;
3321 case PY_PROTO_MINIMUM_SUPPORTED:
3322 /* Emulate max for set_min_proto_version */
3323 v = PY_PROTO_MINIMUM_AVAILABLE;
3324 break;
3325 default:
3326 break;
3327 }
3328 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3329 }
3330 if (result == 0) {
3331 PyErr_Format(PyExc_ValueError,
3332 "Unsupported protocol version 0x%x", v);
3333 return -1;
3334 }
3335 return 0;
3336}
3337
3338static PyObject *
3339get_minimum_version(PySSLContext *self, void *c)
3340{
3341 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3342 if (v == 0) {
3343 v = PY_PROTO_MINIMUM_SUPPORTED;
3344 }
3345 return PyLong_FromLong(v);
3346}
3347
3348static int
3349set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3350{
3351 return set_min_max_proto_version(self, arg, 0);
3352}
3353
3354static PyObject *
3355get_maximum_version(PySSLContext *self, void *c)
3356{
3357 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3358 if (v == 0) {
3359 v = PY_PROTO_MAXIMUM_SUPPORTED;
3360 }
3361 return PyLong_FromLong(v);
3362}
3363
3364static int
3365set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3366{
3367 return set_min_max_proto_version(self, arg, 1);
3368}
Christian Heimes698dde12018-02-27 11:54:43 +01003369
Christian Heimes39258d32021-04-17 11:36:35 +02003370#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02003371static PyObject *
3372get_num_tickets(PySSLContext *self, void *c)
3373{
Victor Stinner76611c72019-07-09 13:30:52 +02003374 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003375}
3376
3377static int
3378set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3379{
3380 long num;
3381 if (!PyArg_Parse(arg, "l", &num))
3382 return -1;
3383 if (num < 0) {
3384 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3385 return -1;
3386 }
3387 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3388 PyErr_SetString(PyExc_ValueError,
3389 "SSLContext is not a server context.");
3390 return -1;
3391 }
3392 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3393 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3394 return -1;
3395 }
3396 return 0;
3397}
3398
3399PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3400"Control the number of TLSv1.3 session tickets");
Christian Heimes39258d32021-04-17 11:36:35 +02003401#endif /* TLS1_3_VERSION */
Christian Heimes78c7d522019-06-03 21:00:10 +02003402
matthewhughes9348e836bb2020-07-17 09:59:15 +01003403static PyObject *
3404get_security_level(PySSLContext *self, void *c)
3405{
3406 return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3407}
3408PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
matthewhughes9348e836bb2020-07-17 09:59:15 +01003409
Christian Heimes22587792013-11-21 23:56:13 +01003410static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003411get_options(PySSLContext *self, void *c)
3412{
3413 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3414}
3415
3416static int
3417set_options(PySSLContext *self, PyObject *arg, void *c)
3418{
3419 long new_opts, opts, set, clear;
3420 if (!PyArg_Parse(arg, "l", &new_opts))
3421 return -1;
3422 opts = SSL_CTX_get_options(self->ctx);
3423 clear = opts & ~new_opts;
3424 set = ~opts & new_opts;
3425 if (clear) {
Antoine Pitroub5218772010-05-21 09:56:06 +00003426 SSL_CTX_clear_options(self->ctx, clear);
Antoine Pitroub5218772010-05-21 09:56:06 +00003427 }
3428 if (set)
3429 SSL_CTX_set_options(self->ctx, set);
3430 return 0;
3431}
3432
Christian Heimes1aa9a752013-12-02 02:41:19 +01003433static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003434get_host_flags(PySSLContext *self, void *c)
3435{
3436 return PyLong_FromUnsignedLong(self->hostflags);
3437}
3438
3439static int
3440set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3441{
3442 X509_VERIFY_PARAM *param;
3443 unsigned int new_flags = 0;
3444
3445 if (!PyArg_Parse(arg, "I", &new_flags))
3446 return -1;
3447
3448 param = SSL_CTX_get0_param(self->ctx);
3449 self->hostflags = new_flags;
3450 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3451 return 0;
3452}
3453
3454static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003455get_check_hostname(PySSLContext *self, void *c)
3456{
3457 return PyBool_FromLong(self->check_hostname);
3458}
3459
3460static int
3461set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3462{
3463 int check_hostname;
3464 if (!PyArg_Parse(arg, "p", &check_hostname))
3465 return -1;
3466 if (check_hostname &&
3467 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003468 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003469 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003470 return -1;
3471 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003472 }
3473 self->check_hostname = check_hostname;
3474 return 0;
3475}
3476
Christian Heimes11a14932018-02-24 02:35:08 +01003477static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003478get_post_handshake_auth(PySSLContext *self, void *c) {
3479#if TLS1_3_VERSION
3480 return PyBool_FromLong(self->post_handshake_auth);
3481#else
3482 Py_RETURN_NONE;
3483#endif
3484}
3485
3486#if TLS1_3_VERSION
3487static int
3488set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003489 if (arg == NULL) {
3490 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3491 return -1;
3492 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003493 int pha = PyObject_IsTrue(arg);
3494
3495 if (pha == -1) {
3496 return -1;
3497 }
3498 self->post_handshake_auth = pha;
3499
Christian Heimesf0f59302019-07-01 08:29:17 +02003500 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3501 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003502
3503 return 0;
3504}
3505#endif
3506
3507static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003508get_protocol(PySSLContext *self, void *c) {
3509 return PyLong_FromLong(self->protocol);
3510}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003511
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003512typedef struct {
3513 PyThreadState *thread_state;
3514 PyObject *callable;
3515 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003516 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003517 int error;
3518} _PySSLPasswordInfo;
3519
3520static int
3521_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3522 const char *bad_type_error)
3523{
3524 /* Set the password and size fields of a _PySSLPasswordInfo struct
3525 from a unicode, bytes, or byte array object.
3526 The password field will be dynamically allocated and must be freed
3527 by the caller */
3528 PyObject *password_bytes = NULL;
3529 const char *data = NULL;
3530 Py_ssize_t size;
3531
3532 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003533 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003534 if (!password_bytes) {
3535 goto error;
3536 }
3537 data = PyBytes_AS_STRING(password_bytes);
3538 size = PyBytes_GET_SIZE(password_bytes);
3539 } else if (PyBytes_Check(password)) {
3540 data = PyBytes_AS_STRING(password);
3541 size = PyBytes_GET_SIZE(password);
3542 } else if (PyByteArray_Check(password)) {
3543 data = PyByteArray_AS_STRING(password);
3544 size = PyByteArray_GET_SIZE(password);
3545 } else {
3546 PyErr_SetString(PyExc_TypeError, bad_type_error);
3547 goto error;
3548 }
3549
Victor Stinner9ee02032013-06-23 15:08:23 +02003550 if (size > (Py_ssize_t)INT_MAX) {
3551 PyErr_Format(PyExc_ValueError,
3552 "password cannot be longer than %d bytes", INT_MAX);
3553 goto error;
3554 }
3555
Victor Stinner11ebff22013-07-07 17:07:52 +02003556 PyMem_Free(pw_info->password);
3557 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003558 if (!pw_info->password) {
3559 PyErr_SetString(PyExc_MemoryError,
3560 "unable to allocate password buffer");
3561 goto error;
3562 }
3563 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003564 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003565
3566 Py_XDECREF(password_bytes);
3567 return 1;
3568
3569error:
3570 Py_XDECREF(password_bytes);
3571 return 0;
3572}
3573
3574static int
3575_password_callback(char *buf, int size, int rwflag, void *userdata)
3576{
3577 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3578 PyObject *fn_ret = NULL;
3579
3580 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3581
Christian Heimesd3b73f32021-04-09 15:23:38 +02003582 if (pw_info->error) {
3583 /* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
3584 * callback multiple times which can lead to fatal Python error in
3585 * exception check. */
3586 goto error;
3587 }
3588
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003589 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003590 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003591 if (!fn_ret) {
3592 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3593 core python API, so we could use it to add a frame here */
3594 goto error;
3595 }
3596
3597 if (!_pwinfo_set(pw_info, fn_ret,
3598 "password callback must return a string")) {
3599 goto error;
3600 }
3601 Py_CLEAR(fn_ret);
3602 }
3603
3604 if (pw_info->size > size) {
3605 PyErr_Format(PyExc_ValueError,
3606 "password cannot be longer than %d bytes", size);
3607 goto error;
3608 }
3609
3610 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3611 memcpy(buf, pw_info->password, pw_info->size);
3612 return pw_info->size;
3613
3614error:
3615 Py_XDECREF(fn_ret);
3616 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3617 pw_info->error = 1;
3618 return -1;
3619}
3620
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003621/*[clinic input]
3622_ssl._SSLContext.load_cert_chain
3623 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003624 keyfile: object = None
3625 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003626
3627[clinic start generated code]*/
3628
Antoine Pitroub5218772010-05-21 09:56:06 +00003629static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003630_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3631 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003632/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003633{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003634 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003635 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3636 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003637 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003638 int r;
3639
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003640 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003641 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003642 if (keyfile == Py_None)
3643 keyfile = NULL;
3644 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003645 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3646 PyErr_SetString(PyExc_TypeError,
3647 "certfile should be a valid filesystem path");
3648 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003649 return NULL;
3650 }
3651 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003652 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3653 PyErr_SetString(PyExc_TypeError,
3654 "keyfile should be a valid filesystem path");
3655 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003656 goto error;
3657 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003658 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003659 if (PyCallable_Check(password)) {
3660 pw_info.callable = password;
3661 } else if (!_pwinfo_set(&pw_info, password,
3662 "password should be a string or callable")) {
3663 goto error;
3664 }
3665 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3666 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3667 }
3668 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003669 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3670 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003671 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003672 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003673 if (pw_info.error) {
3674 ERR_clear_error();
3675 /* the password callback has already set the error information */
3676 }
3677 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003678 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003679 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003680 }
3681 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003682 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003683 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003684 goto error;
3685 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003686 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003687 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003688 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3689 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003690 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3691 Py_CLEAR(keyfile_bytes);
3692 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003693 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003694 if (pw_info.error) {
3695 ERR_clear_error();
3696 /* the password callback has already set the error information */
3697 }
3698 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003699 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003700 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003701 }
3702 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003703 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003704 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003705 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003706 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003707 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003708 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003709 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003710 if (r != 1) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003711 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003712 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003713 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003714 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3715 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003716 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003717 Py_RETURN_NONE;
3718
3719error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003720 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3721 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003722 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003723 Py_XDECREF(keyfile_bytes);
3724 Py_XDECREF(certfile_bytes);
3725 return NULL;
3726}
3727
Christian Heimesefff7062013-11-21 03:35:02 +01003728/* internal helper function, returns -1 on error
3729 */
3730static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03003731_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01003732 int filetype)
3733{
3734 BIO *biobuf = NULL;
3735 X509_STORE *store;
3736 int retval = 0, err, loaded = 0;
3737
3738 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3739
3740 if (len <= 0) {
3741 PyErr_SetString(PyExc_ValueError,
3742 "Empty certificate data");
3743 return -1;
3744 } else if (len > INT_MAX) {
3745 PyErr_SetString(PyExc_OverflowError,
3746 "Certificate data is too long.");
3747 return -1;
3748 }
3749
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003750 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003751 if (biobuf == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003752 _setSSLError(get_state_ctx(self), "Can't allocate buffer", 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003753 return -1;
3754 }
3755
3756 store = SSL_CTX_get_cert_store(self->ctx);
3757 assert(store != NULL);
3758
3759 while (1) {
3760 X509 *cert = NULL;
3761 int r;
3762
3763 if (filetype == SSL_FILETYPE_ASN1) {
3764 cert = d2i_X509_bio(biobuf, NULL);
3765 } else {
3766 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003767 SSL_CTX_get_default_passwd_cb(self->ctx),
3768 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3769 );
Christian Heimesefff7062013-11-21 03:35:02 +01003770 }
3771 if (cert == NULL) {
3772 break;
3773 }
3774 r = X509_STORE_add_cert(store, cert);
3775 X509_free(cert);
3776 if (!r) {
3777 err = ERR_peek_last_error();
3778 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3779 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3780 /* cert already in hash table, not an error */
3781 ERR_clear_error();
3782 } else {
3783 break;
3784 }
3785 }
3786 loaded++;
3787 }
3788
3789 err = ERR_peek_last_error();
3790 if ((filetype == SSL_FILETYPE_ASN1) &&
3791 (loaded > 0) &&
3792 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3793 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3794 /* EOF ASN1 file, not an error */
3795 ERR_clear_error();
3796 retval = 0;
3797 } else if ((filetype == SSL_FILETYPE_PEM) &&
3798 (loaded > 0) &&
3799 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3800 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3801 /* EOF PEM file, not an error */
3802 ERR_clear_error();
3803 retval = 0;
3804 } else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003805 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003806 retval = -1;
3807 }
3808
3809 BIO_free(biobuf);
3810 return retval;
3811}
3812
3813
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003814/*[clinic input]
3815_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003816 cafile: object = None
3817 capath: object = None
3818 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003819
3820[clinic start generated code]*/
3821
Antoine Pitrou152efa22010-05-16 18:19:27 +00003822static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003823_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3824 PyObject *cafile,
3825 PyObject *capath,
3826 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003827/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003828{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003829 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3830 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003831 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003832
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003833 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003834 if (cafile == Py_None)
3835 cafile = NULL;
3836 if (capath == Py_None)
3837 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003838 if (cadata == Py_None)
3839 cadata = NULL;
3840
3841 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003842 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003843 "cafile, capath and cadata cannot be all omitted");
3844 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003845 }
3846 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003847 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3848 PyErr_SetString(PyExc_TypeError,
3849 "cafile should be a valid filesystem path");
3850 }
Christian Heimesefff7062013-11-21 03:35:02 +01003851 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003852 }
3853 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003854 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3855 PyErr_SetString(PyExc_TypeError,
3856 "capath should be a valid filesystem path");
3857 }
Christian Heimesefff7062013-11-21 03:35:02 +01003858 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003859 }
Christian Heimesefff7062013-11-21 03:35:02 +01003860
3861 /* validata cadata type and load cadata */
3862 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003863 if (PyUnicode_Check(cadata)) {
3864 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
3865 if (cadata_ascii == NULL) {
3866 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
3867 goto invalid_cadata;
3868 }
3869 goto error;
3870 }
3871 r = _add_ca_certs(self,
3872 PyBytes_AS_STRING(cadata_ascii),
3873 PyBytes_GET_SIZE(cadata_ascii),
3874 SSL_FILETYPE_PEM);
3875 Py_DECREF(cadata_ascii);
3876 if (r == -1) {
3877 goto error;
3878 }
3879 }
3880 else if (PyObject_CheckBuffer(cadata)) {
3881 Py_buffer buf;
3882 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
3883 goto error;
3884 }
Christian Heimesefff7062013-11-21 03:35:02 +01003885 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3886 PyBuffer_Release(&buf);
3887 PyErr_SetString(PyExc_TypeError,
3888 "cadata should be a contiguous buffer with "
3889 "a single dimension");
3890 goto error;
3891 }
3892 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3893 PyBuffer_Release(&buf);
3894 if (r == -1) {
3895 goto error;
3896 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003897 }
3898 else {
3899 invalid_cadata:
3900 PyErr_SetString(PyExc_TypeError,
3901 "cadata should be an ASCII string or a "
3902 "bytes-like object");
3903 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01003904 }
3905 }
3906
3907 /* load cafile or capath */
3908 if (cafile || capath) {
3909 if (cafile)
3910 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3911 if (capath)
3912 capath_buf = PyBytes_AS_STRING(capath_bytes);
3913 PySSL_BEGIN_ALLOW_THREADS
3914 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3915 PySSL_END_ALLOW_THREADS
3916 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01003917 if (errno != 0) {
3918 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003919 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003920 }
3921 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003922 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Christian Heimesefff7062013-11-21 03:35:02 +01003923 }
3924 goto error;
3925 }
3926 }
3927 goto end;
3928
3929 error:
3930 ok = 0;
3931 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003932 Py_XDECREF(cafile_bytes);
3933 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003934 if (ok) {
3935 Py_RETURN_NONE;
3936 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003937 return NULL;
3938 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003939}
3940
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003941/*[clinic input]
3942_ssl._SSLContext.load_dh_params
3943 path as filepath: object
3944 /
3945
3946[clinic start generated code]*/
3947
Antoine Pitrou152efa22010-05-16 18:19:27 +00003948static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003949_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3950/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003951{
3952 FILE *f;
3953 DH *dh;
3954
Victor Stinnerdaf45552013-08-28 00:53:59 +02003955 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003956 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003957 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003958
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003959 errno = 0;
3960 PySSL_BEGIN_ALLOW_THREADS
3961 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003962 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003963 PySSL_END_ALLOW_THREADS
3964 if (dh == NULL) {
3965 if (errno != 0) {
3966 ERR_clear_error();
3967 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3968 }
3969 else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02003970 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003971 }
3972 return NULL;
3973 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06003974 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
3975 DH_free(dh);
Christian Heimes7f1305e2021-04-17 20:06:38 +02003976 return _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Zackery Spytzaebc0492020-07-07 22:21:58 -06003977 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003978 DH_free(dh);
3979 Py_RETURN_NONE;
3980}
3981
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003982/*[clinic input]
3983_ssl._SSLContext._wrap_socket
Christian Heimes7f1305e2021-04-17 20:06:38 +02003984 sock: object(subclass_of="get_state_ctx(self)->Sock_Type")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003985 server_side: int
3986 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01003987 *
3988 owner: object = None
3989 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003990
3991[clinic start generated code]*/
3992
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003993static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003994_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01003995 int server_side, PyObject *hostname_obj,
3996 PyObject *owner, PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02003997/*[clinic end generated code: output=f103f238633940b4 input=f5916eadbc6eae81]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003998{
Antoine Pitroud5323212010-10-22 18:19:07 +00003999 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004000 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004001
Antoine Pitroud5323212010-10-22 18:19:07 +00004002 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004003 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004004 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004005 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004006 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004007 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004008
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004009 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4010 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004011 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004012 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004013 if (hostname != NULL)
4014 PyMem_Free(hostname);
4015 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004016}
4017
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004018/*[clinic input]
4019_ssl._SSLContext._wrap_bio
Christian Heimes7f1305e2021-04-17 20:06:38 +02004020 incoming: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4021 outgoing: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004022 server_side: int
4023 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004024 *
4025 owner: object = None
4026 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004027
4028[clinic start generated code]*/
4029
Antoine Pitroub0182c82010-10-12 20:09:02 +00004030static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004031_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4032 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004033 PyObject *hostname_obj, PyObject *owner,
4034 PyObject *session)
Christian Heimes7f1305e2021-04-17 20:06:38 +02004035/*[clinic end generated code: output=5c5d6d9b41f99332 input=331edeec9c738382]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004036{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004037 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004038 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004039
4040 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004041 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004042 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004043 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004044 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004045 }
4046
4047 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004048 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004049 incoming, outgoing);
4050
4051 PyMem_Free(hostname);
4052 return res;
4053}
4054
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004055/*[clinic input]
4056_ssl._SSLContext.session_stats
4057[clinic start generated code]*/
4058
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004059static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004060_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4061/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004062{
4063 int r;
4064 PyObject *value, *stats = PyDict_New();
4065 if (!stats)
4066 return NULL;
4067
4068#define ADD_STATS(SSL_NAME, KEY_NAME) \
4069 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4070 if (value == NULL) \
4071 goto error; \
4072 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4073 Py_DECREF(value); \
4074 if (r < 0) \
4075 goto error;
4076
4077 ADD_STATS(number, "number");
4078 ADD_STATS(connect, "connect");
4079 ADD_STATS(connect_good, "connect_good");
4080 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4081 ADD_STATS(accept, "accept");
4082 ADD_STATS(accept_good, "accept_good");
4083 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4084 ADD_STATS(accept, "accept");
4085 ADD_STATS(hits, "hits");
4086 ADD_STATS(misses, "misses");
4087 ADD_STATS(timeouts, "timeouts");
4088 ADD_STATS(cache_full, "cache_full");
4089
4090#undef ADD_STATS
4091
4092 return stats;
4093
4094error:
4095 Py_DECREF(stats);
4096 return NULL;
4097}
4098
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004099/*[clinic input]
4100_ssl._SSLContext.set_default_verify_paths
4101[clinic start generated code]*/
4102
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004103static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004104_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4105/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004106{
4107 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004108 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004109 return NULL;
4110 }
4111 Py_RETURN_NONE;
4112}
4113
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004114/*[clinic input]
4115_ssl._SSLContext.set_ecdh_curve
4116 name: object
4117 /
4118
4119[clinic start generated code]*/
4120
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004121static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004122_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4123/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004124{
4125 PyObject *name_bytes;
4126 int nid;
4127 EC_KEY *key;
4128
4129 if (!PyUnicode_FSConverter(name, &name_bytes))
4130 return NULL;
4131 assert(PyBytes_Check(name_bytes));
4132 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4133 Py_DECREF(name_bytes);
4134 if (nid == 0) {
4135 PyErr_Format(PyExc_ValueError,
4136 "unknown elliptic curve name %R", name);
4137 return NULL;
4138 }
4139 key = EC_KEY_new_by_curve_name(nid);
4140 if (key == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004141 _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004142 return NULL;
4143 }
4144 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4145 EC_KEY_free(key);
4146 Py_RETURN_NONE;
4147}
4148
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004149static int
4150_servername_callback(SSL *s, int *al, void *args)
4151{
4152 int ret;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004153 PySSLContext *sslctx = (PySSLContext *) args;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004154 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004155 PyObject *result;
4156 /* The high-level ssl.SSLSocket object */
4157 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004158 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004159 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004160
Christian Heimes7f1305e2021-04-17 20:06:38 +02004161 if (sslctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004162 /* remove race condition in this the call back while if removing the
4163 * callback is in progress */
4164 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004165 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004166 }
4167
4168 ssl = SSL_get_app_data(s);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004169 assert(Py_IS_TYPE(ssl, get_state_ctx(sslctx)->PySSLSocket_Type));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004170
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004171 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004172 * SSL connection and that has a .context attribute that can be changed to
4173 * identify the requested hostname. Since the official API is the Python
4174 * level API we want to pass the callback a Python level object rather than
4175 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4176 * SSLObject) that will be passed. Otherwise if there's a socket then that
4177 * will be passed. If both do not exist only then the C-level object is
4178 * passed. */
4179 if (ssl->owner)
4180 ssl_socket = PyWeakref_GetObject(ssl->owner);
4181 else if (ssl->Socket)
4182 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4183 else
4184 ssl_socket = (PyObject *) ssl;
4185
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004186 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004187 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004188 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004189
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004190 if (servername == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004191 result = PyObject_CallFunctionObjArgs(sslctx->set_sni_cb, ssl_socket,
4192 Py_None, sslctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004193 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004194 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004195 PyObject *servername_bytes;
4196 PyObject *servername_str;
4197
4198 servername_bytes = PyBytes_FromString(servername);
4199 if (servername_bytes == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004200 PyErr_WriteUnraisable((PyObject *) sslctx);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004201 goto error;
4202 }
Christian Heimes11a14932018-02-24 02:35:08 +01004203 /* server_hostname was encoded to an A-label by our caller; put it
4204 * back into a str object, but still as an A-label (bpo-28414)
4205 */
4206 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004207 if (servername_str == NULL) {
4208 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004209 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004210 goto error;
4211 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004212 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004213 result = PyObject_CallFunctionObjArgs(
Christian Heimes7f1305e2021-04-17 20:06:38 +02004214 sslctx->set_sni_cb, ssl_socket, servername_str,
4215 sslctx, NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004216 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004217 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004218 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004219
4220 if (result == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004221 PyErr_WriteUnraisable(sslctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004222 *al = SSL_AD_HANDSHAKE_FAILURE;
4223 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4224 }
4225 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004226 /* Result may be None, a SSLContext or an integer
4227 * None and SSLContext are OK, integer or other values are an error.
4228 */
4229 if (result == Py_None) {
4230 ret = SSL_TLSEXT_ERR_OK;
4231 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004232 *al = (int) PyLong_AsLong(result);
4233 if (PyErr_Occurred()) {
4234 PyErr_WriteUnraisable(result);
4235 *al = SSL_AD_INTERNAL_ERROR;
4236 }
4237 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4238 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004239 Py_DECREF(result);
4240 }
4241
4242 PyGILState_Release(gstate);
4243 return ret;
4244
4245error:
4246 Py_DECREF(ssl_socket);
4247 *al = SSL_AD_INTERNAL_ERROR;
4248 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4249 PyGILState_Release(gstate);
4250 return ret;
4251}
4252
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004253static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004254get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004255{
Christian Heimes11a14932018-02-24 02:35:08 +01004256 PyObject *cb = self->set_sni_cb;
4257 if (cb == NULL) {
4258 Py_RETURN_NONE;
4259 }
4260 Py_INCREF(cb);
4261 return cb;
4262}
4263
4264static int
4265set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4266{
4267 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4268 PyErr_SetString(PyExc_ValueError,
4269 "sni_callback cannot be set on TLS_CLIENT context");
4270 return -1;
4271 }
Christian Heimes11a14932018-02-24 02:35:08 +01004272 Py_CLEAR(self->set_sni_cb);
4273 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004274 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4275 }
4276 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004277 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004278 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4279 PyErr_SetString(PyExc_TypeError,
4280 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004281 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004282 }
Christian Heimes11a14932018-02-24 02:35:08 +01004283 Py_INCREF(arg);
4284 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004285 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4286 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4287 }
Christian Heimes11a14932018-02-24 02:35:08 +01004288 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004289}
4290
Christian Heimes11a14932018-02-24 02:35:08 +01004291PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4292"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4293\n\
4294If the argument is None then the callback is disabled. The method is called\n\
4295with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4296See RFC 6066 for details of the SNI extension.");
4297
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004298/*[clinic input]
4299_ssl._SSLContext.cert_store_stats
4300
4301Returns quantities of loaded X.509 certificates.
4302
4303X.509 certificates with a CA extension and certificate revocation lists
4304inside the context's cert store.
4305
4306NOTE: Certificates in a capath directory aren't loaded unless they have
4307been used at least once.
4308[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004309
4310static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004311_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4312/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004313{
4314 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004315 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004316 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004317 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004318
4319 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004320 objs = X509_STORE_get0_objects(store);
4321 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4322 obj = sk_X509_OBJECT_value(objs, i);
4323 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004324 case X509_LU_X509:
4325 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004326 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004327 ca++;
4328 }
4329 break;
4330 case X509_LU_CRL:
4331 crl++;
4332 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004333 default:
4334 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4335 * As far as I can tell they are internal states and never
4336 * stored in a cert store */
4337 break;
4338 }
4339 }
4340 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4341 "x509_ca", ca);
4342}
4343
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004344/*[clinic input]
4345_ssl._SSLContext.get_ca_certs
4346 binary_form: bool = False
4347
4348Returns a list of dicts with information of loaded CA certs.
4349
4350If the optional argument is True, returns a DER-encoded copy of the CA
4351certificate.
4352
4353NOTE: Certificates in a capath directory aren't loaded unless they have
4354been used at least once.
4355[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004356
4357static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004358_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4359/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004360{
4361 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004362 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004363 PyObject *ci = NULL, *rlist = NULL;
4364 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004365
4366 if ((rlist = PyList_New(0)) == NULL) {
4367 return NULL;
4368 }
4369
4370 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004371 objs = X509_STORE_get0_objects(store);
4372 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004373 X509_OBJECT *obj;
4374 X509 *cert;
4375
Christian Heimes598894f2016-09-05 23:19:05 +02004376 obj = sk_X509_OBJECT_value(objs, i);
4377 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004378 /* not a x509 cert */
4379 continue;
4380 }
4381 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004382 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004383 if (!X509_check_ca(cert)) {
4384 continue;
4385 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004386 if (binary_form) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004387 ci = _certificate_to_der(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004388 } else {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004389 ci = _decode_certificate(get_state_ctx(self), cert);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004390 }
4391 if (ci == NULL) {
4392 goto error;
4393 }
4394 if (PyList_Append(rlist, ci) == -1) {
4395 goto error;
4396 }
4397 Py_CLEAR(ci);
4398 }
4399 return rlist;
4400
4401 error:
4402 Py_XDECREF(ci);
4403 Py_XDECREF(rlist);
4404 return NULL;
4405}
4406
4407
Antoine Pitrou152efa22010-05-16 18:19:27 +00004408static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004409 {"check_hostname", (getter) get_check_hostname,
4410 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004411 {"_host_flags", (getter) get_host_flags,
4412 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004413 {"minimum_version", (getter) get_minimum_version,
4414 (setter) set_minimum_version, NULL},
4415 {"maximum_version", (getter) get_maximum_version,
4416 (setter) set_maximum_version, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004417 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4418 (setter) _PySSLContext_set_keylog_filename, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004419 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4420 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004421 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004422 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes39258d32021-04-17 11:36:35 +02004423#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02004424 {"num_tickets", (getter) get_num_tickets,
4425 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4426#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004427 {"options", (getter) get_options,
4428 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004429 {"post_handshake_auth", (getter) get_post_handshake_auth,
4430#ifdef TLS1_3_VERSION
4431 (setter) set_post_handshake_auth,
4432#else
4433 NULL,
4434#endif
4435 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004436 {"protocol", (getter) get_protocol,
4437 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004438 {"verify_flags", (getter) get_verify_flags,
4439 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004440 {"verify_mode", (getter) get_verify_mode,
4441 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004442 {"security_level", (getter) get_security_level,
4443 NULL, PySSLContext_security_level_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004444 {NULL}, /* sentinel */
4445};
4446
4447static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004448 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4449 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4450 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4451 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004452 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4453 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4454 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4455 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4456 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4457 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004458 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4459 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004460 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004461 {NULL, NULL} /* sentinel */
4462};
4463
Christian Heimes5c36da72020-11-20 09:40:12 +01004464static PyType_Slot PySSLContext_slots[] = {
4465 {Py_tp_methods, context_methods},
4466 {Py_tp_getset, context_getsetlist},
4467 {Py_tp_new, _ssl__SSLContext},
4468 {Py_tp_dealloc, context_dealloc},
4469 {Py_tp_traverse, context_traverse},
4470 {Py_tp_clear, context_clear},
4471 {0, 0},
4472};
4473
4474static PyType_Spec PySSLContext_spec = {
4475 "_ssl._SSLContext",
4476 sizeof(PySSLContext),
4477 0,
4478 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
4479 PySSLContext_slots,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004480};
4481
4482
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004483/*
4484 * MemoryBIO objects
4485 */
4486
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004487/*[clinic input]
4488@classmethod
4489_ssl.MemoryBIO.__new__
4490
4491[clinic start generated code]*/
4492
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004493static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004494_ssl_MemoryBIO_impl(PyTypeObject *type)
4495/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004496{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004497 BIO *bio;
4498 PySSLMemoryBIO *self;
4499
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004500 bio = BIO_new(BIO_s_mem());
4501 if (bio == NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004502 PyErr_SetString(PyExc_MemoryError, "failed to allocate BIO");
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004503 return NULL;
4504 }
4505 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4506 * just that no data is currently available. The SSL routines should retry
4507 * the read, which we can achieve by calling BIO_set_retry_read(). */
4508 BIO_set_retry_read(bio);
4509 BIO_set_mem_eof_return(bio, -1);
4510
4511 assert(type != NULL && type->tp_alloc != NULL);
4512 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4513 if (self == NULL) {
4514 BIO_free(bio);
4515 return NULL;
4516 }
4517 self->bio = bio;
4518 self->eof_written = 0;
4519
4520 return (PyObject *) self;
4521}
4522
4523static void
4524memory_bio_dealloc(PySSLMemoryBIO *self)
4525{
Christian Heimes5c36da72020-11-20 09:40:12 +01004526 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004527 BIO_free(self->bio);
4528 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004529 Py_DECREF(tp);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004530}
4531
4532static PyObject *
4533memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4534{
Segev Finer5cff6372017-07-27 01:19:17 +03004535 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004536}
4537
4538PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4539"The number of bytes pending in the memory BIO.");
4540
4541static PyObject *
4542memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4543{
4544 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4545 && self->eof_written);
4546}
4547
4548PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4549"Whether the memory BIO is at EOF.");
4550
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004551/*[clinic input]
4552_ssl.MemoryBIO.read
4553 size as len: int = -1
4554 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004555
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004556Read up to size bytes from the memory BIO.
4557
4558If size is not specified, read the entire buffer.
4559If the return value is an empty bytes instance, this means either
4560EOF or that no data is available. Use the "eof" property to
4561distinguish between the two.
4562[clinic start generated code]*/
4563
4564static PyObject *
4565_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4566/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4567{
4568 int avail, nbytes;
4569 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004570
Segev Finer5cff6372017-07-27 01:19:17 +03004571 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004572 if ((len < 0) || (len > avail))
4573 len = avail;
4574
4575 result = PyBytes_FromStringAndSize(NULL, len);
4576 if ((result == NULL) || (len == 0))
4577 return result;
4578
4579 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004580 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004581 _sslmodulestate *state = get_state_mbio(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004582 Py_DECREF(result);
Christian Heimes7f1305e2021-04-17 20:06:38 +02004583 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004584 return NULL;
4585 }
4586
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004587 /* There should never be any short reads but check anyway. */
4588 if (nbytes < len) {
4589 _PyBytes_Resize(&result, nbytes);
4590 }
4591
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004592 return result;
4593}
4594
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004595/*[clinic input]
4596_ssl.MemoryBIO.write
4597 b: Py_buffer
4598 /
4599
4600Writes the bytes b into the memory BIO.
4601
4602Returns the number of bytes written.
4603[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004604
4605static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004606_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4607/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004608{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004609 int nbytes;
4610
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004611 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004612 PyErr_Format(PyExc_OverflowError,
4613 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004614 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004615 }
4616
4617 if (self->eof_written) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004618 PyObject *module = PyType_GetModule(Py_TYPE(self));
4619 if (module == NULL)
4620 return NULL;
4621 PyErr_SetString(get_ssl_state(module)->PySSLErrorObject,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004622 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004623 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004624 }
4625
Segev Finer5cff6372017-07-27 01:19:17 +03004626 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004627 if (nbytes < 0) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004628 _sslmodulestate *state = get_state_mbio(self);
4629 _setSSLError(state, NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004630 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004631 }
4632
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004633 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004634}
4635
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004636/*[clinic input]
4637_ssl.MemoryBIO.write_eof
4638
4639Write an EOF marker to the memory BIO.
4640
4641When all data has been read, the "eof" property will be True.
4642[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004643
4644static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004645_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4646/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004647{
4648 self->eof_written = 1;
4649 /* After an EOF is written, a zero return from read() should be a real EOF
4650 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4651 BIO_clear_retry_flags(self->bio);
4652 BIO_set_mem_eof_return(self->bio, 0);
4653
4654 Py_RETURN_NONE;
4655}
4656
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004657static PyGetSetDef memory_bio_getsetlist[] = {
4658 {"pending", (getter) memory_bio_get_pending, NULL,
4659 PySSL_memory_bio_pending_doc},
4660 {"eof", (getter) memory_bio_get_eof, NULL,
4661 PySSL_memory_bio_eof_doc},
4662 {NULL}, /* sentinel */
4663};
4664
4665static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004666 _SSL_MEMORYBIO_READ_METHODDEF
4667 _SSL_MEMORYBIO_WRITE_METHODDEF
4668 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004669 {NULL, NULL} /* sentinel */
4670};
4671
Christian Heimes5c36da72020-11-20 09:40:12 +01004672static PyType_Slot PySSLMemoryBIO_slots[] = {
4673 {Py_tp_methods, memory_bio_methods},
4674 {Py_tp_getset, memory_bio_getsetlist},
4675 {Py_tp_new, _ssl_MemoryBIO},
4676 {Py_tp_dealloc, memory_bio_dealloc},
4677 {0, 0},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004678};
4679
Christian Heimes5c36da72020-11-20 09:40:12 +01004680static PyType_Spec PySSLMemoryBIO_spec = {
4681 "_ssl.MemoryBIO",
4682 sizeof(PySSLMemoryBIO),
4683 0,
4684 Py_TPFLAGS_DEFAULT,
4685 PySSLMemoryBIO_slots,
4686};
Antoine Pitrou152efa22010-05-16 18:19:27 +00004687
Christian Heimes99a65702016-09-10 23:44:53 +02004688/*
4689 * SSL Session object
4690 */
4691
4692static void
4693PySSLSession_dealloc(PySSLSession *self)
4694{
Christian Heimes5c36da72020-11-20 09:40:12 +01004695 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09004696 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004697 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004698 Py_XDECREF(self->ctx);
4699 if (self->session != NULL) {
4700 SSL_SESSION_free(self->session);
4701 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004702 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004703 Py_DECREF(tp);
Christian Heimes99a65702016-09-10 23:44:53 +02004704}
4705
4706static PyObject *
4707PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4708{
4709 int result;
Christian Heimes7f1305e2021-04-17 20:06:38 +02004710 PyTypeObject *sesstype = ((PySSLSession*)left)->ctx->state->PySSLSession_Type;
Christian Heimes99a65702016-09-10 23:44:53 +02004711
4712 if (left == NULL || right == NULL) {
4713 PyErr_BadInternalCall();
4714 return NULL;
4715 }
4716
Christian Heimes7f1305e2021-04-17 20:06:38 +02004717 if (!Py_IS_TYPE(left, sesstype) || !Py_IS_TYPE(right, sesstype)) {
Christian Heimes99a65702016-09-10 23:44:53 +02004718 Py_RETURN_NOTIMPLEMENTED;
4719 }
4720
4721 if (left == right) {
4722 result = 0;
4723 } else {
4724 const unsigned char *left_id, *right_id;
4725 unsigned int left_len, right_len;
4726 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4727 &left_len);
4728 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4729 &right_len);
4730 if (left_len == right_len) {
4731 result = memcmp(left_id, right_id, left_len);
4732 } else {
4733 result = 1;
4734 }
4735 }
4736
4737 switch (op) {
4738 case Py_EQ:
4739 if (result == 0) {
4740 Py_RETURN_TRUE;
4741 } else {
4742 Py_RETURN_FALSE;
4743 }
4744 break;
4745 case Py_NE:
4746 if (result != 0) {
4747 Py_RETURN_TRUE;
4748 } else {
4749 Py_RETURN_FALSE;
4750 }
4751 break;
4752 case Py_LT:
4753 case Py_LE:
4754 case Py_GT:
4755 case Py_GE:
4756 Py_RETURN_NOTIMPLEMENTED;
4757 break;
4758 default:
4759 PyErr_BadArgument();
4760 return NULL;
4761 }
4762}
4763
4764static int
4765PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4766{
4767 Py_VISIT(self->ctx);
4768 return 0;
4769}
4770
4771static int
4772PySSLSession_clear(PySSLSession *self)
4773{
4774 Py_CLEAR(self->ctx);
4775 return 0;
4776}
4777
4778
4779static PyObject *
4780PySSLSession_get_time(PySSLSession *self, void *closure) {
4781 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4782}
4783
4784PyDoc_STRVAR(PySSLSession_get_time_doc,
4785"Session creation time (seconds since epoch).");
4786
4787
4788static PyObject *
4789PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4790 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4791}
4792
4793PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4794"Session timeout (delta in seconds).");
4795
4796
4797static PyObject *
4798PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4799 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4800 return PyLong_FromUnsignedLong(hint);
4801}
4802
4803PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4804"Ticket life time hint.");
4805
4806
4807static PyObject *
4808PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4809 const unsigned char *id;
4810 unsigned int len;
4811 id = SSL_SESSION_get_id(self->session, &len);
4812 return PyBytes_FromStringAndSize((const char *)id, len);
4813}
4814
4815PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4816"Session id");
4817
4818
4819static PyObject *
4820PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4821 if (SSL_SESSION_has_ticket(self->session)) {
4822 Py_RETURN_TRUE;
4823 } else {
4824 Py_RETURN_FALSE;
4825 }
4826}
4827
4828PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4829"Does the session contain a ticket?");
4830
4831
4832static PyGetSetDef PySSLSession_getsetlist[] = {
4833 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4834 PySSLSession_get_has_ticket_doc},
4835 {"id", (getter) PySSLSession_get_session_id, NULL,
4836 PySSLSession_get_session_id_doc},
4837 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4838 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4839 {"time", (getter) PySSLSession_get_time, NULL,
4840 PySSLSession_get_time_doc},
4841 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4842 PySSLSession_get_timeout_doc},
4843 {NULL}, /* sentinel */
4844};
4845
Christian Heimes5c36da72020-11-20 09:40:12 +01004846static PyType_Slot PySSLSession_slots[] = {
4847 {Py_tp_getset,PySSLSession_getsetlist},
4848 {Py_tp_richcompare, PySSLSession_richcompare},
4849 {Py_tp_dealloc, PySSLSession_dealloc},
4850 {Py_tp_traverse, PySSLSession_traverse},
4851 {Py_tp_clear, PySSLSession_clear},
4852 {0, 0},
4853};
4854
4855static PyType_Spec PySSLSession_spec = {
4856 "_ssl.SSLSession",
4857 sizeof(PySSLSession),
4858 0,
4859 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
4860 PySSLSession_slots,
Christian Heimes99a65702016-09-10 23:44:53 +02004861};
4862
4863
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004864/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004865/*[clinic input]
4866_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004867 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004868 entropy: double
4869 /
4870
4871Mix string into the OpenSSL PRNG state.
4872
4873entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304874string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004875[clinic start generated code]*/
4876
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004877static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004878_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004879/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004880{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004881 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004882 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004883
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004884 buf = (const char *)view->buf;
4885 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004886 do {
4887 written = Py_MIN(len, INT_MAX);
4888 RAND_add(buf, (int)written, entropy);
4889 buf += written;
4890 len -= written;
4891 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004892 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004893}
4894
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004895static PyObject *
Christian Heimes7f1305e2021-04-17 20:06:38 +02004896PySSL_RAND(PyObject *module, int len, int pseudo)
Victor Stinner99c8b162011-05-24 12:05:19 +02004897{
4898 int ok;
4899 PyObject *bytes;
4900 unsigned long err;
4901 const char *errstr;
4902 PyObject *v;
4903
Victor Stinner1e81a392013-12-19 16:47:04 +01004904 if (len < 0) {
4905 PyErr_SetString(PyExc_ValueError, "num must be positive");
4906 return NULL;
4907 }
4908
Victor Stinner99c8b162011-05-24 12:05:19 +02004909 bytes = PyBytes_FromStringAndSize(NULL, len);
4910 if (bytes == NULL)
4911 return NULL;
4912 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02004913 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Victor Stinner99c8b162011-05-24 12:05:19 +02004914 if (ok == 0 || ok == 1)
4915 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4916 }
4917 else {
4918 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4919 if (ok == 1)
4920 return bytes;
4921 }
4922 Py_DECREF(bytes);
4923
4924 err = ERR_get_error();
4925 errstr = ERR_reason_error_string(err);
4926 v = Py_BuildValue("(ks)", err, errstr);
4927 if (v != NULL) {
Christian Heimes7f1305e2021-04-17 20:06:38 +02004928 PyErr_SetObject(get_ssl_state(module)->PySSLErrorObject, v);
Victor Stinner99c8b162011-05-24 12:05:19 +02004929 Py_DECREF(v);
4930 }
4931 return NULL;
4932}
4933
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004934/*[clinic input]
4935_ssl.RAND_bytes
4936 n: int
4937 /
4938
4939Generate n cryptographically strong pseudo-random bytes.
4940[clinic start generated code]*/
4941
Victor Stinner99c8b162011-05-24 12:05:19 +02004942static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004943_ssl_RAND_bytes_impl(PyObject *module, int n)
4944/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004945{
Christian Heimes7f1305e2021-04-17 20:06:38 +02004946 return PySSL_RAND(module, n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004947}
4948
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004949/*[clinic input]
4950_ssl.RAND_pseudo_bytes
4951 n: int
4952 /
4953
4954Generate n pseudo-random bytes.
4955
4956Return a pair (bytes, is_cryptographic). is_cryptographic is True
4957if the bytes generated are cryptographically strong.
4958[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004959
4960static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004961_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4962/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004963{
Christian Heimes7f1305e2021-04-17 20:06:38 +02004964 return PySSL_RAND(module, n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004965}
4966
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004967/*[clinic input]
4968_ssl.RAND_status
4969
4970Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4971
4972It is necessary to seed the PRNG with RAND_add() on some platforms before
4973using the ssl() function.
4974[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004975
4976static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004977_ssl_RAND_status_impl(PyObject *module)
4978/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004979{
Christian Heimes217cfd12007-12-02 14:31:20 +00004980 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004981}
4982
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004983/*[clinic input]
4984_ssl.get_default_verify_paths
4985
4986Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4987
4988The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4989[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004990
4991static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004992_ssl_get_default_verify_paths_impl(PyObject *module)
4993/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004994{
4995 PyObject *ofile_env = NULL;
4996 PyObject *ofile = NULL;
4997 PyObject *odir_env = NULL;
4998 PyObject *odir = NULL;
4999
Benjamin Petersond113c962015-07-18 10:59:13 -07005000#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005001 const char *tmp = (info); \
5002 target = NULL; \
5003 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5004 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5005 target = PyBytes_FromString(tmp); } \
5006 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005007 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005008
Benjamin Petersond113c962015-07-18 10:59:13 -07005009 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5010 CONVERT(X509_get_default_cert_file(), ofile);
5011 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5012 CONVERT(X509_get_default_cert_dir(), odir);
5013#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005014
Christian Heimes200bb1b2013-06-14 15:14:29 +02005015 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005016
5017 error:
5018 Py_XDECREF(ofile_env);
5019 Py_XDECREF(ofile);
5020 Py_XDECREF(odir_env);
5021 Py_XDECREF(odir);
5022 return NULL;
5023}
5024
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005025static PyObject*
Christian Heimes7f1305e2021-04-17 20:06:38 +02005026asn1obj2py(_sslmodulestate *state, ASN1_OBJECT *obj)
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005027{
5028 int nid;
5029 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005030
5031 nid = OBJ_obj2nid(obj);
5032 if (nid == NID_undef) {
5033 PyErr_Format(PyExc_ValueError, "Unknown object");
5034 return NULL;
5035 }
5036 sn = OBJ_nid2sn(nid);
5037 ln = OBJ_nid2ln(nid);
Christian Heimes7f1305e2021-04-17 20:06:38 +02005038 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(state, obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005039}
5040
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005041/*[clinic input]
5042_ssl.txt2obj
5043 txt: str
5044 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005045
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005046Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5047
5048By default objects are looked up by OID. With name=True short and
5049long name are also matched.
5050[clinic start generated code]*/
5051
5052static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005053_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5054/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005055{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005056 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005057 ASN1_OBJECT *obj;
5058
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005059 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5060 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005061 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005062 return NULL;
5063 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005064 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005065 ASN1_OBJECT_free(obj);
5066 return result;
5067}
5068
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005069/*[clinic input]
5070_ssl.nid2obj
5071 nid: int
5072 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005073
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005074Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5075[clinic start generated code]*/
5076
5077static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005078_ssl_nid2obj_impl(PyObject *module, int nid)
5079/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005080{
5081 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005082 ASN1_OBJECT *obj;
5083
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005084 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005085 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005086 return NULL;
5087 }
5088 obj = OBJ_nid2obj(nid);
5089 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005090 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005091 return NULL;
5092 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005093 result = asn1obj2py(get_ssl_state(module), obj);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005094 ASN1_OBJECT_free(obj);
5095 return result;
5096}
5097
Christian Heimes46bebee2013-06-09 19:03:31 +02005098#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005099
5100static PyObject*
5101certEncodingType(DWORD encodingType)
5102{
5103 static PyObject *x509_asn = NULL;
5104 static PyObject *pkcs_7_asn = NULL;
5105
5106 if (x509_asn == NULL) {
5107 x509_asn = PyUnicode_InternFromString("x509_asn");
5108 if (x509_asn == NULL)
5109 return NULL;
5110 }
5111 if (pkcs_7_asn == NULL) {
5112 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5113 if (pkcs_7_asn == NULL)
5114 return NULL;
5115 }
5116 switch(encodingType) {
5117 case X509_ASN_ENCODING:
5118 Py_INCREF(x509_asn);
5119 return x509_asn;
5120 case PKCS_7_ASN_ENCODING:
5121 Py_INCREF(pkcs_7_asn);
5122 return pkcs_7_asn;
5123 default:
5124 return PyLong_FromLong(encodingType);
5125 }
5126}
5127
5128static PyObject*
5129parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5130{
5131 CERT_ENHKEY_USAGE *usage;
5132 DWORD size, error, i;
5133 PyObject *retval;
5134
5135 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5136 error = GetLastError();
5137 if (error == CRYPT_E_NOT_FOUND) {
5138 Py_RETURN_TRUE;
5139 }
5140 return PyErr_SetFromWindowsErr(error);
5141 }
5142
5143 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5144 if (usage == NULL) {
5145 return PyErr_NoMemory();
5146 }
5147
5148 /* Now get the actual enhanced usage property */
5149 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5150 PyMem_Free(usage);
5151 error = GetLastError();
5152 if (error == CRYPT_E_NOT_FOUND) {
5153 Py_RETURN_TRUE;
5154 }
5155 return PyErr_SetFromWindowsErr(error);
5156 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005157 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005158 if (retval == NULL) {
5159 goto error;
5160 }
5161 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5162 if (usage->rgpszUsageIdentifier[i]) {
5163 PyObject *oid;
5164 int err;
5165 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5166 if (oid == NULL) {
5167 Py_CLEAR(retval);
5168 goto error;
5169 }
5170 err = PySet_Add(retval, oid);
5171 Py_DECREF(oid);
5172 if (err == -1) {
5173 Py_CLEAR(retval);
5174 goto error;
5175 }
5176 }
5177 }
5178 error:
5179 PyMem_Free(usage);
5180 return retval;
5181}
5182
kctherookied93fbbf2019-03-29 00:59:06 +07005183static HCERTSTORE
5184ssl_collect_certificates(const char *store_name)
5185{
5186/* this function collects the system certificate stores listed in
5187 * system_stores into a collection certificate store for being
5188 * enumerated. The store must be readable to be added to the
5189 * store collection.
5190 */
5191
5192 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5193 static DWORD system_stores[] = {
5194 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5195 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5196 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5197 CERT_SYSTEM_STORE_CURRENT_USER,
5198 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5199 CERT_SYSTEM_STORE_SERVICES,
5200 CERT_SYSTEM_STORE_USERS};
5201 size_t i, storesAdded;
5202 BOOL result;
5203
5204 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5205 (HCRYPTPROV)NULL, 0, NULL);
5206 if (!hCollectionStore) {
5207 return NULL;
5208 }
5209 storesAdded = 0;
5210 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5211 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5212 (HCRYPTPROV)NULL,
5213 CERT_STORE_READONLY_FLAG |
5214 system_stores[i], store_name);
5215 if (hSystemStore) {
5216 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5217 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5218 if (result) {
5219 ++storesAdded;
5220 }
neoneneed701292019-09-09 21:33:43 +09005221 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005222 }
5223 }
5224 if (storesAdded == 0) {
5225 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5226 return NULL;
5227 }
5228
5229 return hCollectionStore;
5230}
5231
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005232/*[clinic input]
5233_ssl.enum_certificates
5234 store_name: str
5235
5236Retrieve certificates from Windows' cert store.
5237
5238store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5239more cert storages, too. The function returns a list of (bytes,
5240encoding_type, trust) tuples. The encoding_type flag can be interpreted
5241with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5242a set of OIDs or the boolean True.
5243[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005244
Christian Heimes46bebee2013-06-09 19:03:31 +02005245static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005246_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5247/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005248{
kctherookied93fbbf2019-03-29 00:59:06 +07005249 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005250 PCCERT_CONTEXT pCertCtx = NULL;
5251 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005252 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005253
Christian Heimes915cd3f2019-09-09 18:06:55 +02005254 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005255 if (result == NULL) {
5256 return NULL;
5257 }
kctherookied93fbbf2019-03-29 00:59:06 +07005258 hCollectionStore = ssl_collect_certificates(store_name);
5259 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005260 Py_DECREF(result);
5261 return PyErr_SetFromWindowsErr(GetLastError());
5262 }
5263
kctherookied93fbbf2019-03-29 00:59:06 +07005264 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005265 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5266 pCertCtx->cbCertEncoded);
5267 if (!cert) {
5268 Py_CLEAR(result);
5269 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005270 }
Christian Heimes44109d72013-11-22 01:51:30 +01005271 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5272 Py_CLEAR(result);
5273 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005274 }
Christian Heimes44109d72013-11-22 01:51:30 +01005275 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5276 if (keyusage == Py_True) {
5277 Py_DECREF(keyusage);
5278 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005279 }
Christian Heimes44109d72013-11-22 01:51:30 +01005280 if (keyusage == NULL) {
5281 Py_CLEAR(result);
5282 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005283 }
Christian Heimes44109d72013-11-22 01:51:30 +01005284 if ((tup = PyTuple_New(3)) == NULL) {
5285 Py_CLEAR(result);
5286 break;
5287 }
5288 PyTuple_SET_ITEM(tup, 0, cert);
5289 cert = NULL;
5290 PyTuple_SET_ITEM(tup, 1, enc);
5291 enc = NULL;
5292 PyTuple_SET_ITEM(tup, 2, keyusage);
5293 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005294 if (PySet_Add(result, tup) == -1) {
5295 Py_CLEAR(result);
5296 Py_CLEAR(tup);
5297 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005298 }
5299 Py_CLEAR(tup);
5300 }
5301 if (pCertCtx) {
5302 /* loop ended with an error, need to clean up context manually */
5303 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005304 }
5305
5306 /* In error cases cert, enc and tup may not be NULL */
5307 Py_XDECREF(cert);
5308 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005309 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005310 Py_XDECREF(tup);
5311
kctherookied93fbbf2019-03-29 00:59:06 +07005312 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5313 associated with the store, in this case our collection store and the
5314 associated system stores. */
5315 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005316 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005317 Py_XDECREF(result);
5318 return PyErr_SetFromWindowsErr(GetLastError());
5319 }
kctherookied93fbbf2019-03-29 00:59:06 +07005320
Christian Heimes915cd3f2019-09-09 18:06:55 +02005321 /* convert set to list */
5322 if (result == NULL) {
5323 return NULL;
5324 } else {
5325 PyObject *lst = PySequence_List(result);
5326 Py_DECREF(result);
5327 return lst;
5328 }
Christian Heimes44109d72013-11-22 01:51:30 +01005329}
5330
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005331/*[clinic input]
5332_ssl.enum_crls
5333 store_name: str
5334
5335Retrieve CRLs from Windows' cert store.
5336
5337store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5338more cert storages, too. The function returns a list of (bytes,
5339encoding_type) tuples. The encoding_type flag can be interpreted with
5340X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5341[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005342
5343static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005344_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5345/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005346{
kctherookied93fbbf2019-03-29 00:59:06 +07005347 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005348 PCCRL_CONTEXT pCrlCtx = NULL;
5349 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5350 PyObject *result = NULL;
5351
Christian Heimes915cd3f2019-09-09 18:06:55 +02005352 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005353 if (result == NULL) {
5354 return NULL;
5355 }
kctherookied93fbbf2019-03-29 00:59:06 +07005356 hCollectionStore = ssl_collect_certificates(store_name);
5357 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005358 Py_DECREF(result);
5359 return PyErr_SetFromWindowsErr(GetLastError());
5360 }
Christian Heimes44109d72013-11-22 01:51:30 +01005361
kctherookied93fbbf2019-03-29 00:59:06 +07005362 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005363 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5364 pCrlCtx->cbCrlEncoded);
5365 if (!crl) {
5366 Py_CLEAR(result);
5367 break;
5368 }
5369 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5370 Py_CLEAR(result);
5371 break;
5372 }
5373 if ((tup = PyTuple_New(2)) == NULL) {
5374 Py_CLEAR(result);
5375 break;
5376 }
5377 PyTuple_SET_ITEM(tup, 0, crl);
5378 crl = NULL;
5379 PyTuple_SET_ITEM(tup, 1, enc);
5380 enc = NULL;
5381
Christian Heimes915cd3f2019-09-09 18:06:55 +02005382 if (PySet_Add(result, tup) == -1) {
5383 Py_CLEAR(result);
5384 Py_CLEAR(tup);
5385 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005386 }
5387 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005388 }
Christian Heimes44109d72013-11-22 01:51:30 +01005389 if (pCrlCtx) {
5390 /* loop ended with an error, need to clean up context manually */
5391 CertFreeCRLContext(pCrlCtx);
5392 }
5393
5394 /* In error cases cert, enc and tup may not be NULL */
5395 Py_XDECREF(crl);
5396 Py_XDECREF(enc);
5397 Py_XDECREF(tup);
5398
kctherookied93fbbf2019-03-29 00:59:06 +07005399 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5400 associated with the store, in this case our collection store and the
5401 associated system stores. */
5402 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005403 /* This error case might shadow another exception.*/
5404 Py_XDECREF(result);
5405 return PyErr_SetFromWindowsErr(GetLastError());
5406 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005407 /* convert set to list */
5408 if (result == NULL) {
5409 return NULL;
5410 } else {
5411 PyObject *lst = PySequence_List(result);
5412 Py_DECREF(result);
5413 return lst;
5414 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005415}
Christian Heimes44109d72013-11-22 01:51:30 +01005416
5417#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005418
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005419/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005420static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005421 _SSL__TEST_DECODE_CERT_METHODDEF
5422 _SSL_RAND_ADD_METHODDEF
5423 _SSL_RAND_BYTES_METHODDEF
5424 _SSL_RAND_PSEUDO_BYTES_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005425 _SSL_RAND_STATUS_METHODDEF
5426 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5427 _SSL_ENUM_CERTIFICATES_METHODDEF
5428 _SSL_ENUM_CRLS_METHODDEF
5429 _SSL_TXT2OBJ_METHODDEF
5430 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005431 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005432};
5433
5434
Christian Heimes7f1305e2021-04-17 20:06:38 +02005435PyDoc_STRVAR(module_doc,
5436"Implementation module for SSL socket operations. See the socket module\n\
5437for documentation.");
Christian Heimes5c36da72020-11-20 09:40:12 +01005438
5439static int
5440sslmodule_init_exceptions(PyObject *module)
5441{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005442 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005443 PyObject *bases = NULL;
5444
Christian Heimes7f1305e2021-04-17 20:06:38 +02005445#define add_exception(exc, name, doc, base) \
5446do { \
5447 (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5448 if ((state) == NULL) goto error; \
5449 if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
Christian Heimes5c36da72020-11-20 09:40:12 +01005450} while(0)
5451
Christian Heimes7f1305e2021-04-17 20:06:38 +02005452 state->PySSLErrorObject = PyType_FromSpecWithBases(
5453 &sslerror_type_spec, PyExc_OSError);
5454 if (state->PySSLErrorObject == NULL) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005455 goto error;
5456 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005457 if (PyModule_AddObjectRef(module, "SSLError", state->PySSLErrorObject) < 0) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005458 goto error;
5459 }
5460
5461 /* ssl.CertificateError used to be a subclass of ValueError */
Christian Heimes7f1305e2021-04-17 20:06:38 +02005462 bases = PyTuple_Pack(2, state->PySSLErrorObject, PyExc_ValueError);
Christian Heimes5c36da72020-11-20 09:40:12 +01005463 if (bases == NULL) {
5464 goto error;
5465 }
5466 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005467 state->PySSLCertVerificationErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005468 "SSLCertVerificationError",
5469 SSLCertVerificationError_doc,
5470 bases
5471 );
5472 Py_CLEAR(bases);
5473
5474 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005475 state->PySSLZeroReturnErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005476 "SSLZeroReturnError",
5477 SSLZeroReturnError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005478 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005479 );
5480
5481 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005482 state->PySSLWantWriteErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005483 "SSLWantWriteError",
5484 SSLWantWriteError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005485 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005486 );
5487
5488 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005489 state->PySSLWantReadErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005490 "SSLWantReadError",
5491 SSLWantReadError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005492 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005493 );
5494
5495 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005496 state->PySSLSyscallErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005497 "SSLSyscallError",
5498 SSLSyscallError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005499 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005500 );
5501
5502 add_exception(
Christian Heimes7f1305e2021-04-17 20:06:38 +02005503 state->PySSLEOFErrorObject,
Christian Heimes5c36da72020-11-20 09:40:12 +01005504 "SSLEOFError",
5505 SSLEOFError_doc,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005506 state->PySSLErrorObject
Christian Heimes5c36da72020-11-20 09:40:12 +01005507 );
5508#undef add_exception
5509
5510 return 0;
5511 error:
5512 Py_XDECREF(bases);
5513 return -1;
5514}
5515
5516static int
5517sslmodule_init_socketapi(PyObject *module)
5518{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005519 _sslmodulestate *state = get_ssl_state(module);
5520 PySocketModule_APIObject *sockmod = PySocketModule_ImportModuleAndAPI();
Christian Heimes5c36da72020-11-20 09:40:12 +01005521
Christian Heimes7f1305e2021-04-17 20:06:38 +02005522 if ((sockmod == NULL) || (sockmod->Sock_Type == NULL)) {
Christian Heimes5c36da72020-11-20 09:40:12 +01005523 return -1;
Christian Heimes5c36da72020-11-20 09:40:12 +01005524 }
Christian Heimes7f1305e2021-04-17 20:06:38 +02005525 state->Sock_Type = sockmod->Sock_Type;
5526 Py_INCREF(state->Sock_Type);
Christian Heimes5c36da72020-11-20 09:40:12 +01005527 return 0;
5528}
Christian Heimesc941e622017-09-05 15:47:11 +02005529
Christian Heimes5c36da72020-11-20 09:40:12 +01005530static int
5531sslmodule_init_constants(PyObject *m)
5532{
Christian Heimes7f1305e2021-04-17 20:06:38 +02005533
Christian Heimes892d66e2018-01-29 14:10:18 +01005534 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5535 PY_SSL_DEFAULT_CIPHER_STRING);
5536
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005537 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5538 PY_SSL_ERROR_ZERO_RETURN);
5539 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5540 PY_SSL_ERROR_WANT_READ);
5541 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5542 PY_SSL_ERROR_WANT_WRITE);
5543 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5544 PY_SSL_ERROR_WANT_X509_LOOKUP);
5545 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5546 PY_SSL_ERROR_SYSCALL);
5547 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5548 PY_SSL_ERROR_SSL);
5549 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5550 PY_SSL_ERROR_WANT_CONNECT);
5551 /* non ssl.h errorcodes */
5552 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5553 PY_SSL_ERROR_EOF);
5554 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5555 PY_SSL_ERROR_INVALID_ERROR_CODE);
5556 /* cert requirements */
5557 PyModule_AddIntConstant(m, "CERT_NONE",
5558 PY_SSL_CERT_NONE);
5559 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5560 PY_SSL_CERT_OPTIONAL);
5561 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5562 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005563 /* CRL verification for verification_flags */
5564 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5565 0);
5566 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5567 X509_V_FLAG_CRL_CHECK);
5568 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5569 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5570 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5571 X509_V_FLAG_X509_STRICT);
Chris Burre0b4aa02021-03-18 09:24:01 +01005572 PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
5573 X509_V_FLAG_ALLOW_PROXY_CERTS);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005574 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5575 X509_V_FLAG_TRUSTED_FIRST);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005576
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005577 /* Alert Descriptions from ssl.h */
5578 /* note RESERVED constants no longer intended for use have been removed */
5579 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5580
5581#define ADD_AD_CONSTANT(s) \
5582 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5583 SSL_AD_##s)
5584
5585 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5586 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5587 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5588 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5589 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5590 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5591 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5592 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5593 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5594 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5595 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5596 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5597 ADD_AD_CONSTANT(UNKNOWN_CA);
5598 ADD_AD_CONSTANT(ACCESS_DENIED);
5599 ADD_AD_CONSTANT(DECODE_ERROR);
5600 ADD_AD_CONSTANT(DECRYPT_ERROR);
5601 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5602 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5603 ADD_AD_CONSTANT(INTERNAL_ERROR);
5604 ADD_AD_CONSTANT(USER_CANCELLED);
5605 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005606 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005607#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5608 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5609#endif
5610#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5611 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5612#endif
5613#ifdef SSL_AD_UNRECOGNIZED_NAME
5614 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5615#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005616#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5617 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5618#endif
5619#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5620 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5621#endif
5622#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5623 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5624#endif
5625
5626#undef ADD_AD_CONSTANT
5627
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005628 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005629#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005630 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5631 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005632#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005633#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005634 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5635 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005636#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005637 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005638 PY_SSL_VERSION_TLS);
5639 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5640 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005641 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5642 PY_SSL_VERSION_TLS_CLIENT);
5643 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5644 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005645 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5646 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005647 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5648 PY_SSL_VERSION_TLS1_1);
5649 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5650 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005651
Antoine Pitroub5218772010-05-21 09:56:06 +00005652 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005653 PyModule_AddIntConstant(m, "OP_ALL",
5654 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005655 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5656 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5657 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005658 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5659 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005660#ifdef SSL_OP_NO_TLSv1_3
5661 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5662#else
5663 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5664#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005665 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5666 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005667 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005668 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005669#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005670 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005671#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005672#ifdef SSL_OP_NO_COMPRESSION
5673 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5674 SSL_OP_NO_COMPRESSION);
5675#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005676#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5677 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5678 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5679#endif
Christian Heimes67c48012018-05-15 16:25:40 -04005680#ifdef SSL_OP_NO_RENEGOTIATION
5681 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5682 SSL_OP_NO_RENEGOTIATION);
5683#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02005684#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
5685 PyModule_AddIntConstant(m, "OP_IGNORE_UNEXPECTED_EOF",
5686 SSL_OP_IGNORE_UNEXPECTED_EOF);
5687#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005688
Christian Heimes61d478c2018-01-27 15:51:38 +01005689#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5690 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5691 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5692#endif
5693#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5694 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5695 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5696#endif
5697#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5698 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5699 X509_CHECK_FLAG_NO_WILDCARDS);
5700#endif
5701#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5702 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5703 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5704#endif
5705#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5706 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5707 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5708#endif
5709#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5710 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5711 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5712#endif
5713
Christian Heimes698dde12018-02-27 11:54:43 +01005714 /* protocol versions */
5715 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5716 PY_PROTO_MINIMUM_SUPPORTED);
5717 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5718 PY_PROTO_MAXIMUM_SUPPORTED);
5719 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5720 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5721 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5722 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5723 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005724
Victor Stinnerb37672d2018-11-22 03:37:50 +01005725#define addbool(m, key, value) \
5726 do { \
5727 PyObject *bool_obj = (value) ? Py_True : Py_False; \
5728 Py_INCREF(bool_obj); \
5729 PyModule_AddObject((m), (key), bool_obj); \
5730 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01005731
Christian Heimes698dde12018-02-27 11:54:43 +01005732 addbool(m, "HAS_SNI", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005733 addbool(m, "HAS_TLS_UNIQUE", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005734 addbool(m, "HAS_ECDH", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005735 addbool(m, "HAS_NPN", 0);
Christian Heimes698dde12018-02-27 11:54:43 +01005736 addbool(m, "HAS_ALPN", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005737
5738#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5739 addbool(m, "HAS_SSLv2", 1);
5740#else
5741 addbool(m, "HAS_SSLv2", 0);
5742#endif
5743
5744#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5745 addbool(m, "HAS_SSLv3", 1);
5746#else
5747 addbool(m, "HAS_SSLv3", 0);
5748#endif
5749
5750#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5751 addbool(m, "HAS_TLSv1", 1);
5752#else
5753 addbool(m, "HAS_TLSv1", 0);
5754#endif
5755
5756#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5757 addbool(m, "HAS_TLSv1_1", 1);
5758#else
5759 addbool(m, "HAS_TLSv1_1", 0);
5760#endif
5761
5762#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5763 addbool(m, "HAS_TLSv1_2", 1);
5764#else
5765 addbool(m, "HAS_TLSv1_2", 0);
5766#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005767
Christian Heimescb5b68a2017-09-07 18:07:00 -07005768#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005769 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005770#else
Christian Heimes698dde12018-02-27 11:54:43 +01005771 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005772#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005773
Christian Heimes5c36da72020-11-20 09:40:12 +01005774 return 0;
5775}
5776
Christian Heimes7f1305e2021-04-17 20:06:38 +02005777static int
5778sslmodule_init_errorcodes(PyObject *module)
5779{
5780 _sslmodulestate *state = get_ssl_state(module);
Christian Heimes5c36da72020-11-20 09:40:12 +01005781
Christian Heimes7f1305e2021-04-17 20:06:38 +02005782 struct py_ssl_error_code *errcode;
5783 struct py_ssl_library_code *libcode;
Christian Heimes5c36da72020-11-20 09:40:12 +01005784
Christian Heimes7f1305e2021-04-17 20:06:38 +02005785 /* Mappings for error codes */
5786 state->err_codes_to_names = PyDict_New();
5787 if (state->err_codes_to_names == NULL)
5788 return -1;
5789 state->err_names_to_codes = PyDict_New();
5790 if (state->err_names_to_codes == NULL)
5791 return -1;
5792 state->lib_codes_to_names = PyDict_New();
5793 if (state->lib_codes_to_names == NULL)
5794 return -1;
5795
5796 errcode = error_codes;
5797 while (errcode->mnemonic != NULL) {
5798 PyObject *mnemo, *key;
5799 mnemo = PyUnicode_FromString(errcode->mnemonic);
5800 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5801 if (mnemo == NULL || key == NULL)
5802 return -1;
5803 if (PyDict_SetItem(state->err_codes_to_names, key, mnemo))
5804 return -1;
5805 if (PyDict_SetItem(state->err_names_to_codes, mnemo, key))
5806 return -1;
5807 Py_DECREF(key);
5808 Py_DECREF(mnemo);
5809 errcode++;
5810 }
5811
5812 libcode = library_codes;
5813 while (libcode->library != NULL) {
5814 PyObject *mnemo, *key;
5815 key = PyLong_FromLong(libcode->code);
5816 mnemo = PyUnicode_FromString(libcode->library);
5817 if (key == NULL || mnemo == NULL)
5818 return -1;
5819 if (PyDict_SetItem(state->lib_codes_to_names, key, mnemo))
5820 return -1;
5821 Py_DECREF(key);
5822 Py_DECREF(mnemo);
5823 libcode++;
5824 }
5825
5826 if (PyModule_AddObjectRef(module, "err_codes_to_names", state->err_codes_to_names))
5827 return -1;
5828 if (PyModule_AddObjectRef(module, "err_names_to_codes", state->err_names_to_codes))
5829 return -1;
5830 if (PyModule_AddObjectRef(module, "lib_codes_to_names", state->lib_codes_to_names))
5831 return -1;
5832
5833 return 0;
5834}
5835
5836static void
5837parse_openssl_version(unsigned long libver,
5838 unsigned int *major, unsigned int *minor,
5839 unsigned int *fix, unsigned int *patch,
5840 unsigned int *status)
5841{
5842 *status = libver & 0xF;
5843 libver >>= 4;
5844 *patch = libver & 0xFF;
5845 libver >>= 8;
5846 *fix = libver & 0xFF;
5847 libver >>= 8;
5848 *minor = libver & 0xFF;
5849 libver >>= 8;
5850 *major = libver & 0xFF;
5851}
5852
5853static int
5854sslmodule_init_versioninfo(PyObject *m)
5855{
5856 PyObject *r;
5857 unsigned long libver;
5858 unsigned int major, minor, fix, patch, status;
5859
5860 /* OpenSSL version */
5861 /* SSLeay() gives us the version of the library linked against,
5862 which could be different from the headers version.
5863 */
5864 libver = OpenSSL_version_num();
5865 r = PyLong_FromUnsignedLong(libver);
5866 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5867 return -1;
5868
5869 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5870 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5871 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5872 return -1;
5873
5874 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
5875 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5876 return -1;
5877
5878 libver = OPENSSL_VERSION_NUMBER;
5879 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5880 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5881 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5882 return -1;
5883
5884 return 0;
5885}
5886
5887static int
5888sslmodule_init_types(PyObject *module)
5889{
5890 _sslmodulestate *state = get_ssl_state(module);
5891
5892 state->PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5893 module, &PySSLContext_spec, NULL
5894 );
5895 if (state->PySSLContext_Type == NULL)
5896 return -1;
5897
5898 state->PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5899 module, &PySSLSocket_spec, NULL
5900 );
5901 if (state->PySSLSocket_Type == NULL)
5902 return -1;
5903
5904 state->PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5905 module, &PySSLMemoryBIO_spec, NULL
5906 );
5907 if (state->PySSLMemoryBIO_Type == NULL)
5908 return -1;
5909
5910 state->PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5911 module, &PySSLSession_spec, NULL
5912 );
5913 if (state->PySSLSession_Type == NULL)
5914 return -1;
5915
5916 if (PyModule_AddType(module, state->PySSLContext_Type))
5917 return -1;
5918 if (PyModule_AddType(module, state->PySSLSocket_Type))
5919 return -1;
5920 if (PyModule_AddType(module, state->PySSLMemoryBIO_Type))
5921 return -1;
5922 if (PyModule_AddType(module, state->PySSLSession_Type))
5923 return -1;
5924
5925 return 0;
5926}
5927
5928static PyModuleDef_Slot sslmodule_slots[] = {
5929 {Py_mod_exec, sslmodule_init_types},
5930 {Py_mod_exec, sslmodule_init_exceptions},
5931 {Py_mod_exec, sslmodule_init_socketapi},
5932 {Py_mod_exec, sslmodule_init_errorcodes},
5933 {Py_mod_exec, sslmodule_init_constants},
5934 {Py_mod_exec, sslmodule_init_versioninfo},
5935 {0, NULL}
5936};
5937
5938static int
5939sslmodule_traverse(PyObject *m, visitproc visit, void *arg)
5940{
5941 _sslmodulestate *state = get_ssl_state(m);
5942
5943 Py_VISIT(state->PySSLContext_Type);
5944 Py_VISIT(state->PySSLSocket_Type);
5945 Py_VISIT(state->PySSLMemoryBIO_Type);
5946 Py_VISIT(state->PySSLSession_Type);
5947 Py_VISIT(state->PySSLErrorObject);
5948 Py_VISIT(state->PySSLCertVerificationErrorObject);
5949 Py_VISIT(state->PySSLZeroReturnErrorObject);
5950 Py_VISIT(state->PySSLWantReadErrorObject);
5951 Py_VISIT(state->PySSLWantWriteErrorObject);
5952 Py_VISIT(state->PySSLSyscallErrorObject);
5953 Py_VISIT(state->PySSLEOFErrorObject);
5954 Py_VISIT(state->err_codes_to_names);
5955 Py_VISIT(state->err_names_to_codes);
5956 Py_VISIT(state->lib_codes_to_names);
5957 Py_VISIT(state->Sock_Type);
5958
5959 return 0;
5960}
5961
5962static int
5963sslmodule_clear(PyObject *m)
5964{
5965 _sslmodulestate *state = get_ssl_state(m);
5966
5967 Py_CLEAR(state->PySSLContext_Type);
5968 Py_CLEAR(state->PySSLSocket_Type);
5969 Py_CLEAR(state->PySSLMemoryBIO_Type);
5970 Py_CLEAR(state->PySSLSession_Type);
5971 Py_CLEAR(state->PySSLErrorObject);
5972 Py_CLEAR(state->PySSLCertVerificationErrorObject);
5973 Py_CLEAR(state->PySSLZeroReturnErrorObject);
5974 Py_CLEAR(state->PySSLWantReadErrorObject);
5975 Py_CLEAR(state->PySSLWantWriteErrorObject);
5976 Py_CLEAR(state->PySSLSyscallErrorObject);
5977 Py_CLEAR(state->PySSLEOFErrorObject);
5978 Py_CLEAR(state->err_codes_to_names);
5979 Py_CLEAR(state->err_names_to_codes);
5980 Py_CLEAR(state->lib_codes_to_names);
5981 Py_CLEAR(state->Sock_Type);
5982
5983 return 0;
5984}
5985
5986static void
5987sslmodule_free(void *m)
5988{
5989 sslmodule_clear((PyObject *)m);
5990}
5991
5992static struct PyModuleDef _sslmodule_def = {
Christian Heimes5c36da72020-11-20 09:40:12 +01005993 PyModuleDef_HEAD_INIT,
Christian Heimes7f1305e2021-04-17 20:06:38 +02005994 .m_name = "_ssl",
5995 .m_doc = module_doc,
5996 .m_size = sizeof(_sslmodulestate),
5997 .m_methods = PySSL_methods,
5998 .m_slots = sslmodule_slots,
5999 .m_traverse = sslmodule_traverse,
6000 .m_clear = sslmodule_clear,
6001 .m_free = sslmodule_free
Christian Heimes5c36da72020-11-20 09:40:12 +01006002};
6003
6004PyMODINIT_FUNC
6005PyInit__ssl(void)
6006{
Christian Heimes7f1305e2021-04-17 20:06:38 +02006007 return PyModuleDef_Init(&_sslmodule_def);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006008}