blob: f441a16625bc76f99d568c512373c817a8151a7b [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
Steve Dower68d663c2017-07-17 11:15:48 +020028/* Redefined below for Windows debug builds after important #includes */
29#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020030
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020031#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
Christian Heimes39258d32021-04-17 11:36:35 +020032 do { (save) = PyEval_SaveThread(); } while(0)
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020033#define PySSL_END_ALLOW_THREADS_S(save) \
Christian Heimes39258d32021-04-17 11:36:35 +020034 do { PyEval_RestoreThread(save); _PySSL_FIX_ERRNO; } while(0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000035#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000036 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020037 PySSL_BEGIN_ALLOW_THREADS_S(_save);
38#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
39#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
40#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000041
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010042/* Include symbols from _socket module */
43#include "socketmodule.h"
44
45static PySocketModule_APIObject PySocketModule;
46
47#if defined(HAVE_POLL_H)
48#include <poll.h>
49#elif defined(HAVE_SYS_POLL_H)
50#include <sys/poll.h>
51#endif
52
53/* Include OpenSSL header files */
54#include "openssl/rsa.h"
55#include "openssl/crypto.h"
56#include "openssl/x509.h"
57#include "openssl/x509v3.h"
58#include "openssl/pem.h"
59#include "openssl/ssl.h"
60#include "openssl/err.h"
61#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020062#include "openssl/bio.h"
Alexandru Ardeleanb3a271f2018-09-17 14:53:31 +030063#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010064
Christian Heimesc087a262020-05-15 20:55:25 +020065#ifndef OPENSSL_THREADS
66# error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
67#endif
68
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010069/* SSL error object */
70static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070071static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010072static PyObject *PySSLZeroReturnErrorObject;
73static PyObject *PySSLWantReadErrorObject;
74static PyObject *PySSLWantWriteErrorObject;
75static PyObject *PySSLSyscallErrorObject;
76static PyObject *PySSLEOFErrorObject;
77
78/* Error mappings */
79static PyObject *err_codes_to_names;
80static PyObject *err_names_to_codes;
81static PyObject *lib_codes_to_names;
82
83struct py_ssl_error_code {
84 const char *mnemonic;
85 int library, reason;
86};
87struct py_ssl_library_code {
88 const char *library;
89 int code;
90};
91
Steve Dower68d663c2017-07-17 11:15:48 +020092#if defined(MS_WINDOWS) && defined(Py_DEBUG)
93/* Debug builds on Windows rely on getting errno directly from OpenSSL.
94 * However, because it uses a different CRT, we need to transfer the
95 * value of errno from OpenSSL into our debug CRT.
96 *
97 * Don't be fooled - this is horribly ugly code. The only reasonable
98 * alternative is to do both debug and release builds of OpenSSL, which
99 * requires much uglier code to transform their automatically generated
100 * makefile. This is the lesser of all the evils.
101 */
102
103static void _PySSLFixErrno(void) {
104 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
105 if (!ucrtbase) {
106 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
107 * have a catastrophic failure, but this function is not the
108 * place to raise it. */
109 return;
110 }
111
112 typedef int *(__stdcall *errno_func)(void);
113 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
114 if (ssl_errno) {
115 errno = *ssl_errno();
116 *ssl_errno() = 0;
117 } else {
118 errno = ENOTRECOVERABLE;
119 }
120}
121
122#undef _PySSL_FIX_ERRNO
123#define _PySSL_FIX_ERRNO _PySSLFixErrno()
124#endif
125
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100126/* Include generated data (error codes) */
Christian Heimes150af752021-04-09 17:02:00 +0200127#if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
128#include "_ssl_data_300.h"
129#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
130#include "_ssl_data_111.h"
131#else
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100132#include "_ssl_data.h"
Christian Heimes150af752021-04-09 17:02:00 +0200133#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100134
Christian Heimes39258d32021-04-17 11:36:35 +0200135/* OpenSSL API 1.1.0+ does not include version methods */
Christian Heimesa871f692020-06-01 08:58:14 +0200136#ifndef OPENSSL_NO_TLS1_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200137extern const SSL_METHOD *TLSv1_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200138#endif
139#ifndef OPENSSL_NO_TLS1_1_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200140extern const SSL_METHOD *TLSv1_1_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200141#endif
142#ifndef OPENSSL_NO_TLS1_2_METHOD
Christian Heimesa4833882021-04-13 08:17:26 +0200143extern const SSL_METHOD *TLSv1_2_method(void);
Christian Heimesa871f692020-06-01 08:58:14 +0200144#endif
145
Victor Stinner524714e2016-07-22 17:43:59 +0200146#ifndef INVALID_SOCKET /* MS defines this */
147#define INVALID_SOCKET (-1)
148#endif
149
Christian Heimes39258d32021-04-17 11:36:35 +0200150/* OpenSSL 1.1 does not have SSL 2.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200151#define OPENSSL_NO_SSL2
Christian Heimes598894f2016-09-05 23:19:05 +0200152
Christian Heimes892d66e2018-01-29 14:10:18 +0100153/* Default cipher suites */
154#ifndef PY_SSL_DEFAULT_CIPHERS
155#define PY_SSL_DEFAULT_CIPHERS 1
156#endif
157
158#if PY_SSL_DEFAULT_CIPHERS == 0
159 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
160 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
161 #endif
162#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200163/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100164 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
165 * !aNULL:!eNULL: really no NULL ciphers
166 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
167 * !aDSS: no authentication with discrete logarithm DSA algorithm
168 * !SRP:!PSK: no secure remote password or pre-shared key authentication
169 */
170 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
171#elif PY_SSL_DEFAULT_CIPHERS == 2
172/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
173 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
174#else
175 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
176#endif
177
Christian Heimes598894f2016-09-05 23:19:05 +0200178
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000179enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000180 /* these mirror ssl.h */
181 PY_SSL_ERROR_NONE,
182 PY_SSL_ERROR_SSL,
183 PY_SSL_ERROR_WANT_READ,
184 PY_SSL_ERROR_WANT_WRITE,
185 PY_SSL_ERROR_WANT_X509_LOOKUP,
186 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
187 PY_SSL_ERROR_ZERO_RETURN,
188 PY_SSL_ERROR_WANT_CONNECT,
189 /* start of non ssl.h errorcodes */
190 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
191 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
192 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000193};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000194
Thomas Woutersed03b412007-08-28 21:37:11 +0000195enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000196 PY_SSL_CLIENT,
197 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000198};
199
200enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000201 PY_SSL_CERT_NONE,
202 PY_SSL_CERT_OPTIONAL,
203 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000204};
205
206enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000207 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200208 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200209 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100210 PY_SSL_VERSION_TLS1,
211 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200212 PY_SSL_VERSION_TLS1_2,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200213 PY_SSL_VERSION_TLS_CLIENT=0x10,
214 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100215};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200216
Christian Heimes698dde12018-02-27 11:54:43 +0100217enum py_proto_version {
218 PY_PROTO_MINIMUM_SUPPORTED = -2,
219 PY_PROTO_SSLv3 = SSL3_VERSION,
220 PY_PROTO_TLSv1 = TLS1_VERSION,
221 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
222 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
223#ifdef TLS1_3_VERSION
224 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
225#else
226 PY_PROTO_TLSv1_3 = 0x304,
227#endif
228 PY_PROTO_MAXIMUM_SUPPORTED = -1,
229
230/* OpenSSL has no dedicated API to set the minimum version to the maximum
231 * available version, and the other way around. We have to figure out the
232 * minimum and maximum available version on our own and hope for the best.
233 */
234#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
235 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
236#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
237 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
238#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
239 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
240#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
241 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
242#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
243 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
244#else
245 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
246#endif
247
248#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
249 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
250#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
251 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
252#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
253 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
254#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
255 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
256#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
257 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
258#else
259 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
260#endif
261};
262
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000263/* SSL socket object */
264
265#define X509_NAME_MAXLEN 256
266
Antoine Pitroub5218772010-05-21 09:56:06 +0000267
Antoine Pitroud6494802011-07-21 01:11:30 +0200268/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
269 * older SSL, but let's be safe */
270#define PySSL_CB_MAXLEN 128
271
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100272
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000273typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000274 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000275 SSL_CTX *ctx;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500276 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300277 unsigned int alpn_protocols_len;
Christian Heimes11a14932018-02-24 02:35:08 +0100278 PyObject *set_sni_cb;
Christian Heimes1aa9a752013-12-02 02:41:19 +0100279 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100280 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
281 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
282 */
283 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100284 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200285#ifdef TLS1_3_VERSION
286 int post_handshake_auth;
287#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200288 PyObject *msg_cb;
Christian Heimesc7f70692019-05-31 11:44:05 +0200289 PyObject *keylog_filename;
290 BIO *keylog_bio;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000291} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000292
Antoine Pitrou152efa22010-05-16 18:19:27 +0000293typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700294 int ssl; /* last seen error from SSL */
295 int c; /* last seen error from libc */
296#ifdef MS_WINDOWS
297 int ws; /* last seen error from winsock */
298#endif
299} _PySSLError;
300
301typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000302 PyObject_HEAD
303 PyObject *Socket; /* weakref to socket on which we're layered */
304 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100305 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200306 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200307 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200308 PyObject *owner; /* Python level "owner" passed to servername callback */
309 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700310 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200311 /* Some SSL callbacks don't have error reporting. Callback wrappers
312 * store exception information on the socket. The handshake, read, write,
313 * and shutdown methods check for chained exceptions.
314 */
315 PyObject *exc_type;
316 PyObject *exc_value;
317 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000318} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000319
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200320typedef struct {
321 PyObject_HEAD
322 BIO *bio;
323 int eof_written;
324} PySSLMemoryBIO;
325
Christian Heimes99a65702016-09-10 23:44:53 +0200326typedef struct {
327 PyObject_HEAD
328 SSL_SESSION *session;
329 PySSLContext *ctx;
330} PySSLSession;
331
Christian Heimes5c36da72020-11-20 09:40:12 +0100332static PyTypeObject *PySSLContext_Type;
333static PyTypeObject *PySSLSocket_Type;
334static PyTypeObject *PySSLMemoryBIO_Type;
335static PyTypeObject *PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000336
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700337static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
338{
339 _PySSLError err = { 0 };
340 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700341#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700342 err.ws = WSAGetLastError();
343 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700344#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700345 err.c = errno;
346 err.ssl = SSL_get_error(ssl, retcode);
347 }
348 return err;
349}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700350
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300351/*[clinic input]
352module _ssl
Christian Heimes5c36da72020-11-20 09:40:12 +0100353class _ssl._SSLContext "PySSLContext *" "PySSLContext_Type"
354class _ssl._SSLSocket "PySSLSocket *" "PySSLSocket_Type"
355class _ssl.MemoryBIO "PySSLMemoryBIO *" "PySSLMemoryBIO_Type"
356class _ssl.SSLSession "PySSLSession *" "PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300357[clinic start generated code]*/
Christian Heimes5c36da72020-11-20 09:40:12 +0100358/*[clinic end generated code: output=da39a3ee5e6b4b0d input=cc4883756da17954]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300359
360#include "clinic/_ssl.c.h"
361
Victor Stinner14690702015-04-06 22:46:13 +0200362static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000363
Christian Heimes141c5e82018-02-24 21:10:57 +0100364static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
365static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Christian Heimes5c36da72020-11-20 09:40:12 +0100366#define PySSLSocket_Check(v) Py_IS_TYPE(v, PySSLSocket_Type)
367#define PySSLMemoryBIO_Check(v) Py_IS_TYPE(v, PySSLMemoryBIO_Type)
368#define PySSLSession_Check(v) Py_IS_TYPE(v, PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000369
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000370typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000371 SOCKET_IS_NONBLOCKING,
372 SOCKET_IS_BLOCKING,
373 SOCKET_HAS_TIMED_OUT,
374 SOCKET_HAS_BEEN_CLOSED,
375 SOCKET_TOO_LARGE_FOR_SELECT,
376 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000377} timeout_state;
378
Thomas Woutersed03b412007-08-28 21:37:11 +0000379/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000380#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200381#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000382
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200383/* Get the socket from a PySSLSocket, if it has one */
384#define GET_SOCKET(obj) ((obj)->Socket ? \
385 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200386
Victor Stinner14690702015-04-06 22:46:13 +0200387/* If sock is NULL, use a timeout of 0 second */
388#define GET_SOCKET_TIMEOUT(sock) \
389 ((sock != NULL) ? (sock)->sock_timeout : 0)
390
Christian Heimesc7f70692019-05-31 11:44:05 +0200391#include "_ssl/debughelpers.c"
392
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200393/*
394 * SSL errors.
395 */
396
397PyDoc_STRVAR(SSLError_doc,
398"An error occurred in the SSL implementation.");
399
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700400PyDoc_STRVAR(SSLCertVerificationError_doc,
401"A certificate could not be verified.");
402
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200403PyDoc_STRVAR(SSLZeroReturnError_doc,
404"SSL/TLS session closed cleanly.");
405
406PyDoc_STRVAR(SSLWantReadError_doc,
407"Non-blocking SSL socket needs to read more data\n"
408"before the requested operation can be completed.");
409
410PyDoc_STRVAR(SSLWantWriteError_doc,
411"Non-blocking SSL socket needs to write more data\n"
412"before the requested operation can be completed.");
413
414PyDoc_STRVAR(SSLSyscallError_doc,
415"System error when attempting SSL operation.");
416
417PyDoc_STRVAR(SSLEOFError_doc,
418"SSL/TLS connection terminated abruptly.");
419
420static PyObject *
421SSLError_str(PyOSErrorObject *self)
422{
423 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
424 Py_INCREF(self->strerror);
425 return self->strerror;
426 }
427 else
428 return PyObject_Str(self->args);
429}
430
431static PyType_Slot sslerror_type_slots[] = {
Inada Naoki926b0cb2019-04-17 08:39:46 +0900432 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200433 {Py_tp_str, SSLError_str},
434 {0, 0},
435};
436
437static PyType_Spec sslerror_type_spec = {
438 "ssl.SSLError",
439 sizeof(PyOSErrorObject),
440 0,
441 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
442 sslerror_type_slots
443};
444
445static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700446fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
447 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200448{
449 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700450 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200451 PyObject *init_value, *msg, *key;
452 _Py_IDENTIFIER(reason);
453 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700454 _Py_IDENTIFIER(verify_message);
455 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200456
457 if (errcode != 0) {
458 int lib, reason;
459
460 lib = ERR_GET_LIB(errcode);
461 reason = ERR_GET_REASON(errcode);
462 key = Py_BuildValue("ii", lib, reason);
463 if (key == NULL)
464 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300465 reason_obj = PyDict_GetItemWithError(err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200466 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300467 if (reason_obj == NULL && PyErr_Occurred()) {
468 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200469 }
470 key = PyLong_FromLong(lib);
471 if (key == NULL)
472 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300473 lib_obj = PyDict_GetItemWithError(lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200474 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300475 if (lib_obj == NULL && PyErr_Occurred()) {
476 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200477 }
478 if (errstr == NULL)
479 errstr = ERR_reason_error_string(errcode);
480 }
481 if (errstr == NULL)
482 errstr = "unknown error";
483
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700484 /* verify code for cert validation error */
485 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
486 const char *verify_str = NULL;
487 long verify_code;
488
489 verify_code = SSL_get_verify_result(sslsock->ssl);
490 verify_code_obj = PyLong_FromLong(verify_code);
491 if (verify_code_obj == NULL) {
492 goto fail;
493 }
494
495 switch (verify_code) {
496 case X509_V_ERR_HOSTNAME_MISMATCH:
497 verify_obj = PyUnicode_FromFormat(
498 "Hostname mismatch, certificate is not valid for '%S'.",
499 sslsock->server_hostname
500 );
501 break;
502 case X509_V_ERR_IP_ADDRESS_MISMATCH:
503 verify_obj = PyUnicode_FromFormat(
504 "IP address mismatch, certificate is not valid for '%S'.",
505 sslsock->server_hostname
506 );
507 break;
508 default:
509 verify_str = X509_verify_cert_error_string(verify_code);
510 if (verify_str != NULL) {
511 verify_obj = PyUnicode_FromString(verify_str);
512 } else {
513 verify_obj = Py_None;
514 Py_INCREF(verify_obj);
515 }
516 break;
517 }
518 if (verify_obj == NULL) {
519 goto fail;
520 }
521 }
522
523 if (verify_obj && reason_obj && lib_obj)
524 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
525 lib_obj, reason_obj, errstr, verify_obj,
526 lineno);
527 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200528 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
529 lib_obj, reason_obj, errstr, lineno);
530 else if (lib_obj)
531 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
532 lib_obj, errstr, lineno);
533 else
534 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200535 if (msg == NULL)
536 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100537
Paul Monsonfb7e7502019-05-15 15:38:55 -0700538 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100539 if (init_value == NULL)
540 goto fail;
541
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200542 err_value = PyObject_CallObject(type, init_value);
543 Py_DECREF(init_value);
544 if (err_value == NULL)
545 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100546
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200547 if (reason_obj == NULL)
548 reason_obj = Py_None;
549 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
550 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700551
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200552 if (lib_obj == NULL)
553 lib_obj = Py_None;
554 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
555 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700556
557 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
558 /* Only set verify code / message for SSLCertVerificationError */
559 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
560 verify_code_obj))
561 goto fail;
562 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
563 goto fail;
564 }
565
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200566 PyErr_SetObject(type, err_value);
567fail:
568 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700569 Py_XDECREF(verify_code_obj);
570 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200571}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000572
Christian Heimesc7f70692019-05-31 11:44:05 +0200573static int
574PySSL_ChainExceptions(PySSLSocket *sslsock) {
575 if (sslsock->exc_type == NULL)
576 return 0;
577
578 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
579 sslsock->exc_type = NULL;
580 sslsock->exc_value = NULL;
581 sslsock->exc_tb = NULL;
582 return -1;
583}
584
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000585static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700586PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000587{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200588 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200589 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700590 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000591 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200592 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000593
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000594 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200595 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000596
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700597 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700598 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000599
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700600 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000601 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200602 errstr = "TLS/SSL connection has been closed (EOF)";
603 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000604 p = PY_SSL_ERROR_ZERO_RETURN;
605 break;
606 case SSL_ERROR_WANT_READ:
607 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200608 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000609 p = PY_SSL_ERROR_WANT_READ;
610 break;
611 case SSL_ERROR_WANT_WRITE:
612 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200613 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000614 errstr = "The operation did not complete (write)";
615 break;
616 case SSL_ERROR_WANT_X509_LOOKUP:
617 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000618 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000619 break;
620 case SSL_ERROR_WANT_CONNECT:
621 p = PY_SSL_ERROR_WANT_CONNECT;
622 errstr = "The operation did not complete (connect)";
623 break;
624 case SSL_ERROR_SYSCALL:
625 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000626 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700627 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000628 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000629 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200630 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000631 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200632 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000633 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000634 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700635#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700636 if (err.ws) {
637 return PyErr_SetFromWindowsErr(err.ws);
638 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700639#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700640 if (err.c) {
641 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700642 return PyErr_SetFromErrno(PyExc_OSError);
643 }
Dima Tisnek495bd032020-08-16 02:01:19 +0900644 else {
645 p = PY_SSL_ERROR_EOF;
646 type = PySSLEOFErrorObject;
647 errstr = "EOF occurred in violation of protocol";
648 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000649 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000650 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200651 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000652 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000653 }
654 } else {
655 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000656 }
657 break;
658 }
659 case SSL_ERROR_SSL:
660 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000661 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700662 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200663 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000664 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700665 }
666 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
667 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
668 type = PySSLCertVerificationErrorObject;
669 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000670 break;
671 }
672 default:
673 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
674 errstr = "Invalid error code";
675 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000676 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700677 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000678 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200679 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000680 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000681}
682
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000683static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200684_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000685
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200686 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000687 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200688 else
689 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700690 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000691 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000692 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000693}
694
Christian Heimes61d478c2018-01-27 15:51:38 +0100695/*
696 * SSL objects
697 */
698
699static int
700_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
701{
702 int retval = -1;
703 ASN1_OCTET_STRING *ip;
704 PyObject *hostname;
705 size_t len;
706
707 assert(server_hostname);
708
709 /* Disable OpenSSL's special mode with leading dot in hostname:
710 * When name starts with a dot (e.g ".example.com"), it will be
711 * matched by a certificate valid for any sub-domain of name.
712 */
713 len = strlen(server_hostname);
714 if (len == 0 || *server_hostname == '.') {
715 PyErr_SetString(
716 PyExc_ValueError,
717 "server_hostname cannot be an empty string or start with a "
718 "leading dot.");
719 return retval;
720 }
721
722 /* inet_pton is not available on all platforms. */
723 ip = a2i_IPADDRESS(server_hostname);
724 if (ip == NULL) {
725 ERR_clear_error();
726 }
727
Christian Heimes11a14932018-02-24 02:35:08 +0100728 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100729 if (hostname == NULL) {
730 goto error;
731 }
732 self->server_hostname = hostname;
733
734 /* Only send SNI extension for non-IP hostnames */
735 if (ip == NULL) {
736 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
737 _setSSLError(NULL, 0, __FILE__, __LINE__);
Zackery Spytzc32f2972020-10-25 12:02:30 -0600738 goto error;
Christian Heimes61d478c2018-01-27 15:51:38 +0100739 }
740 }
741 if (self->ctx->check_hostname) {
742 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
743 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200744 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
745 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100746 _setSSLError(NULL, 0, __FILE__, __LINE__);
747 goto error;
748 }
749 } else {
Christian Heimesa871f692020-06-01 08:58:14 +0200750 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
Christian Heimes61d478c2018-01-27 15:51:38 +0100751 ASN1_STRING_length(ip))) {
752 _setSSLError(NULL, 0, __FILE__, __LINE__);
753 goto error;
754 }
755 }
756 }
757 retval = 0;
758 error:
759 if (ip != NULL) {
760 ASN1_OCTET_STRING_free(ip);
761 }
762 return retval;
763}
764
Antoine Pitrou152efa22010-05-16 18:19:27 +0000765static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100766newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000767 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200768 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100769 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200770 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000771{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000772 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100773 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700774 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000775
Christian Heimes5c36da72020-11-20 09:40:12 +0100776 self = PyObject_New(PySSLSocket, PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000777 if (self == NULL)
778 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000779
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000780 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000781 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100782 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700783 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200784 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200785 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700786 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700787 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200788 self->exc_type = NULL;
789 self->exc_value = NULL;
790 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200791
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000793 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000794
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000795 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000796 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700798 if (self->ssl == NULL) {
799 Py_DECREF(self);
800 _setSSLError(NULL, 0, __FILE__, __LINE__);
801 return NULL;
802 }
Christian Heimesb467d9a2021-04-17 10:07:19 +0200803 /* bpo43522 and OpenSSL < 1.1.1l: copy hostflags manually */
804#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION < 0x101010cf
805 X509_VERIFY_PARAM *ssl_params = SSL_get0_param(self->ssl);
806 X509_VERIFY_PARAM_set_hostflags(ssl_params, sslctx->hostflags);
807#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200808 SSL_set_app_data(self->ssl, self);
809 if (sock) {
810 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
811 } else {
812 /* BIOs are reference counted and SSL_set_bio borrows our reference.
813 * To prevent a double free in memory_bio_dealloc() we need to take an
814 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200815 BIO_up_ref(inbio->bio);
816 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200817 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
818 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400819 SSL_set_mode(self->ssl,
820 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000821
Christian Heimesf0f59302019-07-01 08:29:17 +0200822#ifdef TLS1_3_VERSION
823 if (sslctx->post_handshake_auth == 1) {
824 if (socket_type == PY_SSL_SERVER) {
825 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
826 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
827 * only in combination with SSL_VERIFY_PEER flag. */
828 int mode = SSL_get_verify_mode(self->ssl);
829 if (mode & SSL_VERIFY_PEER) {
830 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
831 verify_cb = SSL_get_verify_callback(self->ssl);
832 mode |= SSL_VERIFY_POST_HANDSHAKE;
833 SSL_set_verify(self->ssl, mode, verify_cb);
834 }
835 } else {
836 /* client socket */
837 SSL_set_post_handshake_auth(self->ssl, 1);
838 }
839 }
840#endif
841
Christian Heimes61d478c2018-01-27 15:51:38 +0100842 if (server_hostname != NULL) {
843 if (_ssl_configure_hostname(self, server_hostname) < 0) {
844 Py_DECREF(self);
845 return NULL;
846 }
847 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000848 /* If the socket is in non-blocking mode or timeout mode, set the BIO
849 * to non-blocking mode (blocking is the default)
850 */
Victor Stinnere2452312015-03-28 03:00:46 +0100851 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000852 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
853 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
854 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000855
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000856 PySSL_BEGIN_ALLOW_THREADS
857 if (socket_type == PY_SSL_CLIENT)
858 SSL_set_connect_state(self->ssl);
859 else
860 SSL_set_accept_state(self->ssl);
861 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000862
Antoine Pitroud6494802011-07-21 01:11:30 +0200863 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200864 if (sock != NULL) {
865 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
866 if (self->Socket == NULL) {
867 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200868 return NULL;
869 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100870 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100871 if (owner && owner != Py_None) {
872 if (PySSL_set_owner(self, owner, NULL) == -1) {
873 Py_DECREF(self);
874 return NULL;
875 }
876 }
877 if (session && session != Py_None) {
878 if (PySSL_set_session(self, session, NULL) == -1) {
879 Py_DECREF(self);
880 return NULL;
881 }
882 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000883 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000884}
885
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000886/* SSL object methods */
887
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300888/*[clinic input]
889_ssl._SSLSocket.do_handshake
890[clinic start generated code]*/
891
892static PyObject *
893_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
894/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000895{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700897 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000898 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200899 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200900 _PyTime_t timeout, deadline = 0;
901 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000902
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200903 if (sock) {
904 if (((PyObject*)sock) == Py_None) {
905 _setSSLError("Underlying socket connection gone",
906 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
907 return NULL;
908 }
909 Py_INCREF(sock);
910
911 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100912 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200913 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
914 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000915 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000916
Victor Stinner14690702015-04-06 22:46:13 +0200917 timeout = GET_SOCKET_TIMEOUT(sock);
918 has_timeout = (timeout > 0);
919 if (has_timeout)
920 deadline = _PyTime_GetMonotonicClock() + timeout;
921
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000922 /* Actually negotiate SSL connection */
923 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000924 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000925 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000926 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700927 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000928 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700929 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200930
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000931 if (PyErr_CheckSignals())
932 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200933
Victor Stinner14690702015-04-06 22:46:13 +0200934 if (has_timeout)
935 timeout = deadline - _PyTime_GetMonotonicClock();
936
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700937 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200938 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700939 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200940 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 } else {
942 sockstate = SOCKET_OPERATION_OK;
943 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200944
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +0100946 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000947 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000948 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000949 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
950 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000951 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000952 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000953 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
954 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000955 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000956 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
958 break;
959 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700960 } while (err.ssl == SSL_ERROR_WANT_READ ||
961 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200962 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000963 if (ret < 1)
964 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +0200965 if (PySSL_ChainExceptions(self) < 0)
966 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200967 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000968error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200969 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +0200970 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000971 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000972}
973
Thomas Woutersed03b412007-08-28 21:37:11 +0000974static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300975_asn1obj2py(const ASN1_OBJECT *name, int no_name)
976{
977 char buf[X509_NAME_MAXLEN];
978 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000979 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300980 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000981
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300982 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000983 if (buflen < 0) {
984 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300985 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000986 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300987 /* initial buffer is too small for oid + terminating null byte */
988 if (buflen > X509_NAME_MAXLEN - 1) {
989 /* make OBJ_obj2txt() calculate the required buflen */
990 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
991 /* allocate len + 1 for terminating NULL byte */
992 namebuf = PyMem_Malloc(buflen + 1);
993 if (namebuf == NULL) {
994 PyErr_NoMemory();
995 return NULL;
996 }
997 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
998 if (buflen < 0) {
999 _setSSLError(NULL, 0, __FILE__, __LINE__);
1000 goto done;
1001 }
1002 }
1003 if (!buflen && no_name) {
1004 Py_INCREF(Py_None);
1005 name_obj = Py_None;
1006 }
1007 else {
1008 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1009 }
1010
1011 done:
1012 if (buf != namebuf) {
1013 PyMem_Free(namebuf);
1014 }
1015 return name_obj;
1016}
1017
1018static PyObject *
1019_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1020{
1021 Py_ssize_t buflen;
1022 unsigned char *valuebuf = NULL;
1023 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001024
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001025 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1026 if (buflen < 0) {
1027 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001028 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001029 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001030 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001031 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001032 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001033}
1034
1035static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001036_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001037{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001038 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1039 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1040 PyObject *rdnt;
1041 PyObject *attr = NULL; /* tuple to hold an attribute */
1042 int entry_count = X509_NAME_entry_count(xname);
1043 X509_NAME_ENTRY *entry;
1044 ASN1_OBJECT *name;
1045 ASN1_STRING *value;
1046 int index_counter;
1047 int rdn_level = -1;
1048 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001049
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 dn = PyList_New(0);
1051 if (dn == NULL)
1052 return NULL;
1053 /* now create another tuple to hold the top-level RDN */
1054 rdn = PyList_New(0);
1055 if (rdn == NULL)
1056 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001057
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001058 for (index_counter = 0;
1059 index_counter < entry_count;
1060 index_counter++)
1061 {
1062 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001063
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001064 /* check to see if we've gotten to a new RDN */
1065 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001066 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001067 /* yes, new RDN */
1068 /* add old RDN to DN */
1069 rdnt = PyList_AsTuple(rdn);
1070 Py_DECREF(rdn);
1071 if (rdnt == NULL)
1072 goto fail0;
1073 retcode = PyList_Append(dn, rdnt);
1074 Py_DECREF(rdnt);
1075 if (retcode < 0)
1076 goto fail0;
1077 /* create new RDN */
1078 rdn = PyList_New(0);
1079 if (rdn == NULL)
1080 goto fail0;
1081 }
1082 }
Christian Heimes598894f2016-09-05 23:19:05 +02001083 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001084
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001085 /* now add this attribute to the current RDN */
1086 name = X509_NAME_ENTRY_get_object(entry);
1087 value = X509_NAME_ENTRY_get_data(entry);
1088 attr = _create_tuple_for_attribute(name, value);
1089 /*
1090 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1091 entry->set,
1092 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1093 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1094 */
1095 if (attr == NULL)
1096 goto fail1;
1097 retcode = PyList_Append(rdn, attr);
1098 Py_DECREF(attr);
1099 if (retcode < 0)
1100 goto fail1;
1101 }
1102 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001103 if (rdn != NULL) {
1104 if (PyList_GET_SIZE(rdn) > 0) {
1105 rdnt = PyList_AsTuple(rdn);
1106 Py_DECREF(rdn);
1107 if (rdnt == NULL)
1108 goto fail0;
1109 retcode = PyList_Append(dn, rdnt);
1110 Py_DECREF(rdnt);
1111 if (retcode < 0)
1112 goto fail0;
1113 }
1114 else {
1115 Py_DECREF(rdn);
1116 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001117 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001118
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001119 /* convert list to tuple */
1120 rdnt = PyList_AsTuple(dn);
1121 Py_DECREF(dn);
1122 if (rdnt == NULL)
1123 return NULL;
1124 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001125
1126 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001128
1129 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001130 Py_XDECREF(dn);
1131 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001132}
1133
1134static PyObject *
1135_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 /* this code follows the procedure outlined in
1138 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1139 function to extract the STACK_OF(GENERAL_NAME),
1140 then iterates through the stack to add the
1141 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001142
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001143 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001144 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001145 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001146 GENERAL_NAMES *names = NULL;
1147 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 BIO *biobuf = NULL;
1149 char buf[2048];
1150 char *vptr;
1151 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001152
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001153 if (certificate == NULL)
1154 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001155
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001156 /* get a memory buffer */
1157 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001158 if (biobuf == NULL) {
1159 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1160 return NULL;
1161 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001162
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001163 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1164 certificate, NID_subject_alt_name, NULL, NULL);
1165 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001166 if (peer_alt_names == Py_None) {
1167 peer_alt_names = PyList_New(0);
1168 if (peer_alt_names == NULL)
1169 goto fail;
1170 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001171
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001172 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001173 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001174 int gntype;
1175 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001176
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001177 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001178 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001179 switch (gntype) {
1180 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001181 /* we special-case DirName as a tuple of
1182 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001183
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001184 t = PyTuple_New(2);
1185 if (t == NULL) {
1186 goto fail;
1187 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001188
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001189 v = PyUnicode_FromString("DirName");
1190 if (v == NULL) {
1191 Py_DECREF(t);
1192 goto fail;
1193 }
1194 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001196 v = _create_tuple_for_X509_NAME (name->d.dirn);
1197 if (v == NULL) {
1198 Py_DECREF(t);
1199 goto fail;
1200 }
1201 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001202 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001203
Christian Heimes824f7f32013-08-17 00:54:47 +02001204 case GEN_EMAIL:
1205 case GEN_DNS:
1206 case GEN_URI:
1207 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1208 correctly, CVE-2013-4238 */
1209 t = PyTuple_New(2);
1210 if (t == NULL)
1211 goto fail;
1212 switch (gntype) {
1213 case GEN_EMAIL:
1214 v = PyUnicode_FromString("email");
1215 as = name->d.rfc822Name;
1216 break;
1217 case GEN_DNS:
1218 v = PyUnicode_FromString("DNS");
1219 as = name->d.dNSName;
1220 break;
1221 case GEN_URI:
1222 v = PyUnicode_FromString("URI");
1223 as = name->d.uniformResourceIdentifier;
1224 break;
1225 }
1226 if (v == NULL) {
1227 Py_DECREF(t);
1228 goto fail;
1229 }
1230 PyTuple_SET_ITEM(t, 0, v);
Christian Heimesa871f692020-06-01 08:58:14 +02001231 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
Christian Heimes824f7f32013-08-17 00:54:47 +02001232 ASN1_STRING_length(as));
1233 if (v == NULL) {
1234 Py_DECREF(t);
1235 goto fail;
1236 }
1237 PyTuple_SET_ITEM(t, 1, v);
1238 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001239
Christian Heimes1c03abd2016-09-06 23:25:35 +02001240 case GEN_RID:
1241 t = PyTuple_New(2);
1242 if (t == NULL)
1243 goto fail;
1244
1245 v = PyUnicode_FromString("Registered ID");
1246 if (v == NULL) {
1247 Py_DECREF(t);
1248 goto fail;
1249 }
1250 PyTuple_SET_ITEM(t, 0, v);
1251
1252 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1253 if (len < 0) {
1254 Py_DECREF(t);
1255 _setSSLError(NULL, 0, __FILE__, __LINE__);
1256 goto fail;
1257 } else if (len >= (int)sizeof(buf)) {
1258 v = PyUnicode_FromString("<INVALID>");
1259 } else {
1260 v = PyUnicode_FromStringAndSize(buf, len);
1261 }
1262 if (v == NULL) {
1263 Py_DECREF(t);
1264 goto fail;
1265 }
1266 PyTuple_SET_ITEM(t, 1, v);
1267 break;
1268
Christian Heimes2b7de662019-12-07 17:59:36 +01001269 case GEN_IPADD:
1270 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1271 * the trailing newline. Remove it in all versions
1272 */
1273 t = PyTuple_New(2);
1274 if (t == NULL)
1275 goto fail;
1276
1277 v = PyUnicode_FromString("IP Address");
1278 if (v == NULL) {
1279 Py_DECREF(t);
1280 goto fail;
1281 }
1282 PyTuple_SET_ITEM(t, 0, v);
1283
1284 if (name->d.ip->length == 4) {
1285 unsigned char *p = name->d.ip->data;
1286 v = PyUnicode_FromFormat(
1287 "%d.%d.%d.%d",
1288 p[0], p[1], p[2], p[3]
1289 );
1290 } else if (name->d.ip->length == 16) {
1291 /* PyUnicode_FromFormat() does not support %X */
1292 unsigned char *p = name->d.ip->data;
1293 len = sprintf(
1294 buf,
1295 "%X:%X:%X:%X:%X:%X:%X:%X",
1296 p[0] << 8 | p[1],
1297 p[2] << 8 | p[3],
1298 p[4] << 8 | p[5],
1299 p[6] << 8 | p[7],
1300 p[8] << 8 | p[9],
1301 p[10] << 8 | p[11],
1302 p[12] << 8 | p[13],
1303 p[14] << 8 | p[15]
1304 );
1305 v = PyUnicode_FromStringAndSize(buf, len);
1306 } else {
1307 v = PyUnicode_FromString("<invalid>");
1308 }
1309
1310 if (v == NULL) {
1311 Py_DECREF(t);
1312 goto fail;
1313 }
1314 PyTuple_SET_ITEM(t, 1, v);
1315 break;
1316
Christian Heimes824f7f32013-08-17 00:54:47 +02001317 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001318 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001319 switch (gntype) {
1320 /* check for new general name type */
1321 case GEN_OTHERNAME:
1322 case GEN_X400:
1323 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001324 case GEN_RID:
1325 break;
1326 default:
1327 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1328 "Unknown general name type %d",
1329 gntype) == -1) {
1330 goto fail;
1331 }
1332 break;
1333 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 (void) BIO_reset(biobuf);
1335 GENERAL_NAME_print(biobuf, name);
1336 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1337 if (len < 0) {
1338 _setSSLError(NULL, 0, __FILE__, __LINE__);
1339 goto fail;
1340 }
1341 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001342 if (vptr == NULL) {
1343 PyErr_Format(PyExc_ValueError,
1344 "Invalid value %.200s",
1345 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001346 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001347 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001348 t = PyTuple_New(2);
1349 if (t == NULL)
1350 goto fail;
1351 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1352 if (v == NULL) {
1353 Py_DECREF(t);
1354 goto fail;
1355 }
1356 PyTuple_SET_ITEM(t, 0, v);
1357 v = PyUnicode_FromStringAndSize((vptr + 1),
1358 (len - (vptr - buf + 1)));
1359 if (v == NULL) {
1360 Py_DECREF(t);
1361 goto fail;
1362 }
1363 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001364 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001365 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001366
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001367 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001368
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001369 if (PyList_Append(peer_alt_names, t) < 0) {
1370 Py_DECREF(t);
1371 goto fail;
1372 }
1373 Py_DECREF(t);
1374 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001375 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001376 }
1377 BIO_free(biobuf);
1378 if (peer_alt_names != Py_None) {
1379 v = PyList_AsTuple(peer_alt_names);
1380 Py_DECREF(peer_alt_names);
1381 return v;
1382 } else {
1383 return peer_alt_names;
1384 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001385
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001386
1387 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001388 if (biobuf != NULL)
1389 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001390
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001391 if (peer_alt_names != Py_None) {
1392 Py_XDECREF(peer_alt_names);
1393 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001394
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001395 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001396}
1397
1398static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001399_get_aia_uri(X509 *certificate, int nid) {
1400 PyObject *lst = NULL, *ostr = NULL;
1401 int i, result;
1402 AUTHORITY_INFO_ACCESS *info;
1403
1404 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001405 if (info == NULL)
1406 return Py_None;
1407 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1408 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001409 return Py_None;
1410 }
1411
1412 if ((lst = PyList_New(0)) == NULL) {
1413 goto fail;
1414 }
1415
1416 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1417 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1418 ASN1_IA5STRING *uri;
1419
1420 if ((OBJ_obj2nid(ad->method) != nid) ||
1421 (ad->location->type != GEN_URI)) {
1422 continue;
1423 }
1424 uri = ad->location->d.uniformResourceIdentifier;
1425 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1426 uri->length);
1427 if (ostr == NULL) {
1428 goto fail;
1429 }
1430 result = PyList_Append(lst, ostr);
1431 Py_DECREF(ostr);
1432 if (result < 0) {
1433 goto fail;
1434 }
1435 }
1436 AUTHORITY_INFO_ACCESS_free(info);
1437
1438 /* convert to tuple or None */
1439 if (PyList_Size(lst) == 0) {
1440 Py_DECREF(lst);
1441 return Py_None;
1442 } else {
1443 PyObject *tup;
1444 tup = PyList_AsTuple(lst);
1445 Py_DECREF(lst);
1446 return tup;
1447 }
1448
1449 fail:
1450 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001451 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001452 return NULL;
1453}
1454
1455static PyObject *
1456_get_crl_dp(X509 *certificate) {
1457 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001458 int i, j;
1459 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001460
Christian Heimes598894f2016-09-05 23:19:05 +02001461 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001462
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001463 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001464 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001465
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001466 lst = PyList_New(0);
1467 if (lst == NULL)
1468 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001469
1470 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1471 DIST_POINT *dp;
1472 STACK_OF(GENERAL_NAME) *gns;
1473
1474 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001475 if (dp->distpoint == NULL) {
1476 /* Ignore empty DP value, CVE-2019-5010 */
1477 continue;
1478 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001479 gns = dp->distpoint->name.fullname;
1480
1481 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1482 GENERAL_NAME *gn;
1483 ASN1_IA5STRING *uri;
1484 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001485 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001486
1487 gn = sk_GENERAL_NAME_value(gns, j);
1488 if (gn->type != GEN_URI) {
1489 continue;
1490 }
1491 uri = gn->d.uniformResourceIdentifier;
1492 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1493 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001494 if (ouri == NULL)
1495 goto done;
1496
1497 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001498 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001499 if (err < 0)
1500 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001501 }
1502 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001503
1504 /* Convert to tuple. */
1505 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1506
1507 done:
1508 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001509 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001510 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001511}
1512
1513static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001514_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001515
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001516 PyObject *retval = NULL;
1517 BIO *biobuf = NULL;
1518 PyObject *peer;
1519 PyObject *peer_alt_names = NULL;
1520 PyObject *issuer;
1521 PyObject *version;
1522 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001523 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 ASN1_INTEGER *serialNumber;
1525 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001526 int len, result;
Christian Heimesa871f692020-06-01 08:58:14 +02001527 const ASN1_TIME *notBefore, *notAfter;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001529
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001530 retval = PyDict_New();
1531 if (retval == NULL)
1532 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001533
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001534 peer = _create_tuple_for_X509_NAME(
1535 X509_get_subject_name(certificate));
1536 if (peer == NULL)
1537 goto fail0;
1538 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1539 Py_DECREF(peer);
1540 goto fail0;
1541 }
1542 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001543
Antoine Pitroufb046912010-11-09 20:21:19 +00001544 issuer = _create_tuple_for_X509_NAME(
1545 X509_get_issuer_name(certificate));
1546 if (issuer == NULL)
1547 goto fail0;
1548 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001549 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001550 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001551 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001552 Py_DECREF(issuer);
1553
1554 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001555 if (version == NULL)
1556 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001557 if (PyDict_SetItemString(retval, "version", version) < 0) {
1558 Py_DECREF(version);
1559 goto fail0;
1560 }
1561 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001562
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001563 /* get a memory buffer */
1564 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001565 if (biobuf == NULL) {
1566 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1567 goto fail0;
1568 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001569
Antoine Pitroufb046912010-11-09 20:21:19 +00001570 (void) BIO_reset(biobuf);
1571 serialNumber = X509_get_serialNumber(certificate);
1572 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1573 i2a_ASN1_INTEGER(biobuf, serialNumber);
1574 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1575 if (len < 0) {
1576 _setSSLError(NULL, 0, __FILE__, __LINE__);
1577 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001578 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001579 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1580 if (sn_obj == NULL)
1581 goto fail1;
1582 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1583 Py_DECREF(sn_obj);
1584 goto fail1;
1585 }
1586 Py_DECREF(sn_obj);
1587
1588 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001589 notBefore = X509_get0_notBefore(certificate);
Antoine Pitroufb046912010-11-09 20:21:19 +00001590 ASN1_TIME_print(biobuf, notBefore);
1591 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1592 if (len < 0) {
1593 _setSSLError(NULL, 0, __FILE__, __LINE__);
1594 goto fail1;
1595 }
1596 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1597 if (pnotBefore == NULL)
1598 goto fail1;
1599 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1600 Py_DECREF(pnotBefore);
1601 goto fail1;
1602 }
1603 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001604
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001605 (void) BIO_reset(biobuf);
Christian Heimesa871f692020-06-01 08:58:14 +02001606 notAfter = X509_get0_notAfter(certificate);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001607 ASN1_TIME_print(biobuf, notAfter);
1608 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1609 if (len < 0) {
1610 _setSSLError(NULL, 0, __FILE__, __LINE__);
1611 goto fail1;
1612 }
1613 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1614 if (pnotAfter == NULL)
1615 goto fail1;
1616 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1617 Py_DECREF(pnotAfter);
1618 goto fail1;
1619 }
1620 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001621
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001622 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001623
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001624 peer_alt_names = _get_peer_alt_names(certificate);
1625 if (peer_alt_names == NULL)
1626 goto fail1;
1627 else if (peer_alt_names != Py_None) {
1628 if (PyDict_SetItemString(retval, "subjectAltName",
1629 peer_alt_names) < 0) {
1630 Py_DECREF(peer_alt_names);
1631 goto fail1;
1632 }
1633 Py_DECREF(peer_alt_names);
1634 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001635
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001636 /* Authority Information Access: OCSP URIs */
1637 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1638 if (obj == NULL) {
1639 goto fail1;
1640 } else if (obj != Py_None) {
1641 result = PyDict_SetItemString(retval, "OCSP", obj);
1642 Py_DECREF(obj);
1643 if (result < 0) {
1644 goto fail1;
1645 }
1646 }
1647
1648 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1649 if (obj == NULL) {
1650 goto fail1;
1651 } else if (obj != Py_None) {
1652 result = PyDict_SetItemString(retval, "caIssuers", obj);
1653 Py_DECREF(obj);
1654 if (result < 0) {
1655 goto fail1;
1656 }
1657 }
1658
1659 /* CDP (CRL distribution points) */
1660 obj = _get_crl_dp(certificate);
1661 if (obj == NULL) {
1662 goto fail1;
1663 } else if (obj != Py_None) {
1664 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1665 Py_DECREF(obj);
1666 if (result < 0) {
1667 goto fail1;
1668 }
1669 }
1670
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001671 BIO_free(biobuf);
1672 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001673
1674 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001675 if (biobuf != NULL)
1676 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001677 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001678 Py_XDECREF(retval);
1679 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001680}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001681
Christian Heimes9a5395a2013-06-17 15:44:12 +02001682static PyObject *
1683_certificate_to_der(X509 *certificate)
1684{
1685 unsigned char *bytes_buf = NULL;
1686 int len;
1687 PyObject *retval;
1688
1689 bytes_buf = NULL;
1690 len = i2d_X509(certificate, &bytes_buf);
1691 if (len < 0) {
1692 _setSSLError(NULL, 0, __FILE__, __LINE__);
1693 return NULL;
1694 }
1695 /* this is actually an immutable bytes sequence */
1696 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1697 OPENSSL_free(bytes_buf);
1698 return retval;
1699}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001700
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001701/*[clinic input]
1702_ssl._test_decode_cert
1703 path: object(converter="PyUnicode_FSConverter")
1704 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001705
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001706[clinic start generated code]*/
1707
1708static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001709_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1710/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001711{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001712 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001713 X509 *x=NULL;
1714 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001715
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001716 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1717 PyErr_SetString(PySSLErrorObject,
1718 "Can't malloc memory to read file");
1719 goto fail0;
1720 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001721
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001722 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001723 PyErr_SetString(PySSLErrorObject,
1724 "Can't open file");
1725 goto fail0;
1726 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001727
Alex Gaynor40dad952019-08-15 08:31:28 -04001728 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001729 if (x == NULL) {
1730 PyErr_SetString(PySSLErrorObject,
1731 "Error decoding PEM-encoded file");
1732 goto fail0;
1733 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001734
Antoine Pitroufb046912010-11-09 20:21:19 +00001735 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001736 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001737
1738 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001739 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001740 if (cert != NULL) BIO_free(cert);
1741 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001742}
1743
1744
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001745/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001746_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001747 der as binary_mode: bool = False
1748 /
1749
1750Returns the certificate for the peer.
1751
1752If no certificate was provided, returns None. If a certificate was
1753provided, but not validated, returns an empty dictionary. Otherwise
1754returns a dict containing information about the peer certificate.
1755
1756If the optional argument is True, returns a DER-encoded copy of the
1757peer certificate, or None if no certificate was provided. This will
1758return the certificate even if it wasn't validated.
1759[clinic start generated code]*/
1760
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001761static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001762_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1763/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001764{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001765 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001766 X509 *peer_cert;
1767 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001768
Christian Heimes66dc33b2017-05-23 16:02:02 -07001769 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001770 PyErr_SetString(PyExc_ValueError,
1771 "handshake not done yet");
1772 return NULL;
1773 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001774 peer_cert = SSL_get_peer_certificate(self->ssl);
1775 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001776 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001777
Antoine Pitrou721738f2012-08-15 23:20:39 +02001778 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001779 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001780 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001781 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001782 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001783 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001784 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001785 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001786 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001787 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001788 X509_free(peer_cert);
1789 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001790}
1791
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001792static PyObject *
1793cipher_to_tuple(const SSL_CIPHER *cipher)
1794{
1795 const char *cipher_name, *cipher_protocol;
1796 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001797 if (retval == NULL)
1798 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001799
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001800 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001801 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001802 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001803 PyTuple_SET_ITEM(retval, 0, Py_None);
1804 } else {
1805 v = PyUnicode_FromString(cipher_name);
1806 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001807 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001808 PyTuple_SET_ITEM(retval, 0, v);
1809 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001810
1811 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001812 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001813 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001814 PyTuple_SET_ITEM(retval, 1, Py_None);
1815 } else {
1816 v = PyUnicode_FromString(cipher_protocol);
1817 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001818 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001819 PyTuple_SET_ITEM(retval, 1, v);
1820 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001821
1822 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001824 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001826
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001827 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001828
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001829 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001830 Py_DECREF(retval);
1831 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001832}
1833
Christian Heimes25bfcd52016-09-06 00:04:45 +02001834static PyObject *
1835cipher_to_dict(const SSL_CIPHER *cipher)
1836{
1837 const char *cipher_name, *cipher_protocol;
1838
1839 unsigned long cipher_id;
1840 int alg_bits, strength_bits, len;
1841 char buf[512] = {0};
Christian Heimes25bfcd52016-09-06 00:04:45 +02001842 int aead, nid;
1843 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001844
1845 /* can be NULL */
1846 cipher_name = SSL_CIPHER_get_name(cipher);
1847 cipher_protocol = SSL_CIPHER_get_version(cipher);
1848 cipher_id = SSL_CIPHER_get_id(cipher);
1849 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001850 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1851 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001852 if (len > 1 && buf[len-1] == '\n')
1853 buf[len-1] = '\0';
1854 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1855
Christian Heimes25bfcd52016-09-06 00:04:45 +02001856 aead = SSL_CIPHER_is_aead(cipher);
1857 nid = SSL_CIPHER_get_cipher_nid(cipher);
1858 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1859 nid = SSL_CIPHER_get_digest_nid(cipher);
1860 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1861 nid = SSL_CIPHER_get_kx_nid(cipher);
1862 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1863 nid = SSL_CIPHER_get_auth_nid(cipher);
1864 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
Christian Heimes25bfcd52016-09-06 00:04:45 +02001865
Victor Stinner410b9882016-09-12 12:00:23 +02001866 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001867 "{sksssssssisi"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001868 "sOssssssss"
Christian Heimes25bfcd52016-09-06 00:04:45 +02001869 "}",
1870 "id", cipher_id,
1871 "name", cipher_name,
1872 "protocol", cipher_protocol,
1873 "description", buf,
1874 "strength_bits", strength_bits,
1875 "alg_bits", alg_bits
Christian Heimes25bfcd52016-09-06 00:04:45 +02001876 ,"aead", aead ? Py_True : Py_False,
1877 "symmetric", skcipher,
1878 "digest", digest,
1879 "kea", kx,
1880 "auth", auth
Christian Heimes25bfcd52016-09-06 00:04:45 +02001881 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001882}
Christian Heimes25bfcd52016-09-06 00:04:45 +02001883
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001884/*[clinic input]
1885_ssl._SSLSocket.shared_ciphers
1886[clinic start generated code]*/
1887
1888static PyObject *
1889_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1890/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001891{
1892 STACK_OF(SSL_CIPHER) *ciphers;
1893 int i;
1894 PyObject *res;
1895
Christian Heimes598894f2016-09-05 23:19:05 +02001896 ciphers = SSL_get_ciphers(self->ssl);
1897 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001898 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001899 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1900 if (!res)
1901 return NULL;
1902 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1903 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1904 if (!tup) {
1905 Py_DECREF(res);
1906 return NULL;
1907 }
1908 PyList_SET_ITEM(res, i, tup);
1909 }
1910 return res;
1911}
1912
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001913/*[clinic input]
1914_ssl._SSLSocket.cipher
1915[clinic start generated code]*/
1916
1917static PyObject *
1918_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1919/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001920{
1921 const SSL_CIPHER *current;
1922
1923 if (self->ssl == NULL)
1924 Py_RETURN_NONE;
1925 current = SSL_get_current_cipher(self->ssl);
1926 if (current == NULL)
1927 Py_RETURN_NONE;
1928 return cipher_to_tuple(current);
1929}
1930
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001931/*[clinic input]
1932_ssl._SSLSocket.version
1933[clinic start generated code]*/
1934
1935static PyObject *
1936_ssl__SSLSocket_version_impl(PySSLSocket *self)
1937/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001938{
1939 const char *version;
1940
1941 if (self->ssl == NULL)
1942 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001943 if (!SSL_is_init_finished(self->ssl)) {
1944 /* handshake not finished */
1945 Py_RETURN_NONE;
1946 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001947 version = SSL_get_version(self->ssl);
1948 if (!strcmp(version, "unknown"))
1949 Py_RETURN_NONE;
1950 return PyUnicode_FromString(version);
1951}
1952
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001953/*[clinic input]
1954_ssl._SSLSocket.selected_alpn_protocol
1955[clinic start generated code]*/
1956
1957static PyObject *
1958_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1959/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1960{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001961 const unsigned char *out;
1962 unsigned int outlen;
1963
1964 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1965
1966 if (out == NULL)
1967 Py_RETURN_NONE;
1968 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001969}
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001970
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001971/*[clinic input]
1972_ssl._SSLSocket.compression
1973[clinic start generated code]*/
1974
1975static PyObject *
1976_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1977/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1978{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001979#ifdef OPENSSL_NO_COMP
1980 Py_RETURN_NONE;
1981#else
1982 const COMP_METHOD *comp_method;
1983 const char *short_name;
1984
1985 if (self->ssl == NULL)
1986 Py_RETURN_NONE;
1987 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001988 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001989 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001990 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001991 if (short_name == NULL)
1992 Py_RETURN_NONE;
1993 return PyUnicode_DecodeFSDefault(short_name);
1994#endif
1995}
1996
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001997static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1998 Py_INCREF(self->ctx);
1999 return self->ctx;
2000}
2001
2002static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2003 void *closure) {
2004
Christian Heimes5c36da72020-11-20 09:40:12 +01002005 if (PyObject_TypeCheck(value, PySSLContext_Type)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002006 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002007 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002008 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Christian Heimes77cde502021-03-21 16:13:09 +01002009 /* Set SSL* internal msg_callback to state of new context's state */
2010 SSL_set_msg_callback(
2011 self->ssl,
2012 self->ctx->msg_cb ? _PySSL_msg_callback : NULL
2013 );
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002014 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002015 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002016 return -1;
2017 }
2018
2019 return 0;
2020}
2021
2022PyDoc_STRVAR(PySSL_set_context_doc,
2023"_setter_context(ctx)\n\
2024\
2025This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002026used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002027on the SSLContext to change the certificate information associated with the\n\
2028SSLSocket before the cryptographic exchange handshake messages\n");
2029
2030
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002031static PyObject *
2032PySSL_get_server_side(PySSLSocket *self, void *c)
2033{
2034 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2035}
2036
2037PyDoc_STRVAR(PySSL_get_server_side_doc,
2038"Whether this is a server-side socket.");
2039
2040static PyObject *
2041PySSL_get_server_hostname(PySSLSocket *self, void *c)
2042{
2043 if (self->server_hostname == NULL)
2044 Py_RETURN_NONE;
2045 Py_INCREF(self->server_hostname);
2046 return self->server_hostname;
2047}
2048
2049PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2050"The currently set server hostname (for SNI).");
2051
2052static PyObject *
2053PySSL_get_owner(PySSLSocket *self, void *c)
2054{
2055 PyObject *owner;
2056
2057 if (self->owner == NULL)
2058 Py_RETURN_NONE;
2059
2060 owner = PyWeakref_GetObject(self->owner);
2061 Py_INCREF(owner);
2062 return owner;
2063}
2064
2065static int
2066PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2067{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002068 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002069 if (self->owner == NULL)
2070 return -1;
2071 return 0;
2072}
2073
2074PyDoc_STRVAR(PySSL_get_owner_doc,
2075"The Python-level owner of this object.\
2076Passed as \"self\" in servername callback.");
2077
Christian Heimesc7f70692019-05-31 11:44:05 +02002078static int
2079PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2080{
2081 Py_VISIT(self->exc_type);
2082 Py_VISIT(self->exc_value);
2083 Py_VISIT(self->exc_tb);
2084 return 0;
2085}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002086
Christian Heimesc7f70692019-05-31 11:44:05 +02002087static int
2088PySSL_clear(PySSLSocket *self)
2089{
2090 Py_CLEAR(self->exc_type);
2091 Py_CLEAR(self->exc_value);
2092 Py_CLEAR(self->exc_tb);
2093 return 0;
2094}
2095
2096static void
2097PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002098{
Christian Heimes5c36da72020-11-20 09:40:12 +01002099 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002100 if (self->ssl)
2101 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002102 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002103 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002104 Py_XDECREF(self->server_hostname);
2105 Py_XDECREF(self->owner);
Victor Stinner32bd68c2020-12-01 10:37:39 +01002106 PyObject_Free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01002107 Py_DECREF(tp);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002108}
2109
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002110/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002111 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002112 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002113 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002114
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002115static int
Victor Stinner14690702015-04-06 22:46:13 +02002116PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002117{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002118 int rc;
2119#ifdef HAVE_POLL
2120 struct pollfd pollfd;
2121 _PyTime_t ms;
2122#else
2123 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002124 fd_set fds;
2125 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002126#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002127
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002128 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002129 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002130 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002131 else if (timeout < 0) {
2132 if (s->sock_timeout > 0)
2133 return SOCKET_HAS_TIMED_OUT;
2134 else
2135 return SOCKET_IS_BLOCKING;
2136 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002137
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002138 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002139 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002140 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002141
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002142 /* Prefer poll, if available, since you can poll() any fd
2143 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002144#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002145 pollfd.fd = s->sock_fd;
2146 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002147
Victor Stinner14690702015-04-06 22:46:13 +02002148 /* timeout is in seconds, poll() uses milliseconds */
2149 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002150 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002151
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002152 PySSL_BEGIN_ALLOW_THREADS
2153 rc = poll(&pollfd, 1, (int)ms);
2154 PySSL_END_ALLOW_THREADS
2155#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002156 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002157 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002158 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002159
Victor Stinner14690702015-04-06 22:46:13 +02002160 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002161
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002162 FD_ZERO(&fds);
2163 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002164
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002165 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002166 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002167 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002168 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002169 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002170 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002171 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002172 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002173#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002174
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002175 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2176 (when we are able to write or when there's something to read) */
2177 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002178}
2179
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002180/*[clinic input]
2181_ssl._SSLSocket.write
2182 b: Py_buffer
2183 /
2184
2185Writes the bytes-like object b into the SSL object.
2186
2187Returns the number of bytes written.
2188[clinic start generated code]*/
2189
2190static PyObject *
2191_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2192/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002193{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002194 int len;
2195 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002196 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002197 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002198 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002199 _PyTime_t timeout, deadline = 0;
2200 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002201
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002202 if (sock != NULL) {
2203 if (((PyObject*)sock) == Py_None) {
2204 _setSSLError("Underlying socket connection gone",
2205 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2206 return NULL;
2207 }
2208 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002209 }
2210
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002211 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002212 PyErr_Format(PyExc_OverflowError,
2213 "string longer than %d bytes", INT_MAX);
2214 goto error;
2215 }
2216
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002217 if (sock != NULL) {
2218 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002219 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002220 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2221 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2222 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002223
Victor Stinner14690702015-04-06 22:46:13 +02002224 timeout = GET_SOCKET_TIMEOUT(sock);
2225 has_timeout = (timeout > 0);
2226 if (has_timeout)
2227 deadline = _PyTime_GetMonotonicClock() + timeout;
2228
2229 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002230 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002231 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002232 "The write operation timed out");
2233 goto error;
2234 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2235 PyErr_SetString(PySSLErrorObject,
2236 "Underlying socket has been closed.");
2237 goto error;
2238 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2239 PyErr_SetString(PySSLErrorObject,
2240 "Underlying socket too large for select().");
2241 goto error;
2242 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002243
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002244 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002245 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002246 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002247 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002248 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002249 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002250
2251 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002252 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002253
Victor Stinner14690702015-04-06 22:46:13 +02002254 if (has_timeout)
2255 timeout = deadline - _PyTime_GetMonotonicClock();
2256
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002257 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002258 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002259 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002260 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002261 } else {
2262 sockstate = SOCKET_OPERATION_OK;
2263 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002264
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002265 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002266 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002267 "The write operation timed out");
2268 goto error;
2269 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2270 PyErr_SetString(PySSLErrorObject,
2271 "Underlying socket has been closed.");
2272 goto error;
2273 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2274 break;
2275 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002276 } while (err.ssl == SSL_ERROR_WANT_READ ||
2277 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002278
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002279 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002280 if (len <= 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002281 return PySSL_SetError(self, len, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002282 if (PySSL_ChainExceptions(self) < 0)
2283 return NULL;
2284 return PyLong_FromLong(len);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002285error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002286 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002287 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002288 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002289}
2290
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002291/*[clinic input]
2292_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002293
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002294Returns the number of already decrypted bytes available for read, pending on the connection.
2295[clinic start generated code]*/
2296
2297static PyObject *
2298_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2299/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002300{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002301 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002302 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002303
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002304 PySSL_BEGIN_ALLOW_THREADS
2305 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002306 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002307 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002308 self->err = err;
2309
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002310 if (count < 0)
2311 return PySSL_SetError(self, count, __FILE__, __LINE__);
2312 else
2313 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002314}
2315
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002316/*[clinic input]
2317_ssl._SSLSocket.read
2318 size as len: int
2319 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002320 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002321 ]
2322 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002323
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002324Read up to size bytes from the SSL socket.
2325[clinic start generated code]*/
2326
2327static PyObject *
2328_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2329 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002330/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002331{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002332 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002333 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002334 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002335 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002336 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002337 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002338 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002339 _PyTime_t timeout, deadline = 0;
2340 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002341
Martin Panter5503d472016-03-27 05:35:19 +00002342 if (!group_right_1 && len < 0) {
2343 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2344 return NULL;
2345 }
2346
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002347 if (sock != NULL) {
2348 if (((PyObject*)sock) == Py_None) {
2349 _setSSLError("Underlying socket connection gone",
2350 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2351 return NULL;
2352 }
2353 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002354 }
2355
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002356 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002357 dest = PyBytes_FromStringAndSize(NULL, len);
2358 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002359 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002360 if (len == 0) {
2361 Py_XDECREF(sock);
2362 return dest;
2363 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002364 mem = PyBytes_AS_STRING(dest);
2365 }
2366 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002367 mem = buffer->buf;
2368 if (len <= 0 || len > buffer->len) {
2369 len = (int) buffer->len;
2370 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002371 PyErr_SetString(PyExc_OverflowError,
2372 "maximum length can't fit in a C 'int'");
2373 goto error;
2374 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002375 if (len == 0) {
2376 count = 0;
2377 goto done;
2378 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002379 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002380 }
2381
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002382 if (sock != NULL) {
2383 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002384 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002385 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2386 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2387 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002388
Victor Stinner14690702015-04-06 22:46:13 +02002389 timeout = GET_SOCKET_TIMEOUT(sock);
2390 has_timeout = (timeout > 0);
2391 if (has_timeout)
2392 deadline = _PyTime_GetMonotonicClock() + timeout;
2393
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002394 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002395 PySSL_BEGIN_ALLOW_THREADS
2396 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002397 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002398 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002399 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002400
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002401 if (PyErr_CheckSignals())
2402 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002403
Victor Stinner14690702015-04-06 22:46:13 +02002404 if (has_timeout)
2405 timeout = deadline - _PyTime_GetMonotonicClock();
2406
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002407 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002408 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002409 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002410 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002411 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002412 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002413 {
2414 count = 0;
2415 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002416 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002417 else
2418 sockstate = SOCKET_OPERATION_OK;
2419
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002420 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002421 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002422 "The read operation timed out");
2423 goto error;
2424 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2425 break;
2426 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002427 } while (err.ssl == SSL_ERROR_WANT_READ ||
2428 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002429
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002430 if (count <= 0) {
2431 PySSL_SetError(self, count, __FILE__, __LINE__);
2432 goto error;
2433 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002434 if (self->exc_type != NULL)
2435 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002436
2437done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002438 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002439 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002440 _PyBytes_Resize(&dest, count);
2441 return dest;
2442 }
2443 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002444 return PyLong_FromLong(count);
2445 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002446
2447error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002448 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002449 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002450 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002451 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002452 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002453}
2454
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002455/*[clinic input]
2456_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002457
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002458Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002459[clinic start generated code]*/
2460
2461static PyObject *
2462_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002463/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002464{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002465 _PySSLError err;
2466 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002467 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002468 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002469 _PyTime_t timeout, deadline = 0;
2470 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002471
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002472 if (sock != NULL) {
2473 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002474 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002475 _setSSLError("Underlying socket connection gone",
2476 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2477 return NULL;
2478 }
2479 Py_INCREF(sock);
2480
2481 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002482 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002483 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2484 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002485 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002486
Victor Stinner14690702015-04-06 22:46:13 +02002487 timeout = GET_SOCKET_TIMEOUT(sock);
2488 has_timeout = (timeout > 0);
2489 if (has_timeout)
2490 deadline = _PyTime_GetMonotonicClock() + timeout;
2491
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002492 while (1) {
2493 PySSL_BEGIN_ALLOW_THREADS
2494 /* Disable read-ahead so that unwrap can work correctly.
2495 * Otherwise OpenSSL might read in too much data,
2496 * eating clear text data that happens to be
2497 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002498 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002499 * function is used and the shutdown_seen_zero != 0
2500 * condition is met.
2501 */
2502 if (self->shutdown_seen_zero)
2503 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002504 ret = SSL_shutdown(self->ssl);
2505 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002506 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002507 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002508
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002509 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002510 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002511 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002512 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002513 /* Don't loop endlessly; instead preserve legacy
2514 behaviour of trying SSL_shutdown() only twice.
2515 This looks necessary for OpenSSL < 0.9.8m */
2516 if (++zeros > 1)
2517 break;
2518 /* Shutdown was sent, now try receiving */
2519 self->shutdown_seen_zero = 1;
2520 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002521 }
2522
Victor Stinner14690702015-04-06 22:46:13 +02002523 if (has_timeout)
2524 timeout = deadline - _PyTime_GetMonotonicClock();
2525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002526 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002527 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002528 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002529 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002530 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002531 else
2532 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002533
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002534 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002535 if (err.ssl == SSL_ERROR_WANT_READ)
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002536 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002537 "The read operation timed out");
2538 else
Christian Heimes03c8ddd2020-11-20 09:26:07 +01002539 PyErr_SetString(PyExc_TimeoutError,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002540 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002541 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002542 }
2543 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2544 PyErr_SetString(PySSLErrorObject,
2545 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002546 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002547 }
2548 else if (sockstate != SOCKET_OPERATION_OK)
2549 /* Retain the SSL error code */
2550 break;
2551 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002552 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002553 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002554 PySSL_SetError(self, ret, __FILE__, __LINE__);
2555 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002556 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002557 if (self->exc_type != NULL)
2558 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002559 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002560 /* It's already INCREF'ed */
2561 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002562 else
2563 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002564
2565error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002566 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002567 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002568 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002569}
2570
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002571/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002572_ssl._SSLSocket.get_channel_binding
2573 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002574
Christian Heimes141c5e82018-02-24 21:10:57 +01002575Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002576
Christian Heimes141c5e82018-02-24 21:10:57 +01002577Raise ValueError if the requested `cb_type` is not supported. Return bytes
2578of the data or None if the data is not available (e.g. before the handshake).
2579Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002580[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002581
Antoine Pitroud6494802011-07-21 01:11:30 +02002582static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002583_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2584 const char *cb_type)
2585/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002586{
Antoine Pitroud6494802011-07-21 01:11:30 +02002587 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002588 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002589
Christian Heimes141c5e82018-02-24 21:10:57 +01002590 if (strcmp(cb_type, "tls-unique") == 0) {
2591 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2592 /* if session is resumed XOR we are the client */
2593 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2594 }
2595 else {
2596 /* if a new session XOR we are the server */
2597 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2598 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002599 }
2600 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002601 PyErr_Format(
2602 PyExc_ValueError,
2603 "'%s' channel binding type not implemented",
2604 cb_type
2605 );
2606 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002607 }
2608
2609 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002610 if (len == 0)
2611 Py_RETURN_NONE;
2612
Christian Heimes141c5e82018-02-24 21:10:57 +01002613 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002614}
2615
Christian Heimes9fb051f2018-09-23 08:32:31 +02002616/*[clinic input]
2617_ssl._SSLSocket.verify_client_post_handshake
2618
2619Initiate TLS 1.3 post-handshake authentication
2620[clinic start generated code]*/
2621
2622static PyObject *
2623_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2624/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2625{
2626#ifdef TLS1_3_VERSION
2627 int err = SSL_verify_client_post_handshake(self->ssl);
2628 if (err == 0)
2629 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2630 else
2631 Py_RETURN_NONE;
2632#else
2633 PyErr_SetString(PyExc_NotImplementedError,
2634 "Post-handshake auth is not supported by your "
2635 "OpenSSL version.");
2636 return NULL;
2637#endif
2638}
2639
Christian Heimes99a65702016-09-10 23:44:53 +02002640static SSL_SESSION*
2641_ssl_session_dup(SSL_SESSION *session) {
2642 SSL_SESSION *newsession = NULL;
2643 int slen;
2644 unsigned char *senc = NULL, *p;
2645 const unsigned char *const_p;
2646
2647 if (session == NULL) {
2648 PyErr_SetString(PyExc_ValueError, "Invalid session");
2649 goto error;
2650 }
2651
2652 /* get length */
2653 slen = i2d_SSL_SESSION(session, NULL);
2654 if (slen == 0 || slen > 0xFF00) {
2655 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2656 goto error;
2657 }
2658 if ((senc = PyMem_Malloc(slen)) == NULL) {
2659 PyErr_NoMemory();
2660 goto error;
2661 }
2662 p = senc;
2663 if (!i2d_SSL_SESSION(session, &p)) {
2664 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2665 goto error;
2666 }
2667 const_p = senc;
2668 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2669 if (session == NULL) {
2670 goto error;
2671 }
2672 PyMem_Free(senc);
2673 return newsession;
2674 error:
2675 if (senc != NULL) {
2676 PyMem_Free(senc);
2677 }
2678 return NULL;
2679}
Christian Heimes99a65702016-09-10 23:44:53 +02002680
2681static PyObject *
2682PySSL_get_session(PySSLSocket *self, void *closure) {
2683 /* get_session can return sessions from a server-side connection,
2684 * it does not check for handshake done or client socket. */
2685 PySSLSession *pysess;
2686 SSL_SESSION *session;
2687
Christian Heimes99a65702016-09-10 23:44:53 +02002688 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2689 * https://github.com/openssl/openssl/issues/1550 */
2690 session = SSL_get0_session(self->ssl); /* borrowed reference */
2691 if (session == NULL) {
2692 Py_RETURN_NONE;
2693 }
2694 if ((session = _ssl_session_dup(session)) == NULL) {
2695 return NULL;
2696 }
Christian Heimes99a65702016-09-10 23:44:53 +02002697 session = SSL_get1_session(self->ssl);
2698 if (session == NULL) {
2699 Py_RETURN_NONE;
2700 }
Christian Heimes5c36da72020-11-20 09:40:12 +01002701 pysess = PyObject_GC_New(PySSLSession, PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002702 if (pysess == NULL) {
2703 SSL_SESSION_free(session);
2704 return NULL;
2705 }
2706
2707 assert(self->ctx);
2708 pysess->ctx = self->ctx;
2709 Py_INCREF(pysess->ctx);
2710 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002711 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002712 return (PyObject *)pysess;
2713}
2714
2715static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2716 void *closure)
2717 {
2718 PySSLSession *pysess;
Christian Heimes99a65702016-09-10 23:44:53 +02002719 SSL_SESSION *session;
Christian Heimes99a65702016-09-10 23:44:53 +02002720 int result;
2721
2722 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002723 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002724 return -1;
2725 }
2726 pysess = (PySSLSession *)value;
2727
2728 if (self->ctx->ctx != pysess->ctx->ctx) {
2729 PyErr_SetString(PyExc_ValueError,
2730 "Session refers to a different SSLContext.");
2731 return -1;
2732 }
2733 if (self->socket_type != PY_SSL_CLIENT) {
2734 PyErr_SetString(PyExc_ValueError,
2735 "Cannot set session for server-side SSLSocket.");
2736 return -1;
2737 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002738 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002739 PyErr_SetString(PyExc_ValueError,
2740 "Cannot set session after handshake.");
2741 return -1;
2742 }
Christian Heimes99a65702016-09-10 23:44:53 +02002743 /* duplicate session */
2744 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2745 return -1;
2746 }
2747 result = SSL_set_session(self->ssl, session);
2748 /* free duplicate, SSL_set_session() bumps ref count */
2749 SSL_SESSION_free(session);
Christian Heimes99a65702016-09-10 23:44:53 +02002750 if (result == 0) {
2751 _setSSLError(NULL, 0, __FILE__, __LINE__);
2752 return -1;
2753 }
2754 return 0;
2755}
2756
2757PyDoc_STRVAR(PySSL_set_session_doc,
2758"_setter_session(session)\n\
2759\
2760Get / set SSLSession.");
2761
2762static PyObject *
2763PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2764 if (SSL_session_reused(self->ssl)) {
2765 Py_RETURN_TRUE;
2766 } else {
2767 Py_RETURN_FALSE;
2768 }
2769}
2770
2771PyDoc_STRVAR(PySSL_get_session_reused_doc,
2772"Was the client session reused during handshake?");
2773
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002774static PyGetSetDef ssl_getsetlist[] = {
2775 {"context", (getter) PySSL_get_context,
2776 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002777 {"server_side", (getter) PySSL_get_server_side, NULL,
2778 PySSL_get_server_side_doc},
2779 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2780 PySSL_get_server_hostname_doc},
2781 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2782 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002783 {"session", (getter) PySSL_get_session,
2784 (setter) PySSL_set_session, PySSL_set_session_doc},
2785 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2786 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002787 {NULL}, /* sentinel */
2788};
2789
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002790static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002791 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2792 _SSL__SSLSOCKET_WRITE_METHODDEF
2793 _SSL__SSLSOCKET_READ_METHODDEF
2794 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002795 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2796 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002797 _SSL__SSLSOCKET_CIPHER_METHODDEF
2798 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2799 _SSL__SSLSOCKET_VERSION_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002800 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2801 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2802 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002803 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002804 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002805};
2806
Christian Heimes5c36da72020-11-20 09:40:12 +01002807static PyType_Slot PySSLSocket_slots[] = {
2808 {Py_tp_methods, PySSLMethods},
2809 {Py_tp_getset, ssl_getsetlist},
2810 {Py_tp_dealloc, PySSL_dealloc},
2811 {Py_tp_traverse, PySSL_traverse},
2812 {Py_tp_clear, PySSL_clear},
2813 {0, 0},
2814};
2815
2816static PyType_Spec PySSLSocket_spec = {
2817 "_ssl._SSLSocket",
2818 sizeof(PySSLSocket),
2819 0,
2820 Py_TPFLAGS_DEFAULT,
2821 PySSLSocket_slots,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002822};
2823
Antoine Pitrou152efa22010-05-16 18:19:27 +00002824
2825/*
2826 * _SSLContext objects
2827 */
2828
Christian Heimes5fe668c2016-09-12 00:01:11 +02002829static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02002830_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002831{
2832 int mode;
2833 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2834
2835 switch(n) {
2836 case PY_SSL_CERT_NONE:
2837 mode = SSL_VERIFY_NONE;
2838 break;
2839 case PY_SSL_CERT_OPTIONAL:
2840 mode = SSL_VERIFY_PEER;
2841 break;
2842 case PY_SSL_CERT_REQUIRED:
2843 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2844 break;
2845 default:
2846 PyErr_SetString(PyExc_ValueError,
2847 "invalid value for verify_mode");
2848 return -1;
2849 }
Christian Heimesf0f59302019-07-01 08:29:17 +02002850
2851 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
2852 * server sockets and SSL_set_post_handshake_auth() for client. */
2853
Christian Heimes5fe668c2016-09-12 00:01:11 +02002854 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02002855 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2856 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002857 return 0;
2858}
2859
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002860/*[clinic input]
2861@classmethod
2862_ssl._SSLContext.__new__
2863 protocol as proto_version: int
2864 /
2865[clinic start generated code]*/
2866
Antoine Pitrou152efa22010-05-16 18:19:27 +00002867static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002868_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2869/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002870{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002871 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002872 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002873 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002874 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002875 int result;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002876
Antoine Pitrou152efa22010-05-16 18:19:27 +00002877 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes6e8cda92020-05-16 03:33:05 +02002878 switch(proto_version) {
2879#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
2880 case PY_SSL_VERSION_SSL3:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002881 ctx = SSL_CTX_new(SSLv3_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02002882 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05002883#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002884#if (defined(TLS1_VERSION) && \
2885 !defined(OPENSSL_NO_TLS1) && \
2886 !defined(OPENSSL_NO_TLS1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002887 case PY_SSL_VERSION_TLS1:
2888 ctx = SSL_CTX_new(TLSv1_method());
2889 break;
Victor Stinner3de49192011-05-09 00:42:58 +02002890#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002891#if (defined(TLS1_1_VERSION) && \
2892 !defined(OPENSSL_NO_TLS1_1) && \
2893 !defined(OPENSSL_NO_TLS1_1_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002894 case PY_SSL_VERSION_TLS1_1:
2895 ctx = SSL_CTX_new(TLSv1_1_method());
2896 break;
2897#endif
Christian Heimesa871f692020-06-01 08:58:14 +02002898#if (defined(TLS1_2_VERSION) && \
2899 !defined(OPENSSL_NO_TLS1_2) && \
2900 !defined(OPENSSL_NO_TLS1_2_METHOD))
Christian Heimes6e8cda92020-05-16 03:33:05 +02002901 case PY_SSL_VERSION_TLS1_2:
2902 ctx = SSL_CTX_new(TLSv1_2_method());
2903 break;
2904#endif
2905 case PY_SSL_VERSION_TLS:
2906 /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002907 ctx = SSL_CTX_new(TLS_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02002908 break;
2909 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes5fe668c2016-09-12 00:01:11 +02002910 ctx = SSL_CTX_new(TLS_client_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02002911 break;
2912 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes5fe668c2016-09-12 00:01:11 +02002913 ctx = SSL_CTX_new(TLS_server_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02002914 break;
2915 default:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002916 proto_version = -1;
Christian Heimes6e8cda92020-05-16 03:33:05 +02002917 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002918 PySSL_END_ALLOW_THREADS
2919
2920 if (proto_version == -1) {
2921 PyErr_SetString(PyExc_ValueError,
Christian Heimes6e8cda92020-05-16 03:33:05 +02002922 "invalid or unsupported protocol version");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002923 return NULL;
2924 }
2925 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002926 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002927 return NULL;
2928 }
2929
2930 assert(type != NULL && type->tp_alloc != NULL);
2931 self = (PySSLContext *) type->tp_alloc(type, 0);
2932 if (self == NULL) {
2933 SSL_CTX_free(ctx);
2934 return NULL;
2935 }
2936 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002937 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01002938 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02002939 self->msg_cb = NULL;
Christian Heimesc7f70692019-05-31 11:44:05 +02002940 self->keylog_filename = NULL;
2941 self->keylog_bio = NULL;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002942 self->alpn_protocols = NULL;
Christian Heimes11a14932018-02-24 02:35:08 +01002943 self->set_sni_cb = NULL;
Christian Heimes1aa9a752013-12-02 02:41:19 +01002944 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002945 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2946 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02002947 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02002948 Py_DECREF(self);
2949 return NULL;
2950 }
2951 } else {
2952 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02002953 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02002954 Py_DECREF(self);
2955 return NULL;
2956 }
2957 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002958 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002959 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2960 if (proto_version != PY_SSL_VERSION_SSL2)
2961 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002962 if (proto_version != PY_SSL_VERSION_SSL3)
2963 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002964 /* Minimal security flags for server and client side context.
2965 * Client sockets ignore server-side parameters. */
2966#ifdef SSL_OP_NO_COMPRESSION
2967 options |= SSL_OP_NO_COMPRESSION;
2968#endif
2969#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2970 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2971#endif
2972#ifdef SSL_OP_SINGLE_DH_USE
2973 options |= SSL_OP_SINGLE_DH_USE;
2974#endif
2975#ifdef SSL_OP_SINGLE_ECDH_USE
2976 options |= SSL_OP_SINGLE_ECDH_USE;
2977#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02002978#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
2979 /* Make OpenSSL 3.0.0 behave like 1.1.1 */
2980 options |= SSL_OP_IGNORE_UNEXPECTED_EOF;
2981#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002982 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002983
Semen Zhydenko1295e112017-10-15 21:28:31 +02002984 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02002985 * It's far from perfect but gives users a better head start. */
2986 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01002987#if PY_SSL_DEFAULT_CIPHERS == 2
2988 /* stick to OpenSSL's default settings */
2989 result = 1;
2990#else
2991 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
2992#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02002993 } else {
2994 /* SSLv2 needs MD5 */
2995 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2996 }
2997 if (result == 0) {
2998 Py_DECREF(self);
2999 ERR_clear_error();
3000 PyErr_SetString(PySSLErrorObject,
3001 "No cipher can be selected.");
3002 return NULL;
3003 }
3004
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003005 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
Christian Heimes39258d32021-04-17 11:36:35 +02003006 usage for no cost at all. */
3007 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003008
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003009#define SID_CTX "Python"
3010 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3011 sizeof(SID_CTX));
3012#undef SID_CTX
3013
Christian Heimes61d478c2018-01-27 15:51:38 +01003014 params = SSL_CTX_get0_param(self->ctx);
Christian Heimes61d478c2018-01-27 15:51:38 +01003015 /* Improve trust chain building when cross-signed intermediate
3016 certificates are present. See https://bugs.python.org/issue23476. */
3017 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Christian Heimes61d478c2018-01-27 15:51:38 +01003018 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003019
Christian Heimes9fb051f2018-09-23 08:32:31 +02003020#ifdef TLS1_3_VERSION
3021 self->post_handshake_auth = 0;
3022 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3023#endif
3024
Antoine Pitrou152efa22010-05-16 18:19:27 +00003025 return (PyObject *)self;
3026}
3027
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003028static int
3029context_traverse(PySSLContext *self, visitproc visit, void *arg)
3030{
Christian Heimes11a14932018-02-24 02:35:08 +01003031 Py_VISIT(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003032 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003033 return 0;
3034}
3035
3036static int
3037context_clear(PySSLContext *self)
3038{
Christian Heimes11a14932018-02-24 02:35:08 +01003039 Py_CLEAR(self->set_sni_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003040 Py_CLEAR(self->msg_cb);
Christian Heimesc7f70692019-05-31 11:44:05 +02003041 Py_CLEAR(self->keylog_filename);
3042 if (self->keylog_bio != NULL) {
3043 PySSL_BEGIN_ALLOW_THREADS
3044 BIO_free_all(self->keylog_bio);
3045 PySSL_END_ALLOW_THREADS
3046 self->keylog_bio = NULL;
3047 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003048 return 0;
3049}
3050
Antoine Pitrou152efa22010-05-16 18:19:27 +00003051static void
3052context_dealloc(PySSLContext *self)
3053{
Christian Heimes5c36da72020-11-20 09:40:12 +01003054 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09003055 /* bpo-31095: UnTrack is needed before calling any callbacks */
3056 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003057 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003058 SSL_CTX_free(self->ctx);
Christian Heimes39258d32021-04-17 11:36:35 +02003059 PyMem_FREE(self->alpn_protocols);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003060 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01003061 Py_DECREF(tp);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003062}
3063
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003064/*[clinic input]
3065_ssl._SSLContext.set_ciphers
3066 cipherlist: str
3067 /
3068[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003069
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003070static PyObject *
3071_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3072/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3073{
3074 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003075 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003076 /* Clearing the error queue is necessary on some OpenSSL versions,
3077 otherwise the error will be reported again when another SSL call
3078 is done. */
3079 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003080 PyErr_SetString(PySSLErrorObject,
3081 "No cipher can be selected.");
3082 return NULL;
3083 }
3084 Py_RETURN_NONE;
3085}
3086
Christian Heimes25bfcd52016-09-06 00:04:45 +02003087/*[clinic input]
3088_ssl._SSLContext.get_ciphers
3089[clinic start generated code]*/
3090
3091static PyObject *
3092_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3093/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3094{
3095 SSL *ssl = NULL;
3096 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003097 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003098 int i=0;
3099 PyObject *result = NULL, *dct;
3100
3101 ssl = SSL_new(self->ctx);
3102 if (ssl == NULL) {
3103 _setSSLError(NULL, 0, __FILE__, __LINE__);
3104 goto exit;
3105 }
3106 sk = SSL_get_ciphers(ssl);
3107
3108 result = PyList_New(sk_SSL_CIPHER_num(sk));
3109 if (result == NULL) {
3110 goto exit;
3111 }
3112
3113 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3114 cipher = sk_SSL_CIPHER_value(sk, i);
3115 dct = cipher_to_dict(cipher);
3116 if (dct == NULL) {
3117 Py_CLEAR(result);
3118 goto exit;
3119 }
3120 PyList_SET_ITEM(result, i, dct);
3121 }
3122
3123 exit:
3124 if (ssl != NULL)
3125 SSL_free(ssl);
3126 return result;
3127
3128}
Christian Heimes25bfcd52016-09-06 00:04:45 +02003129
3130
Benjamin Petersoncca27322015-01-23 16:35:37 -05003131static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003132do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3133 const unsigned char *server_protocols, unsigned int server_protocols_len,
3134 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003135{
Benjamin Peterson88615022015-01-23 17:30:26 -05003136 int ret;
3137 if (client_protocols == NULL) {
3138 client_protocols = (unsigned char *)"";
3139 client_protocols_len = 0;
3140 }
3141 if (server_protocols == NULL) {
3142 server_protocols = (unsigned char *)"";
3143 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003144 }
3145
Benjamin Peterson88615022015-01-23 17:30:26 -05003146 ret = SSL_select_next_proto(out, outlen,
3147 server_protocols, server_protocols_len,
3148 client_protocols, client_protocols_len);
3149 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3150 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003151
3152 return SSL_TLSEXT_ERR_OK;
3153}
3154
Benjamin Petersoncca27322015-01-23 16:35:37 -05003155static int
3156_selectALPN_cb(SSL *s,
3157 const unsigned char **out, unsigned char *outlen,
3158 const unsigned char *client_protocols, unsigned int client_protocols_len,
3159 void *args)
3160{
3161 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003162 return do_protocol_selection(1, (unsigned char **)out, outlen,
3163 ctx->alpn_protocols, ctx->alpn_protocols_len,
3164 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003165}
Benjamin Petersoncca27322015-01-23 16:35:37 -05003166
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003167/*[clinic input]
3168_ssl._SSLContext._set_alpn_protocols
3169 protos: Py_buffer
3170 /
3171[clinic start generated code]*/
3172
Benjamin Petersoncca27322015-01-23 16:35:37 -05003173static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003174_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3175 Py_buffer *protos)
3176/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003177{
Victor Stinner5a615592017-09-14 01:10:30 -07003178 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003179 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003180 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003181 return NULL;
3182 }
3183
Victor Stinner00d7abd2020-12-01 09:56:42 +01003184 PyMem_Free(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003185 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003186 if (!self->alpn_protocols)
3187 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003188 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003189 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003190
3191 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3192 return PyErr_NoMemory();
3193 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3194
Benjamin Petersoncca27322015-01-23 16:35:37 -05003195 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003196}
3197
Antoine Pitrou152efa22010-05-16 18:19:27 +00003198static PyObject *
3199get_verify_mode(PySSLContext *self, void *c)
3200{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003201 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3202 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3203 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3204 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003205 case SSL_VERIFY_NONE:
3206 return PyLong_FromLong(PY_SSL_CERT_NONE);
3207 case SSL_VERIFY_PEER:
3208 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3209 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3210 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3211 }
3212 PyErr_SetString(PySSLErrorObject,
3213 "invalid return value from SSL_CTX_get_verify_mode");
3214 return NULL;
3215}
3216
3217static int
3218set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3219{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003220 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003221 if (!PyArg_Parse(arg, "i", &n))
3222 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003223 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003224 PyErr_SetString(PyExc_ValueError,
3225 "Cannot set verify_mode to CERT_NONE when "
3226 "check_hostname is enabled.");
3227 return -1;
3228 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003229 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003230}
3231
3232static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003233get_verify_flags(PySSLContext *self, void *c)
3234{
Christian Heimes598894f2016-09-05 23:19:05 +02003235 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003236 unsigned long flags;
3237
Christian Heimes61d478c2018-01-27 15:51:38 +01003238 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003239 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003240 return PyLong_FromUnsignedLong(flags);
3241}
3242
3243static int
3244set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3245{
Christian Heimes598894f2016-09-05 23:19:05 +02003246 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003247 unsigned long new_flags, flags, set, clear;
3248
3249 if (!PyArg_Parse(arg, "k", &new_flags))
3250 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003251 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003252 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003253 clear = flags & ~new_flags;
3254 set = ~flags & new_flags;
3255 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003256 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003257 _setSSLError(NULL, 0, __FILE__, __LINE__);
3258 return -1;
3259 }
3260 }
3261 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003262 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003263 _setSSLError(NULL, 0, __FILE__, __LINE__);
3264 return -1;
3265 }
3266 }
3267 return 0;
3268}
3269
Christian Heimes698dde12018-02-27 11:54:43 +01003270/* Getter and setter for protocol version */
Christian Heimes698dde12018-02-27 11:54:43 +01003271static int
3272set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3273{
3274 long v;
3275 int result;
3276
3277 if (!PyArg_Parse(arg, "l", &v))
3278 return -1;
3279 if (v > INT_MAX) {
3280 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3281 return -1;
3282 }
3283
3284 switch(self->protocol) {
3285 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3286 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3287 case PY_SSL_VERSION_TLS:
3288 break;
3289 default:
3290 PyErr_SetString(
3291 PyExc_ValueError,
3292 "The context's protocol doesn't support modification of "
3293 "highest and lowest version."
3294 );
3295 return -1;
3296 }
3297
3298 if (what == 0) {
3299 switch(v) {
3300 case PY_PROTO_MINIMUM_SUPPORTED:
3301 v = 0;
3302 break;
3303 case PY_PROTO_MAXIMUM_SUPPORTED:
3304 /* Emulate max for set_min_proto_version */
3305 v = PY_PROTO_MAXIMUM_AVAILABLE;
3306 break;
3307 default:
3308 break;
3309 }
3310 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3311 }
3312 else {
3313 switch(v) {
3314 case PY_PROTO_MAXIMUM_SUPPORTED:
3315 v = 0;
3316 break;
3317 case PY_PROTO_MINIMUM_SUPPORTED:
3318 /* Emulate max for set_min_proto_version */
3319 v = PY_PROTO_MINIMUM_AVAILABLE;
3320 break;
3321 default:
3322 break;
3323 }
3324 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3325 }
3326 if (result == 0) {
3327 PyErr_Format(PyExc_ValueError,
3328 "Unsupported protocol version 0x%x", v);
3329 return -1;
3330 }
3331 return 0;
3332}
3333
3334static PyObject *
3335get_minimum_version(PySSLContext *self, void *c)
3336{
3337 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3338 if (v == 0) {
3339 v = PY_PROTO_MINIMUM_SUPPORTED;
3340 }
3341 return PyLong_FromLong(v);
3342}
3343
3344static int
3345set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3346{
3347 return set_min_max_proto_version(self, arg, 0);
3348}
3349
3350static PyObject *
3351get_maximum_version(PySSLContext *self, void *c)
3352{
3353 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3354 if (v == 0) {
3355 v = PY_PROTO_MAXIMUM_SUPPORTED;
3356 }
3357 return PyLong_FromLong(v);
3358}
3359
3360static int
3361set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3362{
3363 return set_min_max_proto_version(self, arg, 1);
3364}
Christian Heimes698dde12018-02-27 11:54:43 +01003365
Christian Heimes39258d32021-04-17 11:36:35 +02003366#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02003367static PyObject *
3368get_num_tickets(PySSLContext *self, void *c)
3369{
Victor Stinner76611c72019-07-09 13:30:52 +02003370 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003371}
3372
3373static int
3374set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3375{
3376 long num;
3377 if (!PyArg_Parse(arg, "l", &num))
3378 return -1;
3379 if (num < 0) {
3380 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3381 return -1;
3382 }
3383 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3384 PyErr_SetString(PyExc_ValueError,
3385 "SSLContext is not a server context.");
3386 return -1;
3387 }
3388 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3389 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3390 return -1;
3391 }
3392 return 0;
3393}
3394
3395PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3396"Control the number of TLSv1.3 session tickets");
Christian Heimes39258d32021-04-17 11:36:35 +02003397#endif /* TLS1_3_VERSION */
Christian Heimes78c7d522019-06-03 21:00:10 +02003398
matthewhughes9348e836bb2020-07-17 09:59:15 +01003399static PyObject *
3400get_security_level(PySSLContext *self, void *c)
3401{
3402 return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3403}
3404PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
matthewhughes9348e836bb2020-07-17 09:59:15 +01003405
Christian Heimes22587792013-11-21 23:56:13 +01003406static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003407get_options(PySSLContext *self, void *c)
3408{
3409 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3410}
3411
3412static int
3413set_options(PySSLContext *self, PyObject *arg, void *c)
3414{
3415 long new_opts, opts, set, clear;
3416 if (!PyArg_Parse(arg, "l", &new_opts))
3417 return -1;
3418 opts = SSL_CTX_get_options(self->ctx);
3419 clear = opts & ~new_opts;
3420 set = ~opts & new_opts;
3421 if (clear) {
Antoine Pitroub5218772010-05-21 09:56:06 +00003422 SSL_CTX_clear_options(self->ctx, clear);
Antoine Pitroub5218772010-05-21 09:56:06 +00003423 }
3424 if (set)
3425 SSL_CTX_set_options(self->ctx, set);
3426 return 0;
3427}
3428
Christian Heimes1aa9a752013-12-02 02:41:19 +01003429static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003430get_host_flags(PySSLContext *self, void *c)
3431{
3432 return PyLong_FromUnsignedLong(self->hostflags);
3433}
3434
3435static int
3436set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3437{
3438 X509_VERIFY_PARAM *param;
3439 unsigned int new_flags = 0;
3440
3441 if (!PyArg_Parse(arg, "I", &new_flags))
3442 return -1;
3443
3444 param = SSL_CTX_get0_param(self->ctx);
3445 self->hostflags = new_flags;
3446 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3447 return 0;
3448}
3449
3450static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003451get_check_hostname(PySSLContext *self, void *c)
3452{
3453 return PyBool_FromLong(self->check_hostname);
3454}
3455
3456static int
3457set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3458{
3459 int check_hostname;
3460 if (!PyArg_Parse(arg, "p", &check_hostname))
3461 return -1;
3462 if (check_hostname &&
3463 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003464 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003465 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003466 return -1;
3467 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003468 }
3469 self->check_hostname = check_hostname;
3470 return 0;
3471}
3472
Christian Heimes11a14932018-02-24 02:35:08 +01003473static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003474get_post_handshake_auth(PySSLContext *self, void *c) {
3475#if TLS1_3_VERSION
3476 return PyBool_FromLong(self->post_handshake_auth);
3477#else
3478 Py_RETURN_NONE;
3479#endif
3480}
3481
3482#if TLS1_3_VERSION
3483static int
3484set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003485 if (arg == NULL) {
3486 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3487 return -1;
3488 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003489 int pha = PyObject_IsTrue(arg);
3490
3491 if (pha == -1) {
3492 return -1;
3493 }
3494 self->post_handshake_auth = pha;
3495
Christian Heimesf0f59302019-07-01 08:29:17 +02003496 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3497 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003498
3499 return 0;
3500}
3501#endif
3502
3503static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003504get_protocol(PySSLContext *self, void *c) {
3505 return PyLong_FromLong(self->protocol);
3506}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003507
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003508typedef struct {
3509 PyThreadState *thread_state;
3510 PyObject *callable;
3511 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003512 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003513 int error;
3514} _PySSLPasswordInfo;
3515
3516static int
3517_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3518 const char *bad_type_error)
3519{
3520 /* Set the password and size fields of a _PySSLPasswordInfo struct
3521 from a unicode, bytes, or byte array object.
3522 The password field will be dynamically allocated and must be freed
3523 by the caller */
3524 PyObject *password_bytes = NULL;
3525 const char *data = NULL;
3526 Py_ssize_t size;
3527
3528 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003529 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003530 if (!password_bytes) {
3531 goto error;
3532 }
3533 data = PyBytes_AS_STRING(password_bytes);
3534 size = PyBytes_GET_SIZE(password_bytes);
3535 } else if (PyBytes_Check(password)) {
3536 data = PyBytes_AS_STRING(password);
3537 size = PyBytes_GET_SIZE(password);
3538 } else if (PyByteArray_Check(password)) {
3539 data = PyByteArray_AS_STRING(password);
3540 size = PyByteArray_GET_SIZE(password);
3541 } else {
3542 PyErr_SetString(PyExc_TypeError, bad_type_error);
3543 goto error;
3544 }
3545
Victor Stinner9ee02032013-06-23 15:08:23 +02003546 if (size > (Py_ssize_t)INT_MAX) {
3547 PyErr_Format(PyExc_ValueError,
3548 "password cannot be longer than %d bytes", INT_MAX);
3549 goto error;
3550 }
3551
Victor Stinner11ebff22013-07-07 17:07:52 +02003552 PyMem_Free(pw_info->password);
3553 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003554 if (!pw_info->password) {
3555 PyErr_SetString(PyExc_MemoryError,
3556 "unable to allocate password buffer");
3557 goto error;
3558 }
3559 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003560 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003561
3562 Py_XDECREF(password_bytes);
3563 return 1;
3564
3565error:
3566 Py_XDECREF(password_bytes);
3567 return 0;
3568}
3569
3570static int
3571_password_callback(char *buf, int size, int rwflag, void *userdata)
3572{
3573 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3574 PyObject *fn_ret = NULL;
3575
3576 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3577
Christian Heimesd3b73f32021-04-09 15:23:38 +02003578 if (pw_info->error) {
3579 /* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
3580 * callback multiple times which can lead to fatal Python error in
3581 * exception check. */
3582 goto error;
3583 }
3584
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003585 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003586 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003587 if (!fn_ret) {
3588 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3589 core python API, so we could use it to add a frame here */
3590 goto error;
3591 }
3592
3593 if (!_pwinfo_set(pw_info, fn_ret,
3594 "password callback must return a string")) {
3595 goto error;
3596 }
3597 Py_CLEAR(fn_ret);
3598 }
3599
3600 if (pw_info->size > size) {
3601 PyErr_Format(PyExc_ValueError,
3602 "password cannot be longer than %d bytes", size);
3603 goto error;
3604 }
3605
3606 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3607 memcpy(buf, pw_info->password, pw_info->size);
3608 return pw_info->size;
3609
3610error:
3611 Py_XDECREF(fn_ret);
3612 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3613 pw_info->error = 1;
3614 return -1;
3615}
3616
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003617/*[clinic input]
3618_ssl._SSLContext.load_cert_chain
3619 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003620 keyfile: object = None
3621 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003622
3623[clinic start generated code]*/
3624
Antoine Pitroub5218772010-05-21 09:56:06 +00003625static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003626_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3627 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003628/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003629{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003630 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003631 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3632 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003633 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003634 int r;
3635
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003636 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003637 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003638 if (keyfile == Py_None)
3639 keyfile = NULL;
3640 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003641 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3642 PyErr_SetString(PyExc_TypeError,
3643 "certfile should be a valid filesystem path");
3644 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003645 return NULL;
3646 }
3647 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003648 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3649 PyErr_SetString(PyExc_TypeError,
3650 "keyfile should be a valid filesystem path");
3651 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003652 goto error;
3653 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003654 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003655 if (PyCallable_Check(password)) {
3656 pw_info.callable = password;
3657 } else if (!_pwinfo_set(&pw_info, password,
3658 "password should be a string or callable")) {
3659 goto error;
3660 }
3661 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3662 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3663 }
3664 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003665 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3666 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003667 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003668 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003669 if (pw_info.error) {
3670 ERR_clear_error();
3671 /* the password callback has already set the error information */
3672 }
3673 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003674 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003675 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003676 }
3677 else {
3678 _setSSLError(NULL, 0, __FILE__, __LINE__);
3679 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003680 goto error;
3681 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003682 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003683 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003684 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3685 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003686 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3687 Py_CLEAR(keyfile_bytes);
3688 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003689 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003690 if (pw_info.error) {
3691 ERR_clear_error();
3692 /* the password callback has already set the error information */
3693 }
3694 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003695 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003696 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003697 }
3698 else {
3699 _setSSLError(NULL, 0, __FILE__, __LINE__);
3700 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003701 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003702 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003703 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003704 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003705 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003706 if (r != 1) {
3707 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003708 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003709 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003710 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3711 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003712 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003713 Py_RETURN_NONE;
3714
3715error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003716 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3717 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003718 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003719 Py_XDECREF(keyfile_bytes);
3720 Py_XDECREF(certfile_bytes);
3721 return NULL;
3722}
3723
Christian Heimesefff7062013-11-21 03:35:02 +01003724/* internal helper function, returns -1 on error
3725 */
3726static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03003727_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01003728 int filetype)
3729{
3730 BIO *biobuf = NULL;
3731 X509_STORE *store;
3732 int retval = 0, err, loaded = 0;
3733
3734 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3735
3736 if (len <= 0) {
3737 PyErr_SetString(PyExc_ValueError,
3738 "Empty certificate data");
3739 return -1;
3740 } else if (len > INT_MAX) {
3741 PyErr_SetString(PyExc_OverflowError,
3742 "Certificate data is too long.");
3743 return -1;
3744 }
3745
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003746 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003747 if (biobuf == NULL) {
3748 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3749 return -1;
3750 }
3751
3752 store = SSL_CTX_get_cert_store(self->ctx);
3753 assert(store != NULL);
3754
3755 while (1) {
3756 X509 *cert = NULL;
3757 int r;
3758
3759 if (filetype == SSL_FILETYPE_ASN1) {
3760 cert = d2i_X509_bio(biobuf, NULL);
3761 } else {
3762 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003763 SSL_CTX_get_default_passwd_cb(self->ctx),
3764 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3765 );
Christian Heimesefff7062013-11-21 03:35:02 +01003766 }
3767 if (cert == NULL) {
3768 break;
3769 }
3770 r = X509_STORE_add_cert(store, cert);
3771 X509_free(cert);
3772 if (!r) {
3773 err = ERR_peek_last_error();
3774 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3775 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3776 /* cert already in hash table, not an error */
3777 ERR_clear_error();
3778 } else {
3779 break;
3780 }
3781 }
3782 loaded++;
3783 }
3784
3785 err = ERR_peek_last_error();
3786 if ((filetype == SSL_FILETYPE_ASN1) &&
3787 (loaded > 0) &&
3788 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3789 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3790 /* EOF ASN1 file, not an error */
3791 ERR_clear_error();
3792 retval = 0;
3793 } else if ((filetype == SSL_FILETYPE_PEM) &&
3794 (loaded > 0) &&
3795 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3796 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3797 /* EOF PEM file, not an error */
3798 ERR_clear_error();
3799 retval = 0;
3800 } else {
3801 _setSSLError(NULL, 0, __FILE__, __LINE__);
3802 retval = -1;
3803 }
3804
3805 BIO_free(biobuf);
3806 return retval;
3807}
3808
3809
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003810/*[clinic input]
3811_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003812 cafile: object = None
3813 capath: object = None
3814 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003815
3816[clinic start generated code]*/
3817
Antoine Pitrou152efa22010-05-16 18:19:27 +00003818static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003819_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3820 PyObject *cafile,
3821 PyObject *capath,
3822 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003823/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003824{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003825 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3826 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003827 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003828
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003829 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003830 if (cafile == Py_None)
3831 cafile = NULL;
3832 if (capath == Py_None)
3833 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003834 if (cadata == Py_None)
3835 cadata = NULL;
3836
3837 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003838 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003839 "cafile, capath and cadata cannot be all omitted");
3840 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003841 }
3842 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003843 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3844 PyErr_SetString(PyExc_TypeError,
3845 "cafile should be a valid filesystem path");
3846 }
Christian Heimesefff7062013-11-21 03:35:02 +01003847 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003848 }
3849 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003850 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3851 PyErr_SetString(PyExc_TypeError,
3852 "capath should be a valid filesystem path");
3853 }
Christian Heimesefff7062013-11-21 03:35:02 +01003854 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003855 }
Christian Heimesefff7062013-11-21 03:35:02 +01003856
3857 /* validata cadata type and load cadata */
3858 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003859 if (PyUnicode_Check(cadata)) {
3860 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
3861 if (cadata_ascii == NULL) {
3862 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
3863 goto invalid_cadata;
3864 }
3865 goto error;
3866 }
3867 r = _add_ca_certs(self,
3868 PyBytes_AS_STRING(cadata_ascii),
3869 PyBytes_GET_SIZE(cadata_ascii),
3870 SSL_FILETYPE_PEM);
3871 Py_DECREF(cadata_ascii);
3872 if (r == -1) {
3873 goto error;
3874 }
3875 }
3876 else if (PyObject_CheckBuffer(cadata)) {
3877 Py_buffer buf;
3878 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
3879 goto error;
3880 }
Christian Heimesefff7062013-11-21 03:35:02 +01003881 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3882 PyBuffer_Release(&buf);
3883 PyErr_SetString(PyExc_TypeError,
3884 "cadata should be a contiguous buffer with "
3885 "a single dimension");
3886 goto error;
3887 }
3888 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3889 PyBuffer_Release(&buf);
3890 if (r == -1) {
3891 goto error;
3892 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003893 }
3894 else {
3895 invalid_cadata:
3896 PyErr_SetString(PyExc_TypeError,
3897 "cadata should be an ASCII string or a "
3898 "bytes-like object");
3899 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01003900 }
3901 }
3902
3903 /* load cafile or capath */
3904 if (cafile || capath) {
3905 if (cafile)
3906 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3907 if (capath)
3908 capath_buf = PyBytes_AS_STRING(capath_bytes);
3909 PySSL_BEGIN_ALLOW_THREADS
3910 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3911 PySSL_END_ALLOW_THREADS
3912 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01003913 if (errno != 0) {
3914 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003915 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003916 }
3917 else {
3918 _setSSLError(NULL, 0, __FILE__, __LINE__);
3919 }
3920 goto error;
3921 }
3922 }
3923 goto end;
3924
3925 error:
3926 ok = 0;
3927 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003928 Py_XDECREF(cafile_bytes);
3929 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003930 if (ok) {
3931 Py_RETURN_NONE;
3932 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003933 return NULL;
3934 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003935}
3936
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003937/*[clinic input]
3938_ssl._SSLContext.load_dh_params
3939 path as filepath: object
3940 /
3941
3942[clinic start generated code]*/
3943
Antoine Pitrou152efa22010-05-16 18:19:27 +00003944static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003945_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3946/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003947{
3948 FILE *f;
3949 DH *dh;
3950
Victor Stinnerdaf45552013-08-28 00:53:59 +02003951 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003952 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003953 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003954
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003955 errno = 0;
3956 PySSL_BEGIN_ALLOW_THREADS
3957 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003958 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003959 PySSL_END_ALLOW_THREADS
3960 if (dh == NULL) {
3961 if (errno != 0) {
3962 ERR_clear_error();
3963 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3964 }
3965 else {
3966 _setSSLError(NULL, 0, __FILE__, __LINE__);
3967 }
3968 return NULL;
3969 }
Zackery Spytzaebc0492020-07-07 22:21:58 -06003970 if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
3971 DH_free(dh);
3972 return _setSSLError(NULL, 0, __FILE__, __LINE__);
3973 }
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003974 DH_free(dh);
3975 Py_RETURN_NONE;
3976}
3977
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003978/*[clinic input]
3979_ssl._SSLContext._wrap_socket
3980 sock: object(subclass_of="PySocketModule.Sock_Type")
3981 server_side: int
3982 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01003983 *
3984 owner: object = None
3985 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003986
3987[clinic start generated code]*/
3988
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003989static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003990_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01003991 int server_side, PyObject *hostname_obj,
3992 PyObject *owner, PyObject *session)
3993/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003994{
Antoine Pitroud5323212010-10-22 18:19:07 +00003995 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003996 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003997
Antoine Pitroud5323212010-10-22 18:19:07 +00003998 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02003999 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004000 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004001 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004002 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004003 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004004
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004005 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4006 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004007 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004008 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004009 if (hostname != NULL)
4010 PyMem_Free(hostname);
4011 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004012}
4013
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004014/*[clinic input]
4015_ssl._SSLContext._wrap_bio
Christian Heimes5c36da72020-11-20 09:40:12 +01004016 incoming: object(subclass_of="PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4017 outgoing: object(subclass_of="PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004018 server_side: int
4019 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004020 *
4021 owner: object = None
4022 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004023
4024[clinic start generated code]*/
4025
Antoine Pitroub0182c82010-10-12 20:09:02 +00004026static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004027_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4028 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004029 PyObject *hostname_obj, PyObject *owner,
4030 PyObject *session)
Christian Heimes5c36da72020-11-20 09:40:12 +01004031/*[clinic end generated code: output=5c5d6d9b41f99332 input=63867b8f3e1a1aa3]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004032{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004033 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004034 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004035
4036 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004037 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004038 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004039 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004040 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004041 }
4042
4043 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004044 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004045 incoming, outgoing);
4046
4047 PyMem_Free(hostname);
4048 return res;
4049}
4050
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004051/*[clinic input]
4052_ssl._SSLContext.session_stats
4053[clinic start generated code]*/
4054
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004055static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004056_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4057/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004058{
4059 int r;
4060 PyObject *value, *stats = PyDict_New();
4061 if (!stats)
4062 return NULL;
4063
4064#define ADD_STATS(SSL_NAME, KEY_NAME) \
4065 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4066 if (value == NULL) \
4067 goto error; \
4068 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4069 Py_DECREF(value); \
4070 if (r < 0) \
4071 goto error;
4072
4073 ADD_STATS(number, "number");
4074 ADD_STATS(connect, "connect");
4075 ADD_STATS(connect_good, "connect_good");
4076 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4077 ADD_STATS(accept, "accept");
4078 ADD_STATS(accept_good, "accept_good");
4079 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4080 ADD_STATS(accept, "accept");
4081 ADD_STATS(hits, "hits");
4082 ADD_STATS(misses, "misses");
4083 ADD_STATS(timeouts, "timeouts");
4084 ADD_STATS(cache_full, "cache_full");
4085
4086#undef ADD_STATS
4087
4088 return stats;
4089
4090error:
4091 Py_DECREF(stats);
4092 return NULL;
4093}
4094
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004095/*[clinic input]
4096_ssl._SSLContext.set_default_verify_paths
4097[clinic start generated code]*/
4098
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004099static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004100_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4101/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004102{
4103 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4104 _setSSLError(NULL, 0, __FILE__, __LINE__);
4105 return NULL;
4106 }
4107 Py_RETURN_NONE;
4108}
4109
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004110/*[clinic input]
4111_ssl._SSLContext.set_ecdh_curve
4112 name: object
4113 /
4114
4115[clinic start generated code]*/
4116
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004117static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004118_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4119/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004120{
4121 PyObject *name_bytes;
4122 int nid;
4123 EC_KEY *key;
4124
4125 if (!PyUnicode_FSConverter(name, &name_bytes))
4126 return NULL;
4127 assert(PyBytes_Check(name_bytes));
4128 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4129 Py_DECREF(name_bytes);
4130 if (nid == 0) {
4131 PyErr_Format(PyExc_ValueError,
4132 "unknown elliptic curve name %R", name);
4133 return NULL;
4134 }
4135 key = EC_KEY_new_by_curve_name(nid);
4136 if (key == NULL) {
4137 _setSSLError(NULL, 0, __FILE__, __LINE__);
4138 return NULL;
4139 }
4140 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4141 EC_KEY_free(key);
4142 Py_RETURN_NONE;
4143}
4144
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004145static int
4146_servername_callback(SSL *s, int *al, void *args)
4147{
4148 int ret;
4149 PySSLContext *ssl_ctx = (PySSLContext *) args;
4150 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004151 PyObject *result;
4152 /* The high-level ssl.SSLSocket object */
4153 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004154 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004155 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004156
Christian Heimes11a14932018-02-24 02:35:08 +01004157 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004158 /* remove race condition in this the call back while if removing the
4159 * callback is in progress */
4160 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004161 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004162 }
4163
4164 ssl = SSL_get_app_data(s);
4165 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004166
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004167 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004168 * SSL connection and that has a .context attribute that can be changed to
4169 * identify the requested hostname. Since the official API is the Python
4170 * level API we want to pass the callback a Python level object rather than
4171 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4172 * SSLObject) that will be passed. Otherwise if there's a socket then that
4173 * will be passed. If both do not exist only then the C-level object is
4174 * passed. */
4175 if (ssl->owner)
4176 ssl_socket = PyWeakref_GetObject(ssl->owner);
4177 else if (ssl->Socket)
4178 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4179 else
4180 ssl_socket = (PyObject *) ssl;
4181
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004182 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004183 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004184 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004185
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004186 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004187 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004188 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004189 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004190 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004191 PyObject *servername_bytes;
4192 PyObject *servername_str;
4193
4194 servername_bytes = PyBytes_FromString(servername);
4195 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004196 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4197 goto error;
4198 }
Christian Heimes11a14932018-02-24 02:35:08 +01004199 /* server_hostname was encoded to an A-label by our caller; put it
4200 * back into a str object, but still as an A-label (bpo-28414)
4201 */
4202 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
Christian Heimes11a14932018-02-24 02:35:08 +01004203 if (servername_str == NULL) {
4204 PyErr_WriteUnraisable(servername_bytes);
Zackery Spytzee96f322020-07-09 04:00:21 -06004205 Py_DECREF(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004206 goto error;
4207 }
Zackery Spytzee96f322020-07-09 04:00:21 -06004208 Py_DECREF(servername_bytes);
Christian Heimes11a14932018-02-24 02:35:08 +01004209 result = PyObject_CallFunctionObjArgs(
4210 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4211 ssl_ctx, NULL);
4212 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004213 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004214 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004215
4216 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004217 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004218 *al = SSL_AD_HANDSHAKE_FAILURE;
4219 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4220 }
4221 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004222 /* Result may be None, a SSLContext or an integer
4223 * None and SSLContext are OK, integer or other values are an error.
4224 */
4225 if (result == Py_None) {
4226 ret = SSL_TLSEXT_ERR_OK;
4227 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004228 *al = (int) PyLong_AsLong(result);
4229 if (PyErr_Occurred()) {
4230 PyErr_WriteUnraisable(result);
4231 *al = SSL_AD_INTERNAL_ERROR;
4232 }
4233 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4234 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004235 Py_DECREF(result);
4236 }
4237
4238 PyGILState_Release(gstate);
4239 return ret;
4240
4241error:
4242 Py_DECREF(ssl_socket);
4243 *al = SSL_AD_INTERNAL_ERROR;
4244 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4245 PyGILState_Release(gstate);
4246 return ret;
4247}
4248
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004249static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004250get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004251{
Christian Heimes11a14932018-02-24 02:35:08 +01004252 PyObject *cb = self->set_sni_cb;
4253 if (cb == NULL) {
4254 Py_RETURN_NONE;
4255 }
4256 Py_INCREF(cb);
4257 return cb;
4258}
4259
4260static int
4261set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4262{
4263 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4264 PyErr_SetString(PyExc_ValueError,
4265 "sni_callback cannot be set on TLS_CLIENT context");
4266 return -1;
4267 }
Christian Heimes11a14932018-02-24 02:35:08 +01004268 Py_CLEAR(self->set_sni_cb);
4269 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004270 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4271 }
4272 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004273 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004274 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4275 PyErr_SetString(PyExc_TypeError,
4276 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004277 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004278 }
Christian Heimes11a14932018-02-24 02:35:08 +01004279 Py_INCREF(arg);
4280 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004281 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4282 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4283 }
Christian Heimes11a14932018-02-24 02:35:08 +01004284 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004285}
4286
Christian Heimes11a14932018-02-24 02:35:08 +01004287PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4288"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4289\n\
4290If the argument is None then the callback is disabled. The method is called\n\
4291with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4292See RFC 6066 for details of the SNI extension.");
4293
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004294/*[clinic input]
4295_ssl._SSLContext.cert_store_stats
4296
4297Returns quantities of loaded X.509 certificates.
4298
4299X.509 certificates with a CA extension and certificate revocation lists
4300inside the context's cert store.
4301
4302NOTE: Certificates in a capath directory aren't loaded unless they have
4303been used at least once.
4304[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004305
4306static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004307_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4308/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004309{
4310 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004311 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004312 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004313 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004314
4315 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004316 objs = X509_STORE_get0_objects(store);
4317 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4318 obj = sk_X509_OBJECT_value(objs, i);
4319 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004320 case X509_LU_X509:
4321 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004322 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004323 ca++;
4324 }
4325 break;
4326 case X509_LU_CRL:
4327 crl++;
4328 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004329 default:
4330 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4331 * As far as I can tell they are internal states and never
4332 * stored in a cert store */
4333 break;
4334 }
4335 }
4336 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4337 "x509_ca", ca);
4338}
4339
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004340/*[clinic input]
4341_ssl._SSLContext.get_ca_certs
4342 binary_form: bool = False
4343
4344Returns a list of dicts with information of loaded CA certs.
4345
4346If the optional argument is True, returns a DER-encoded copy of the CA
4347certificate.
4348
4349NOTE: Certificates in a capath directory aren't loaded unless they have
4350been used at least once.
4351[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004352
4353static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004354_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4355/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004356{
4357 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004358 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004359 PyObject *ci = NULL, *rlist = NULL;
4360 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004361
4362 if ((rlist = PyList_New(0)) == NULL) {
4363 return NULL;
4364 }
4365
4366 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004367 objs = X509_STORE_get0_objects(store);
4368 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004369 X509_OBJECT *obj;
4370 X509 *cert;
4371
Christian Heimes598894f2016-09-05 23:19:05 +02004372 obj = sk_X509_OBJECT_value(objs, i);
4373 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004374 /* not a x509 cert */
4375 continue;
4376 }
4377 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004378 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004379 if (!X509_check_ca(cert)) {
4380 continue;
4381 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004382 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004383 ci = _certificate_to_der(cert);
4384 } else {
4385 ci = _decode_certificate(cert);
4386 }
4387 if (ci == NULL) {
4388 goto error;
4389 }
4390 if (PyList_Append(rlist, ci) == -1) {
4391 goto error;
4392 }
4393 Py_CLEAR(ci);
4394 }
4395 return rlist;
4396
4397 error:
4398 Py_XDECREF(ci);
4399 Py_XDECREF(rlist);
4400 return NULL;
4401}
4402
4403
Antoine Pitrou152efa22010-05-16 18:19:27 +00004404static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004405 {"check_hostname", (getter) get_check_hostname,
4406 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004407 {"_host_flags", (getter) get_host_flags,
4408 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004409 {"minimum_version", (getter) get_minimum_version,
4410 (setter) set_minimum_version, NULL},
4411 {"maximum_version", (getter) get_maximum_version,
4412 (setter) set_maximum_version, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004413 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4414 (setter) _PySSLContext_set_keylog_filename, NULL},
Christian Heimesc7f70692019-05-31 11:44:05 +02004415 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4416 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004417 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004418 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes39258d32021-04-17 11:36:35 +02004419#ifdef TLS1_3_VERSION
Christian Heimes78c7d522019-06-03 21:00:10 +02004420 {"num_tickets", (getter) get_num_tickets,
4421 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4422#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004423 {"options", (getter) get_options,
4424 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004425 {"post_handshake_auth", (getter) get_post_handshake_auth,
4426#ifdef TLS1_3_VERSION
4427 (setter) set_post_handshake_auth,
4428#else
4429 NULL,
4430#endif
4431 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004432 {"protocol", (getter) get_protocol,
4433 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004434 {"verify_flags", (getter) get_verify_flags,
4435 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004436 {"verify_mode", (getter) get_verify_mode,
4437 (setter) set_verify_mode, NULL},
matthewhughes9348e836bb2020-07-17 09:59:15 +01004438 {"security_level", (getter) get_security_level,
4439 NULL, PySSLContext_security_level_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004440 {NULL}, /* sentinel */
4441};
4442
4443static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004444 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4445 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4446 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4447 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004448 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4449 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4450 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4451 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4452 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4453 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004454 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4455 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004456 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004457 {NULL, NULL} /* sentinel */
4458};
4459
Christian Heimes5c36da72020-11-20 09:40:12 +01004460static PyType_Slot PySSLContext_slots[] = {
4461 {Py_tp_methods, context_methods},
4462 {Py_tp_getset, context_getsetlist},
4463 {Py_tp_new, _ssl__SSLContext},
4464 {Py_tp_dealloc, context_dealloc},
4465 {Py_tp_traverse, context_traverse},
4466 {Py_tp_clear, context_clear},
4467 {0, 0},
4468};
4469
4470static PyType_Spec PySSLContext_spec = {
4471 "_ssl._SSLContext",
4472 sizeof(PySSLContext),
4473 0,
4474 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
4475 PySSLContext_slots,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004476};
4477
4478
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004479/*
4480 * MemoryBIO objects
4481 */
4482
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004483/*[clinic input]
4484@classmethod
4485_ssl.MemoryBIO.__new__
4486
4487[clinic start generated code]*/
4488
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004489static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004490_ssl_MemoryBIO_impl(PyTypeObject *type)
4491/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004492{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004493 BIO *bio;
4494 PySSLMemoryBIO *self;
4495
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004496 bio = BIO_new(BIO_s_mem());
4497 if (bio == NULL) {
4498 PyErr_SetString(PySSLErrorObject,
4499 "failed to allocate BIO");
4500 return NULL;
4501 }
4502 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4503 * just that no data is currently available. The SSL routines should retry
4504 * the read, which we can achieve by calling BIO_set_retry_read(). */
4505 BIO_set_retry_read(bio);
4506 BIO_set_mem_eof_return(bio, -1);
4507
4508 assert(type != NULL && type->tp_alloc != NULL);
4509 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4510 if (self == NULL) {
4511 BIO_free(bio);
4512 return NULL;
4513 }
4514 self->bio = bio;
4515 self->eof_written = 0;
4516
4517 return (PyObject *) self;
4518}
4519
4520static void
4521memory_bio_dealloc(PySSLMemoryBIO *self)
4522{
Christian Heimes5c36da72020-11-20 09:40:12 +01004523 PyTypeObject *tp = Py_TYPE(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004524 BIO_free(self->bio);
4525 Py_TYPE(self)->tp_free(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004526 Py_DECREF(tp);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004527}
4528
4529static PyObject *
4530memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4531{
Segev Finer5cff6372017-07-27 01:19:17 +03004532 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004533}
4534
4535PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4536"The number of bytes pending in the memory BIO.");
4537
4538static PyObject *
4539memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4540{
4541 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4542 && self->eof_written);
4543}
4544
4545PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4546"Whether the memory BIO is at EOF.");
4547
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004548/*[clinic input]
4549_ssl.MemoryBIO.read
4550 size as len: int = -1
4551 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004552
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004553Read up to size bytes from the memory BIO.
4554
4555If size is not specified, read the entire buffer.
4556If the return value is an empty bytes instance, this means either
4557EOF or that no data is available. Use the "eof" property to
4558distinguish between the two.
4559[clinic start generated code]*/
4560
4561static PyObject *
4562_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4563/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4564{
4565 int avail, nbytes;
4566 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004567
Segev Finer5cff6372017-07-27 01:19:17 +03004568 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004569 if ((len < 0) || (len > avail))
4570 len = avail;
4571
4572 result = PyBytes_FromStringAndSize(NULL, len);
4573 if ((result == NULL) || (len == 0))
4574 return result;
4575
4576 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004577 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004578 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004579 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004580 return NULL;
4581 }
4582
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004583 /* There should never be any short reads but check anyway. */
4584 if (nbytes < len) {
4585 _PyBytes_Resize(&result, nbytes);
4586 }
4587
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004588 return result;
4589}
4590
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004591/*[clinic input]
4592_ssl.MemoryBIO.write
4593 b: Py_buffer
4594 /
4595
4596Writes the bytes b into the memory BIO.
4597
4598Returns the number of bytes written.
4599[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004600
4601static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004602_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4603/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004604{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004605 int nbytes;
4606
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004607 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004608 PyErr_Format(PyExc_OverflowError,
4609 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004610 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004611 }
4612
4613 if (self->eof_written) {
4614 PyErr_SetString(PySSLErrorObject,
4615 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004616 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004617 }
4618
Segev Finer5cff6372017-07-27 01:19:17 +03004619 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004620 if (nbytes < 0) {
4621 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004622 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004623 }
4624
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004625 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004626}
4627
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004628/*[clinic input]
4629_ssl.MemoryBIO.write_eof
4630
4631Write an EOF marker to the memory BIO.
4632
4633When all data has been read, the "eof" property will be True.
4634[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004635
4636static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004637_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4638/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004639{
4640 self->eof_written = 1;
4641 /* After an EOF is written, a zero return from read() should be a real EOF
4642 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4643 BIO_clear_retry_flags(self->bio);
4644 BIO_set_mem_eof_return(self->bio, 0);
4645
4646 Py_RETURN_NONE;
4647}
4648
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004649static PyGetSetDef memory_bio_getsetlist[] = {
4650 {"pending", (getter) memory_bio_get_pending, NULL,
4651 PySSL_memory_bio_pending_doc},
4652 {"eof", (getter) memory_bio_get_eof, NULL,
4653 PySSL_memory_bio_eof_doc},
4654 {NULL}, /* sentinel */
4655};
4656
4657static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004658 _SSL_MEMORYBIO_READ_METHODDEF
4659 _SSL_MEMORYBIO_WRITE_METHODDEF
4660 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004661 {NULL, NULL} /* sentinel */
4662};
4663
Christian Heimes5c36da72020-11-20 09:40:12 +01004664static PyType_Slot PySSLMemoryBIO_slots[] = {
4665 {Py_tp_methods, memory_bio_methods},
4666 {Py_tp_getset, memory_bio_getsetlist},
4667 {Py_tp_new, _ssl_MemoryBIO},
4668 {Py_tp_dealloc, memory_bio_dealloc},
4669 {0, 0},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004670};
4671
Christian Heimes5c36da72020-11-20 09:40:12 +01004672static PyType_Spec PySSLMemoryBIO_spec = {
4673 "_ssl.MemoryBIO",
4674 sizeof(PySSLMemoryBIO),
4675 0,
4676 Py_TPFLAGS_DEFAULT,
4677 PySSLMemoryBIO_slots,
4678};
Antoine Pitrou152efa22010-05-16 18:19:27 +00004679
Christian Heimes99a65702016-09-10 23:44:53 +02004680/*
4681 * SSL Session object
4682 */
4683
4684static void
4685PySSLSession_dealloc(PySSLSession *self)
4686{
Christian Heimes5c36da72020-11-20 09:40:12 +01004687 PyTypeObject *tp = Py_TYPE(self);
INADA Naokia6296d32017-08-24 14:55:17 +09004688 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004689 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004690 Py_XDECREF(self->ctx);
4691 if (self->session != NULL) {
4692 SSL_SESSION_free(self->session);
4693 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004694 PyObject_GC_Del(self);
Christian Heimes5c36da72020-11-20 09:40:12 +01004695 Py_DECREF(tp);
Christian Heimes99a65702016-09-10 23:44:53 +02004696}
4697
4698static PyObject *
4699PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4700{
4701 int result;
4702
4703 if (left == NULL || right == NULL) {
4704 PyErr_BadInternalCall();
4705 return NULL;
4706 }
4707
4708 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4709 Py_RETURN_NOTIMPLEMENTED;
4710 }
4711
4712 if (left == right) {
4713 result = 0;
4714 } else {
4715 const unsigned char *left_id, *right_id;
4716 unsigned int left_len, right_len;
4717 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4718 &left_len);
4719 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4720 &right_len);
4721 if (left_len == right_len) {
4722 result = memcmp(left_id, right_id, left_len);
4723 } else {
4724 result = 1;
4725 }
4726 }
4727
4728 switch (op) {
4729 case Py_EQ:
4730 if (result == 0) {
4731 Py_RETURN_TRUE;
4732 } else {
4733 Py_RETURN_FALSE;
4734 }
4735 break;
4736 case Py_NE:
4737 if (result != 0) {
4738 Py_RETURN_TRUE;
4739 } else {
4740 Py_RETURN_FALSE;
4741 }
4742 break;
4743 case Py_LT:
4744 case Py_LE:
4745 case Py_GT:
4746 case Py_GE:
4747 Py_RETURN_NOTIMPLEMENTED;
4748 break;
4749 default:
4750 PyErr_BadArgument();
4751 return NULL;
4752 }
4753}
4754
4755static int
4756PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4757{
4758 Py_VISIT(self->ctx);
4759 return 0;
4760}
4761
4762static int
4763PySSLSession_clear(PySSLSession *self)
4764{
4765 Py_CLEAR(self->ctx);
4766 return 0;
4767}
4768
4769
4770static PyObject *
4771PySSLSession_get_time(PySSLSession *self, void *closure) {
4772 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4773}
4774
4775PyDoc_STRVAR(PySSLSession_get_time_doc,
4776"Session creation time (seconds since epoch).");
4777
4778
4779static PyObject *
4780PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4781 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4782}
4783
4784PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4785"Session timeout (delta in seconds).");
4786
4787
4788static PyObject *
4789PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4790 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4791 return PyLong_FromUnsignedLong(hint);
4792}
4793
4794PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4795"Ticket life time hint.");
4796
4797
4798static PyObject *
4799PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4800 const unsigned char *id;
4801 unsigned int len;
4802 id = SSL_SESSION_get_id(self->session, &len);
4803 return PyBytes_FromStringAndSize((const char *)id, len);
4804}
4805
4806PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4807"Session id");
4808
4809
4810static PyObject *
4811PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4812 if (SSL_SESSION_has_ticket(self->session)) {
4813 Py_RETURN_TRUE;
4814 } else {
4815 Py_RETURN_FALSE;
4816 }
4817}
4818
4819PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4820"Does the session contain a ticket?");
4821
4822
4823static PyGetSetDef PySSLSession_getsetlist[] = {
4824 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4825 PySSLSession_get_has_ticket_doc},
4826 {"id", (getter) PySSLSession_get_session_id, NULL,
4827 PySSLSession_get_session_id_doc},
4828 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4829 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4830 {"time", (getter) PySSLSession_get_time, NULL,
4831 PySSLSession_get_time_doc},
4832 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4833 PySSLSession_get_timeout_doc},
4834 {NULL}, /* sentinel */
4835};
4836
Christian Heimes5c36da72020-11-20 09:40:12 +01004837static PyType_Slot PySSLSession_slots[] = {
4838 {Py_tp_getset,PySSLSession_getsetlist},
4839 {Py_tp_richcompare, PySSLSession_richcompare},
4840 {Py_tp_dealloc, PySSLSession_dealloc},
4841 {Py_tp_traverse, PySSLSession_traverse},
4842 {Py_tp_clear, PySSLSession_clear},
4843 {0, 0},
4844};
4845
4846static PyType_Spec PySSLSession_spec = {
4847 "_ssl.SSLSession",
4848 sizeof(PySSLSession),
4849 0,
4850 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
4851 PySSLSession_slots,
Christian Heimes99a65702016-09-10 23:44:53 +02004852};
4853
4854
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004855/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004856/*[clinic input]
4857_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004858 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004859 entropy: double
4860 /
4861
4862Mix string into the OpenSSL PRNG state.
4863
4864entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304865string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004866[clinic start generated code]*/
4867
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004868static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004869_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004870/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004871{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004872 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004873 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004874
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004875 buf = (const char *)view->buf;
4876 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004877 do {
4878 written = Py_MIN(len, INT_MAX);
4879 RAND_add(buf, (int)written, entropy);
4880 buf += written;
4881 len -= written;
4882 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004883 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004884}
4885
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004886static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004887PySSL_RAND(int len, int pseudo)
4888{
4889 int ok;
4890 PyObject *bytes;
4891 unsigned long err;
4892 const char *errstr;
4893 PyObject *v;
4894
Victor Stinner1e81a392013-12-19 16:47:04 +01004895 if (len < 0) {
4896 PyErr_SetString(PyExc_ValueError, "num must be positive");
4897 return NULL;
4898 }
4899
Victor Stinner99c8b162011-05-24 12:05:19 +02004900 bytes = PyBytes_FromStringAndSize(NULL, len);
4901 if (bytes == NULL)
4902 return NULL;
4903 if (pseudo) {
Christian Heimesa871f692020-06-01 08:58:14 +02004904 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
Victor Stinner99c8b162011-05-24 12:05:19 +02004905 if (ok == 0 || ok == 1)
4906 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4907 }
4908 else {
4909 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4910 if (ok == 1)
4911 return bytes;
4912 }
4913 Py_DECREF(bytes);
4914
4915 err = ERR_get_error();
4916 errstr = ERR_reason_error_string(err);
4917 v = Py_BuildValue("(ks)", err, errstr);
4918 if (v != NULL) {
4919 PyErr_SetObject(PySSLErrorObject, v);
4920 Py_DECREF(v);
4921 }
4922 return NULL;
4923}
4924
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004925/*[clinic input]
4926_ssl.RAND_bytes
4927 n: int
4928 /
4929
4930Generate n cryptographically strong pseudo-random bytes.
4931[clinic start generated code]*/
4932
Victor Stinner99c8b162011-05-24 12:05:19 +02004933static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004934_ssl_RAND_bytes_impl(PyObject *module, int n)
4935/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004936{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004937 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004938}
4939
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004940/*[clinic input]
4941_ssl.RAND_pseudo_bytes
4942 n: int
4943 /
4944
4945Generate n pseudo-random bytes.
4946
4947Return a pair (bytes, is_cryptographic). is_cryptographic is True
4948if the bytes generated are cryptographically strong.
4949[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004950
4951static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004952_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4953/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004954{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004955 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004956}
4957
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004958/*[clinic input]
4959_ssl.RAND_status
4960
4961Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4962
4963It is necessary to seed the PRNG with RAND_add() on some platforms before
4964using the ssl() function.
4965[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004966
4967static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004968_ssl_RAND_status_impl(PyObject *module)
4969/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004970{
Christian Heimes217cfd12007-12-02 14:31:20 +00004971 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004972}
4973
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004974#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004975/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004976/*[clinic input]
4977_ssl.RAND_egd
4978 path: object(converter="PyUnicode_FSConverter")
4979 /
4980
4981Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4982
4983Returns number of bytes read. Raises SSLError if connection to EGD
4984fails or if it does not provide enough data to seed PRNG.
4985[clinic start generated code]*/
4986
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004987static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004988_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4989/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004990{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004991 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004992 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004993 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004994 PyErr_SetString(PySSLErrorObject,
4995 "EGD connection failed or EGD did not return "
4996 "enough data to seed the PRNG");
4997 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004998 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004999 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005000}
Christian Heimesa5d07652016-09-24 10:48:05 +02005001/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005002#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005003
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005004
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005005
5006/*[clinic input]
5007_ssl.get_default_verify_paths
5008
5009Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5010
5011The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5012[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005013
5014static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005015_ssl_get_default_verify_paths_impl(PyObject *module)
5016/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005017{
5018 PyObject *ofile_env = NULL;
5019 PyObject *ofile = NULL;
5020 PyObject *odir_env = NULL;
5021 PyObject *odir = NULL;
5022
Benjamin Petersond113c962015-07-18 10:59:13 -07005023#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005024 const char *tmp = (info); \
5025 target = NULL; \
5026 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5027 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5028 target = PyBytes_FromString(tmp); } \
5029 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005030 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005031
Benjamin Petersond113c962015-07-18 10:59:13 -07005032 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5033 CONVERT(X509_get_default_cert_file(), ofile);
5034 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5035 CONVERT(X509_get_default_cert_dir(), odir);
5036#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005037
Christian Heimes200bb1b2013-06-14 15:14:29 +02005038 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005039
5040 error:
5041 Py_XDECREF(ofile_env);
5042 Py_XDECREF(ofile);
5043 Py_XDECREF(odir_env);
5044 Py_XDECREF(odir);
5045 return NULL;
5046}
5047
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005048static PyObject*
5049asn1obj2py(ASN1_OBJECT *obj)
5050{
5051 int nid;
5052 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005053
5054 nid = OBJ_obj2nid(obj);
5055 if (nid == NID_undef) {
5056 PyErr_Format(PyExc_ValueError, "Unknown object");
5057 return NULL;
5058 }
5059 sn = OBJ_nid2sn(nid);
5060 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005061 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005062}
5063
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005064/*[clinic input]
5065_ssl.txt2obj
5066 txt: str
5067 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005068
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005069Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5070
5071By default objects are looked up by OID. With name=True short and
5072long name are also matched.
5073[clinic start generated code]*/
5074
5075static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005076_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5077/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005078{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005079 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005080 ASN1_OBJECT *obj;
5081
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005082 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5083 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005084 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005085 return NULL;
5086 }
5087 result = asn1obj2py(obj);
5088 ASN1_OBJECT_free(obj);
5089 return result;
5090}
5091
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005092/*[clinic input]
5093_ssl.nid2obj
5094 nid: int
5095 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005096
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005097Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5098[clinic start generated code]*/
5099
5100static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005101_ssl_nid2obj_impl(PyObject *module, int nid)
5102/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005103{
5104 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005105 ASN1_OBJECT *obj;
5106
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005107 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005108 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005109 return NULL;
5110 }
5111 obj = OBJ_nid2obj(nid);
5112 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005113 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005114 return NULL;
5115 }
5116 result = asn1obj2py(obj);
5117 ASN1_OBJECT_free(obj);
5118 return result;
5119}
5120
Christian Heimes46bebee2013-06-09 19:03:31 +02005121#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005122
5123static PyObject*
5124certEncodingType(DWORD encodingType)
5125{
5126 static PyObject *x509_asn = NULL;
5127 static PyObject *pkcs_7_asn = NULL;
5128
5129 if (x509_asn == NULL) {
5130 x509_asn = PyUnicode_InternFromString("x509_asn");
5131 if (x509_asn == NULL)
5132 return NULL;
5133 }
5134 if (pkcs_7_asn == NULL) {
5135 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5136 if (pkcs_7_asn == NULL)
5137 return NULL;
5138 }
5139 switch(encodingType) {
5140 case X509_ASN_ENCODING:
5141 Py_INCREF(x509_asn);
5142 return x509_asn;
5143 case PKCS_7_ASN_ENCODING:
5144 Py_INCREF(pkcs_7_asn);
5145 return pkcs_7_asn;
5146 default:
5147 return PyLong_FromLong(encodingType);
5148 }
5149}
5150
5151static PyObject*
5152parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5153{
5154 CERT_ENHKEY_USAGE *usage;
5155 DWORD size, error, i;
5156 PyObject *retval;
5157
5158 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5159 error = GetLastError();
5160 if (error == CRYPT_E_NOT_FOUND) {
5161 Py_RETURN_TRUE;
5162 }
5163 return PyErr_SetFromWindowsErr(error);
5164 }
5165
5166 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5167 if (usage == NULL) {
5168 return PyErr_NoMemory();
5169 }
5170
5171 /* Now get the actual enhanced usage property */
5172 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5173 PyMem_Free(usage);
5174 error = GetLastError();
5175 if (error == CRYPT_E_NOT_FOUND) {
5176 Py_RETURN_TRUE;
5177 }
5178 return PyErr_SetFromWindowsErr(error);
5179 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005180 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005181 if (retval == NULL) {
5182 goto error;
5183 }
5184 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5185 if (usage->rgpszUsageIdentifier[i]) {
5186 PyObject *oid;
5187 int err;
5188 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5189 if (oid == NULL) {
5190 Py_CLEAR(retval);
5191 goto error;
5192 }
5193 err = PySet_Add(retval, oid);
5194 Py_DECREF(oid);
5195 if (err == -1) {
5196 Py_CLEAR(retval);
5197 goto error;
5198 }
5199 }
5200 }
5201 error:
5202 PyMem_Free(usage);
5203 return retval;
5204}
5205
kctherookied93fbbf2019-03-29 00:59:06 +07005206static HCERTSTORE
5207ssl_collect_certificates(const char *store_name)
5208{
5209/* this function collects the system certificate stores listed in
5210 * system_stores into a collection certificate store for being
5211 * enumerated. The store must be readable to be added to the
5212 * store collection.
5213 */
5214
5215 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5216 static DWORD system_stores[] = {
5217 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5218 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5219 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5220 CERT_SYSTEM_STORE_CURRENT_USER,
5221 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5222 CERT_SYSTEM_STORE_SERVICES,
5223 CERT_SYSTEM_STORE_USERS};
5224 size_t i, storesAdded;
5225 BOOL result;
5226
5227 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5228 (HCRYPTPROV)NULL, 0, NULL);
5229 if (!hCollectionStore) {
5230 return NULL;
5231 }
5232 storesAdded = 0;
5233 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5234 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5235 (HCRYPTPROV)NULL,
5236 CERT_STORE_READONLY_FLAG |
5237 system_stores[i], store_name);
5238 if (hSystemStore) {
5239 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5240 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5241 if (result) {
5242 ++storesAdded;
5243 }
neoneneed701292019-09-09 21:33:43 +09005244 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005245 }
5246 }
5247 if (storesAdded == 0) {
5248 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5249 return NULL;
5250 }
5251
5252 return hCollectionStore;
5253}
5254
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005255/*[clinic input]
5256_ssl.enum_certificates
5257 store_name: str
5258
5259Retrieve certificates from Windows' cert store.
5260
5261store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5262more cert storages, too. The function returns a list of (bytes,
5263encoding_type, trust) tuples. The encoding_type flag can be interpreted
5264with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5265a set of OIDs or the boolean True.
5266[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005267
Christian Heimes46bebee2013-06-09 19:03:31 +02005268static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005269_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5270/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005271{
kctherookied93fbbf2019-03-29 00:59:06 +07005272 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005273 PCCERT_CONTEXT pCertCtx = NULL;
5274 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005275 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005276
Christian Heimes915cd3f2019-09-09 18:06:55 +02005277 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005278 if (result == NULL) {
5279 return NULL;
5280 }
kctherookied93fbbf2019-03-29 00:59:06 +07005281 hCollectionStore = ssl_collect_certificates(store_name);
5282 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005283 Py_DECREF(result);
5284 return PyErr_SetFromWindowsErr(GetLastError());
5285 }
5286
kctherookied93fbbf2019-03-29 00:59:06 +07005287 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005288 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5289 pCertCtx->cbCertEncoded);
5290 if (!cert) {
5291 Py_CLEAR(result);
5292 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005293 }
Christian Heimes44109d72013-11-22 01:51:30 +01005294 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5295 Py_CLEAR(result);
5296 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005297 }
Christian Heimes44109d72013-11-22 01:51:30 +01005298 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5299 if (keyusage == Py_True) {
5300 Py_DECREF(keyusage);
5301 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005302 }
Christian Heimes44109d72013-11-22 01:51:30 +01005303 if (keyusage == NULL) {
5304 Py_CLEAR(result);
5305 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005306 }
Christian Heimes44109d72013-11-22 01:51:30 +01005307 if ((tup = PyTuple_New(3)) == NULL) {
5308 Py_CLEAR(result);
5309 break;
5310 }
5311 PyTuple_SET_ITEM(tup, 0, cert);
5312 cert = NULL;
5313 PyTuple_SET_ITEM(tup, 1, enc);
5314 enc = NULL;
5315 PyTuple_SET_ITEM(tup, 2, keyusage);
5316 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005317 if (PySet_Add(result, tup) == -1) {
5318 Py_CLEAR(result);
5319 Py_CLEAR(tup);
5320 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005321 }
5322 Py_CLEAR(tup);
5323 }
5324 if (pCertCtx) {
5325 /* loop ended with an error, need to clean up context manually */
5326 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005327 }
5328
5329 /* In error cases cert, enc and tup may not be NULL */
5330 Py_XDECREF(cert);
5331 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005332 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005333 Py_XDECREF(tup);
5334
kctherookied93fbbf2019-03-29 00:59:06 +07005335 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5336 associated with the store, in this case our collection store and the
5337 associated system stores. */
5338 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005339 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005340 Py_XDECREF(result);
5341 return PyErr_SetFromWindowsErr(GetLastError());
5342 }
kctherookied93fbbf2019-03-29 00:59:06 +07005343
Christian Heimes915cd3f2019-09-09 18:06:55 +02005344 /* convert set to list */
5345 if (result == NULL) {
5346 return NULL;
5347 } else {
5348 PyObject *lst = PySequence_List(result);
5349 Py_DECREF(result);
5350 return lst;
5351 }
Christian Heimes44109d72013-11-22 01:51:30 +01005352}
5353
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005354/*[clinic input]
5355_ssl.enum_crls
5356 store_name: str
5357
5358Retrieve CRLs from Windows' cert store.
5359
5360store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5361more cert storages, too. The function returns a list of (bytes,
5362encoding_type) tuples. The encoding_type flag can be interpreted with
5363X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5364[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005365
5366static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005367_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5368/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005369{
kctherookied93fbbf2019-03-29 00:59:06 +07005370 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005371 PCCRL_CONTEXT pCrlCtx = NULL;
5372 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5373 PyObject *result = NULL;
5374
Christian Heimes915cd3f2019-09-09 18:06:55 +02005375 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005376 if (result == NULL) {
5377 return NULL;
5378 }
kctherookied93fbbf2019-03-29 00:59:06 +07005379 hCollectionStore = ssl_collect_certificates(store_name);
5380 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005381 Py_DECREF(result);
5382 return PyErr_SetFromWindowsErr(GetLastError());
5383 }
Christian Heimes44109d72013-11-22 01:51:30 +01005384
kctherookied93fbbf2019-03-29 00:59:06 +07005385 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005386 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5387 pCrlCtx->cbCrlEncoded);
5388 if (!crl) {
5389 Py_CLEAR(result);
5390 break;
5391 }
5392 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5393 Py_CLEAR(result);
5394 break;
5395 }
5396 if ((tup = PyTuple_New(2)) == NULL) {
5397 Py_CLEAR(result);
5398 break;
5399 }
5400 PyTuple_SET_ITEM(tup, 0, crl);
5401 crl = NULL;
5402 PyTuple_SET_ITEM(tup, 1, enc);
5403 enc = NULL;
5404
Christian Heimes915cd3f2019-09-09 18:06:55 +02005405 if (PySet_Add(result, tup) == -1) {
5406 Py_CLEAR(result);
5407 Py_CLEAR(tup);
5408 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005409 }
5410 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005411 }
Christian Heimes44109d72013-11-22 01:51:30 +01005412 if (pCrlCtx) {
5413 /* loop ended with an error, need to clean up context manually */
5414 CertFreeCRLContext(pCrlCtx);
5415 }
5416
5417 /* In error cases cert, enc and tup may not be NULL */
5418 Py_XDECREF(crl);
5419 Py_XDECREF(enc);
5420 Py_XDECREF(tup);
5421
kctherookied93fbbf2019-03-29 00:59:06 +07005422 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5423 associated with the store, in this case our collection store and the
5424 associated system stores. */
5425 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005426 /* This error case might shadow another exception.*/
5427 Py_XDECREF(result);
5428 return PyErr_SetFromWindowsErr(GetLastError());
5429 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005430 /* convert set to list */
5431 if (result == NULL) {
5432 return NULL;
5433 } else {
5434 PyObject *lst = PySequence_List(result);
5435 Py_DECREF(result);
5436 return lst;
5437 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005438}
Christian Heimes44109d72013-11-22 01:51:30 +01005439
5440#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005441
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005442/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005443static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005444 _SSL__TEST_DECODE_CERT_METHODDEF
5445 _SSL_RAND_ADD_METHODDEF
5446 _SSL_RAND_BYTES_METHODDEF
5447 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5448 _SSL_RAND_EGD_METHODDEF
5449 _SSL_RAND_STATUS_METHODDEF
5450 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5451 _SSL_ENUM_CERTIFICATES_METHODDEF
5452 _SSL_ENUM_CRLS_METHODDEF
5453 _SSL_TXT2OBJ_METHODDEF
5454 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005455 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005456};
5457
5458
Christian Heimes5c36da72020-11-20 09:40:12 +01005459static int
5460sslmodule_init_types(PyObject *module)
5461{
5462 PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5463 module, &PySSLContext_spec, NULL
5464 );
5465 if (PySSLContext_Type == NULL)
5466 return -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005467
Christian Heimes5c36da72020-11-20 09:40:12 +01005468 PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5469 module, &PySSLSocket_spec, NULL
5470 );
5471 if (PySSLSocket_Type == NULL)
5472 return -1;
Martin v. Löwis1a214512008-06-11 05:26:20 +00005473
Christian Heimes5c36da72020-11-20 09:40:12 +01005474 PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5475 module, &PySSLMemoryBIO_spec, NULL
5476 );
5477 if (PySSLMemoryBIO_Type == NULL)
5478 return -1;
Martin v. Löwis1a214512008-06-11 05:26:20 +00005479
Christian Heimes5c36da72020-11-20 09:40:12 +01005480 PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
5481 module, &PySSLSession_spec, NULL
5482 );
5483 if (PySSLSession_Type == NULL)
5484 return -1;
5485
5486 if (PyModule_AddType(module, PySSLContext_Type))
5487 return -1;
5488 if (PyModule_AddType(module, PySSLSocket_Type))
5489 return -1;
5490 if (PyModule_AddType(module, PySSLMemoryBIO_Type))
5491 return -1;
5492 if (PyModule_AddType(module, PySSLSession_Type))
5493 return -1;
5494
5495 return 0;
5496}
5497
5498static int
5499sslmodule_init_exceptions(PyObject *module)
5500{
5501 PyObject *bases = NULL;
5502
5503#define add_exception(exc, name, doc, base) \
5504do { \
5505 (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5506 if ((exc) == NULL) goto error; \
5507 if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
5508} while(0)
5509
Serhiy Storchaka686c2032020-11-22 13:25:02 +02005510 PySSLErrorObject = PyType_FromSpecWithBases(&sslerror_type_spec, PyExc_OSError);
Christian Heimes5c36da72020-11-20 09:40:12 +01005511 if (PySSLErrorObject == NULL) {
5512 goto error;
5513 }
5514 if (PyModule_AddObjectRef(module, "SSLError", PySSLErrorObject) < 0) {
5515 goto error;
5516 }
5517
5518 /* ssl.CertificateError used to be a subclass of ValueError */
5519 bases = PyTuple_Pack(2, PySSLErrorObject, PyExc_ValueError);
5520 if (bases == NULL) {
5521 goto error;
5522 }
5523 add_exception(
5524 PySSLCertVerificationErrorObject,
5525 "SSLCertVerificationError",
5526 SSLCertVerificationError_doc,
5527 bases
5528 );
5529 Py_CLEAR(bases);
5530
5531 add_exception(
5532 PySSLZeroReturnErrorObject,
5533 "SSLZeroReturnError",
5534 SSLZeroReturnError_doc,
5535 PySSLErrorObject
5536 );
5537
5538 add_exception(
5539 PySSLWantWriteErrorObject,
5540 "SSLWantWriteError",
5541 SSLWantWriteError_doc,
5542 PySSLErrorObject
5543 );
5544
5545 add_exception(
5546 PySSLWantReadErrorObject,
5547 "SSLWantReadError",
5548 SSLWantReadError_doc,
5549 PySSLErrorObject
5550 );
5551
5552 add_exception(
5553 PySSLSyscallErrorObject,
5554 "SSLSyscallError",
5555 SSLSyscallError_doc,
5556 PySSLErrorObject
5557 );
5558
5559 add_exception(
5560 PySSLEOFErrorObject,
5561 "SSLEOFError",
5562 SSLEOFError_doc,
5563 PySSLErrorObject
5564 );
5565#undef add_exception
5566
5567 return 0;
5568 error:
5569 Py_XDECREF(bases);
5570 return -1;
5571}
5572
5573static int
5574sslmodule_init_socketapi(PyObject *module)
5575{
5576 PySocketModule_APIObject *socket_api;
5577
5578 /* Load _socket module and its C API */
5579 socket_api = PySocketModule_ImportModuleAndAPI();
5580 if (socket_api == NULL)
5581 return -1;
5582 PySocketModule = *socket_api;
5583
5584 return 0;
5585}
5586
5587static int
5588sslmodule_init_errorcodes(PyObject *module)
5589{
5590 struct py_ssl_error_code *errcode;
5591 struct py_ssl_library_code *libcode;
5592
5593 /* Mappings for error codes */
5594 err_codes_to_names = PyDict_New();
5595 if (err_codes_to_names == NULL)
5596 return -1;
5597 err_names_to_codes = PyDict_New();
5598 if (err_names_to_codes == NULL)
5599 return -1;
5600 lib_codes_to_names = PyDict_New();
5601 if (lib_codes_to_names == NULL)
5602 return -1;
5603
5604 errcode = error_codes;
5605 while (errcode->mnemonic != NULL) {
5606 PyObject *mnemo, *key;
5607 mnemo = PyUnicode_FromString(errcode->mnemonic);
5608 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5609 if (mnemo == NULL || key == NULL)
5610 return -1;
5611 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5612 return -1;
5613 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5614 return -1;
5615 Py_DECREF(key);
5616 Py_DECREF(mnemo);
5617 errcode++;
5618 }
5619
5620 libcode = library_codes;
5621 while (libcode->library != NULL) {
5622 PyObject *mnemo, *key;
5623 key = PyLong_FromLong(libcode->code);
5624 mnemo = PyUnicode_FromString(libcode->library);
5625 if (key == NULL || mnemo == NULL)
5626 return -1;
5627 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5628 return -1;
5629 Py_DECREF(key);
5630 Py_DECREF(mnemo);
5631 libcode++;
5632 }
5633
5634 if (PyModule_AddObject(module, "err_codes_to_names", err_codes_to_names))
5635 return -1;
5636 if (PyModule_AddObject(module, "err_names_to_codes", err_names_to_codes))
5637 return -1;
5638 if (PyModule_AddObject(module, "lib_codes_to_names", lib_codes_to_names))
5639 return -1;
5640
5641 return 0;
5642}
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005643
5644static void
5645parse_openssl_version(unsigned long libver,
5646 unsigned int *major, unsigned int *minor,
5647 unsigned int *fix, unsigned int *patch,
5648 unsigned int *status)
5649{
5650 *status = libver & 0xF;
5651 libver >>= 4;
5652 *patch = libver & 0xFF;
5653 libver >>= 8;
5654 *fix = libver & 0xFF;
5655 libver >>= 8;
5656 *minor = libver & 0xFF;
5657 libver >>= 8;
5658 *major = libver & 0xFF;
5659}
5660
Christian Heimes5c36da72020-11-20 09:40:12 +01005661static int
5662sslmodule_init_versioninfo(PyObject *m)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005663{
Christian Heimes5c36da72020-11-20 09:40:12 +01005664 PyObject *r;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005665 unsigned long libver;
5666 unsigned int major, minor, fix, patch, status;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005667
Christian Heimes5c36da72020-11-20 09:40:12 +01005668 /* OpenSSL version */
5669 /* SSLeay() gives us the version of the library linked against,
5670 which could be different from the headers version.
5671 */
5672 libver = OpenSSL_version_num();
5673 r = PyLong_FromUnsignedLong(libver);
5674 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5675 return -1;
Christian Heimes99a65702016-09-10 23:44:53 +02005676
Christian Heimes5c36da72020-11-20 09:40:12 +01005677 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5678 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5679 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5680 return -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005681
Christian Heimes5c36da72020-11-20 09:40:12 +01005682 r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
5683 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5684 return -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005685
Christian Heimes5c36da72020-11-20 09:40:12 +01005686 libver = OPENSSL_VERSION_NUMBER;
5687 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5688 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5689 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5690 return -1;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005691
Christian Heimes5c36da72020-11-20 09:40:12 +01005692 return 0;
5693}
Christian Heimesc941e622017-09-05 15:47:11 +02005694
Christian Heimes5c36da72020-11-20 09:40:12 +01005695static int
5696sslmodule_init_constants(PyObject *m)
5697{
Christian Heimes892d66e2018-01-29 14:10:18 +01005698 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5699 PY_SSL_DEFAULT_CIPHER_STRING);
5700
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005701 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5702 PY_SSL_ERROR_ZERO_RETURN);
5703 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5704 PY_SSL_ERROR_WANT_READ);
5705 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5706 PY_SSL_ERROR_WANT_WRITE);
5707 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5708 PY_SSL_ERROR_WANT_X509_LOOKUP);
5709 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5710 PY_SSL_ERROR_SYSCALL);
5711 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5712 PY_SSL_ERROR_SSL);
5713 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5714 PY_SSL_ERROR_WANT_CONNECT);
5715 /* non ssl.h errorcodes */
5716 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5717 PY_SSL_ERROR_EOF);
5718 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5719 PY_SSL_ERROR_INVALID_ERROR_CODE);
5720 /* cert requirements */
5721 PyModule_AddIntConstant(m, "CERT_NONE",
5722 PY_SSL_CERT_NONE);
5723 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5724 PY_SSL_CERT_OPTIONAL);
5725 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5726 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005727 /* CRL verification for verification_flags */
5728 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5729 0);
5730 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5731 X509_V_FLAG_CRL_CHECK);
5732 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5733 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5734 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5735 X509_V_FLAG_X509_STRICT);
Chris Burre0b4aa02021-03-18 09:24:01 +01005736 PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
5737 X509_V_FLAG_ALLOW_PROXY_CERTS);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005738 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5739 X509_V_FLAG_TRUSTED_FIRST);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005740
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005741 /* Alert Descriptions from ssl.h */
5742 /* note RESERVED constants no longer intended for use have been removed */
5743 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5744
5745#define ADD_AD_CONSTANT(s) \
5746 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5747 SSL_AD_##s)
5748
5749 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5750 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5751 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5752 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5753 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5754 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5755 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5756 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5757 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5758 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5759 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5760 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5761 ADD_AD_CONSTANT(UNKNOWN_CA);
5762 ADD_AD_CONSTANT(ACCESS_DENIED);
5763 ADD_AD_CONSTANT(DECODE_ERROR);
5764 ADD_AD_CONSTANT(DECRYPT_ERROR);
5765 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5766 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5767 ADD_AD_CONSTANT(INTERNAL_ERROR);
5768 ADD_AD_CONSTANT(USER_CANCELLED);
5769 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005770 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005771#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5772 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5773#endif
5774#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5775 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5776#endif
5777#ifdef SSL_AD_UNRECOGNIZED_NAME
5778 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5779#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005780#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5781 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5782#endif
5783#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5784 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5785#endif
5786#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5787 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5788#endif
5789
5790#undef ADD_AD_CONSTANT
5791
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005792 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005793#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005794 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5795 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005796#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005797#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005798 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5799 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005800#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005801 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005802 PY_SSL_VERSION_TLS);
5803 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5804 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005805 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5806 PY_SSL_VERSION_TLS_CLIENT);
5807 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5808 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005809 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5810 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005811 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5812 PY_SSL_VERSION_TLS1_1);
5813 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5814 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005815
Antoine Pitroub5218772010-05-21 09:56:06 +00005816 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005817 PyModule_AddIntConstant(m, "OP_ALL",
5818 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005819 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5820 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5821 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005822 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5823 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005824#ifdef SSL_OP_NO_TLSv1_3
5825 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5826#else
5827 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5828#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005829 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5830 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005831 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005832 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005833#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005834 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005835#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005836#ifdef SSL_OP_NO_COMPRESSION
5837 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5838 SSL_OP_NO_COMPRESSION);
5839#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005840#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5841 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5842 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5843#endif
Christian Heimes67c48012018-05-15 16:25:40 -04005844#ifdef SSL_OP_NO_RENEGOTIATION
5845 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5846 SSL_OP_NO_RENEGOTIATION);
5847#endif
Christian Heimes6f37ebc2021-04-09 17:59:21 +02005848#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
5849 PyModule_AddIntConstant(m, "OP_IGNORE_UNEXPECTED_EOF",
5850 SSL_OP_IGNORE_UNEXPECTED_EOF);
5851#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005852
Christian Heimes61d478c2018-01-27 15:51:38 +01005853#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5854 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5855 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5856#endif
5857#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5858 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5859 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5860#endif
5861#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5862 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5863 X509_CHECK_FLAG_NO_WILDCARDS);
5864#endif
5865#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5866 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5867 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5868#endif
5869#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5870 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5871 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5872#endif
5873#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5874 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5875 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5876#endif
5877
Christian Heimes698dde12018-02-27 11:54:43 +01005878 /* protocol versions */
5879 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5880 PY_PROTO_MINIMUM_SUPPORTED);
5881 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5882 PY_PROTO_MAXIMUM_SUPPORTED);
5883 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5884 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5885 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5886 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5887 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005888
Victor Stinnerb37672d2018-11-22 03:37:50 +01005889#define addbool(m, key, value) \
5890 do { \
5891 PyObject *bool_obj = (value) ? Py_True : Py_False; \
5892 Py_INCREF(bool_obj); \
5893 PyModule_AddObject((m), (key), bool_obj); \
5894 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01005895
Christian Heimes698dde12018-02-27 11:54:43 +01005896 addbool(m, "HAS_SNI", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005897 addbool(m, "HAS_TLS_UNIQUE", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005898 addbool(m, "HAS_ECDH", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005899 addbool(m, "HAS_NPN", 0);
Christian Heimes698dde12018-02-27 11:54:43 +01005900 addbool(m, "HAS_ALPN", 1);
Christian Heimes698dde12018-02-27 11:54:43 +01005901
5902#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5903 addbool(m, "HAS_SSLv2", 1);
5904#else
5905 addbool(m, "HAS_SSLv2", 0);
5906#endif
5907
5908#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5909 addbool(m, "HAS_SSLv3", 1);
5910#else
5911 addbool(m, "HAS_SSLv3", 0);
5912#endif
5913
5914#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5915 addbool(m, "HAS_TLSv1", 1);
5916#else
5917 addbool(m, "HAS_TLSv1", 0);
5918#endif
5919
5920#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5921 addbool(m, "HAS_TLSv1_1", 1);
5922#else
5923 addbool(m, "HAS_TLSv1_1", 0);
5924#endif
5925
5926#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5927 addbool(m, "HAS_TLSv1_2", 1);
5928#else
5929 addbool(m, "HAS_TLSv1_2", 0);
5930#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005931
Christian Heimescb5b68a2017-09-07 18:07:00 -07005932#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005933 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005934#else
Christian Heimes698dde12018-02-27 11:54:43 +01005935 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005936#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005937
Christian Heimes5c36da72020-11-20 09:40:12 +01005938 return 0;
5939}
5940
Christian Heimes5c36da72020-11-20 09:40:12 +01005941PyDoc_STRVAR(module_doc,
5942"Implementation module for SSL socket operations. See the socket module\n\
5943for documentation.");
5944
5945
5946static struct PyModuleDef _sslmodule = {
5947 PyModuleDef_HEAD_INIT,
5948 "_ssl",
5949 module_doc,
5950 -1,
5951 PySSL_methods,
5952 NULL,
5953 NULL,
5954 NULL,
5955 NULL
5956};
5957
5958PyMODINIT_FUNC
5959PyInit__ssl(void)
5960{
5961 PyObject *m;
5962
5963 m = PyModule_Create(&_sslmodule);
5964 if (m == NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005965 return NULL;
5966
Christian Heimes5c36da72020-11-20 09:40:12 +01005967 if (sslmodule_init_types(m) != 0)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005968 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01005969 if (sslmodule_init_exceptions(m) != 0)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005970 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01005971 if (sslmodule_init_socketapi(m) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005972 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01005973 if (sslmodule_init_errorcodes(m) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005974 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01005975 if (sslmodule_init_constants(m) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005976 return NULL;
Christian Heimes5c36da72020-11-20 09:40:12 +01005977 if (sslmodule_init_versioninfo(m) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005978 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005979
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005980 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005981}