Branch data Line data Source code
1 : : /* SSL socket module
2 : :
3 : : SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
4 : : Re-worked a bit by Bill Janssen to add server-side support and
5 : : certificate decoding. Chris Stawarz contributed some non-blocking
6 : : patches.
7 : :
8 : : This module is imported by ssl.py. It should *not* be used
9 : : directly.
10 : :
11 : : XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
12 : :
13 : : XXX integrate several "shutdown modes" as suggested in
14 : : http://bugs.python.org/issue8108#msg102867 ?
15 : : */
16 : :
17 : : /* 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 : :
24 : : #define PY_SSIZE_T_CLEAN
25 : :
26 : : #include "Python.h"
27 : :
28 : : /* Include symbols from _socket module */
29 : : #include "socketmodule.h"
30 : :
31 : : #ifdef MS_WINDOWS
32 : : # include <wincrypt.h>
33 : : #endif
34 : :
35 : : #include "_ssl.h"
36 : :
37 : : /* Redefined below for Windows debug builds after important #includes */
38 : : #define _PySSL_FIX_ERRNO
39 : :
40 : : #define PySSL_BEGIN_ALLOW_THREADS_S(save) \
41 : : do { (save) = PyEval_SaveThread(); } while(0)
42 : : #define PySSL_END_ALLOW_THREADS_S(save) \
43 : : do { PyEval_RestoreThread(save); _PySSL_FIX_ERRNO; } while(0)
44 : : #define PySSL_BEGIN_ALLOW_THREADS { \
45 : : PyThreadState *_save = NULL; \
46 : : PySSL_BEGIN_ALLOW_THREADS_S(_save);
47 : : #define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
48 : :
49 : :
50 : : #if defined(HAVE_POLL_H)
51 : : #include <poll.h>
52 : : #elif defined(HAVE_SYS_POLL_H)
53 : : #include <sys/poll.h>
54 : : #endif
55 : :
56 : : /* Include OpenSSL header files */
57 : : #include "openssl/rsa.h"
58 : : #include "openssl/crypto.h"
59 : : #include "openssl/x509.h"
60 : : #include "openssl/x509v3.h"
61 : : #include "openssl/pem.h"
62 : : #include "openssl/ssl.h"
63 : : #include "openssl/err.h"
64 : : #include "openssl/rand.h"
65 : : #include "openssl/bio.h"
66 : : #include "openssl/dh.h"
67 : :
68 : : #ifndef OPENSSL_THREADS
69 : : # error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
70 : : #endif
71 : :
72 : :
73 : :
74 : : struct py_ssl_error_code {
75 : : const char *mnemonic;
76 : : int library, reason;
77 : : };
78 : :
79 : : struct py_ssl_library_code {
80 : : const char *library;
81 : : int code;
82 : : };
83 : :
84 : : #if defined(MS_WINDOWS) && defined(Py_DEBUG)
85 : : /* Debug builds on Windows rely on getting errno directly from OpenSSL.
86 : : * However, because it uses a different CRT, we need to transfer the
87 : : * value of errno from OpenSSL into our debug CRT.
88 : : *
89 : : * Don't be fooled - this is horribly ugly code. The only reasonable
90 : : * alternative is to do both debug and release builds of OpenSSL, which
91 : : * requires much uglier code to transform their automatically generated
92 : : * makefile. This is the lesser of all the evils.
93 : : */
94 : :
95 : : static void _PySSLFixErrno(void) {
96 : : HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
97 : : if (!ucrtbase) {
98 : : /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
99 : : * have a catastrophic failure, but this function is not the
100 : : * place to raise it. */
101 : : return;
102 : : }
103 : :
104 : : typedef int *(__stdcall *errno_func)(void);
105 : : errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
106 : : if (ssl_errno) {
107 : : errno = *ssl_errno();
108 : : *ssl_errno() = 0;
109 : : } else {
110 : : errno = ENOTRECOVERABLE;
111 : : }
112 : : }
113 : :
114 : : #undef _PySSL_FIX_ERRNO
115 : : #define _PySSL_FIX_ERRNO _PySSLFixErrno()
116 : : #endif
117 : :
118 : : /* Include generated data (error codes) */
119 : : #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
120 : : #include "_ssl_data_300.h"
121 : : #elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
122 : : #include "_ssl_data_111.h"
123 : : #else
124 : : #include "_ssl_data.h"
125 : : #endif
126 : :
127 : : /* OpenSSL API 1.1.0+ does not include version methods */
128 : : #ifndef OPENSSL_NO_SSL3_METHOD
129 : : extern const SSL_METHOD *SSLv3_method(void);
130 : : #endif
131 : : #ifndef OPENSSL_NO_TLS1_METHOD
132 : : extern const SSL_METHOD *TLSv1_method(void);
133 : : #endif
134 : : #ifndef OPENSSL_NO_TLS1_1_METHOD
135 : : extern const SSL_METHOD *TLSv1_1_method(void);
136 : : #endif
137 : : #ifndef OPENSSL_NO_TLS1_2_METHOD
138 : : extern const SSL_METHOD *TLSv1_2_method(void);
139 : : #endif
140 : :
141 : : #ifndef INVALID_SOCKET /* MS defines this */
142 : : #define INVALID_SOCKET (-1)
143 : : #endif
144 : :
145 : : /* Default cipher suites */
146 : : #ifndef PY_SSL_DEFAULT_CIPHERS
147 : : #define PY_SSL_DEFAULT_CIPHERS 1
148 : : #endif
149 : :
150 : : #if PY_SSL_DEFAULT_CIPHERS == 0
151 : : #ifndef PY_SSL_DEFAULT_CIPHER_STRING
152 : : #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
153 : : #endif
154 : : #ifndef PY_SSL_MIN_PROTOCOL
155 : : #define PY_SSL_MIN_PROTOCOL TLS1_2_VERSION
156 : : #endif
157 : : #elif PY_SSL_DEFAULT_CIPHERS == 1
158 : : /* Python custom selection of sensible cipher suites
159 : : * @SECLEVEL=2: security level 2 with 112 bits minimum security (e.g. 2048 bits RSA key)
160 : : * ECDH+*: enable ephemeral elliptic curve Diffie-Hellman
161 : : * DHE+*: fallback to ephemeral finite field Diffie-Hellman
162 : : * encryption order: AES AEAD (GCM), ChaCha AEAD, AES CBC
163 : : * !aNULL:!eNULL: really no NULL ciphers
164 : : * !aDSS: no authentication with discrete logarithm DSA algorithm
165 : : * !SHA1: no weak SHA1 MAC
166 : : * !AESCCM: no CCM mode, it's uncommon and slow
167 : : *
168 : : * Based on Hynek's excellent blog post (update 2021-02-11)
169 : : * https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
170 : : */
171 : : #define PY_SSL_DEFAULT_CIPHER_STRING "@SECLEVEL=2:ECDH+AESGCM:ECDH+CHACHA20:ECDH+AES:DHE+AES:!aNULL:!eNULL:!aDSS:!SHA1:!AESCCM"
172 : : #ifndef PY_SSL_MIN_PROTOCOL
173 : : #define PY_SSL_MIN_PROTOCOL TLS1_2_VERSION
174 : : #endif
175 : : #elif PY_SSL_DEFAULT_CIPHERS == 2
176 : : /* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
177 : : #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
178 : : #else
179 : : #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
180 : : #endif
181 : :
182 : :
183 : : enum py_ssl_error {
184 : : /* these mirror ssl.h */
185 : : PY_SSL_ERROR_NONE,
186 : : PY_SSL_ERROR_SSL,
187 : : PY_SSL_ERROR_WANT_READ,
188 : : PY_SSL_ERROR_WANT_WRITE,
189 : : PY_SSL_ERROR_WANT_X509_LOOKUP,
190 : : PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
191 : : PY_SSL_ERROR_ZERO_RETURN,
192 : : PY_SSL_ERROR_WANT_CONNECT,
193 : : /* start of non ssl.h errorcodes */
194 : : PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
195 : : PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
196 : : PY_SSL_ERROR_INVALID_ERROR_CODE
197 : : };
198 : :
199 : : enum py_ssl_server_or_client {
200 : : PY_SSL_CLIENT,
201 : : PY_SSL_SERVER
202 : : };
203 : :
204 : : enum py_ssl_cert_requirements {
205 : : PY_SSL_CERT_NONE,
206 : : PY_SSL_CERT_OPTIONAL,
207 : : PY_SSL_CERT_REQUIRED
208 : : };
209 : :
210 : : enum py_ssl_version {
211 : : PY_SSL_VERSION_SSL2,
212 : : PY_SSL_VERSION_SSL3=1,
213 : : PY_SSL_VERSION_TLS, /* SSLv23 */
214 : : PY_SSL_VERSION_TLS1,
215 : : PY_SSL_VERSION_TLS1_1,
216 : : PY_SSL_VERSION_TLS1_2,
217 : : PY_SSL_VERSION_TLS_CLIENT=0x10,
218 : : PY_SSL_VERSION_TLS_SERVER,
219 : : };
220 : :
221 : : enum py_proto_version {
222 : : PY_PROTO_MINIMUM_SUPPORTED = -2,
223 : : PY_PROTO_SSLv3 = SSL3_VERSION,
224 : : PY_PROTO_TLSv1 = TLS1_VERSION,
225 : : PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
226 : : PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
227 : : #ifdef TLS1_3_VERSION
228 : : PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
229 : : #else
230 : : PY_PROTO_TLSv1_3 = 0x304,
231 : : #endif
232 : : PY_PROTO_MAXIMUM_SUPPORTED = -1,
233 : :
234 : : /* OpenSSL has no dedicated API to set the minimum version to the maximum
235 : : * available version, and the other way around. We have to figure out the
236 : : * minimum and maximum available version on our own and hope for the best.
237 : : */
238 : : #if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
239 : : PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
240 : : #elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
241 : : PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
242 : : #elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
243 : : PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
244 : : #elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
245 : : PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
246 : : #elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
247 : : PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
248 : : #else
249 : : #error "PY_PROTO_MINIMUM_AVAILABLE not found"
250 : : #endif
251 : :
252 : : #if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
253 : : PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
254 : : #elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
255 : : PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
256 : : #elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
257 : : PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
258 : : #elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
259 : : PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
260 : : #elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
261 : : PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
262 : : #else
263 : : #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
264 : : #endif
265 : : };
266 : :
267 : : /* SSL socket object */
268 : :
269 : : #define X509_NAME_MAXLEN 256
270 : :
271 : :
272 : : /* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
273 : : * older SSL, but let's be safe */
274 : : #define PySSL_CB_MAXLEN 128
275 : :
276 : :
277 : : typedef struct {
278 : : PyObject_HEAD
279 : : SSL_CTX *ctx;
280 : : unsigned char *alpn_protocols;
281 : : unsigned int alpn_protocols_len;
282 : : PyObject *set_sni_cb;
283 : : int check_hostname;
284 : : /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
285 : : * We have to maintain our own copy. OpenSSL's hostflags default to 0.
286 : : */
287 : : unsigned int hostflags;
288 : : int protocol;
289 : : #ifdef TLS1_3_VERSION
290 : : int post_handshake_auth;
291 : : #endif
292 : : PyObject *msg_cb;
293 : : PyObject *keylog_filename;
294 : : BIO *keylog_bio;
295 : : /* Cached module state, also used in SSLSocket and SSLSession code. */
296 : : _sslmodulestate *state;
297 : : } PySSLContext;
298 : :
299 : : typedef struct {
300 : : int ssl; /* last seen error from SSL */
301 : : int c; /* last seen error from libc */
302 : : #ifdef MS_WINDOWS
303 : : int ws; /* last seen error from winsock */
304 : : #endif
305 : : } _PySSLError;
306 : :
307 : : typedef struct {
308 : : PyObject_HEAD
309 : : PyObject *Socket; /* weakref to socket on which we're layered */
310 : : SSL *ssl;
311 : : PySSLContext *ctx; /* weakref to SSL context */
312 : : char shutdown_seen_zero;
313 : : enum py_ssl_server_or_client socket_type;
314 : : PyObject *owner; /* Python level "owner" passed to servername callback */
315 : : PyObject *server_hostname;
316 : : _PySSLError err; /* last seen error from various sources */
317 : : /* Some SSL callbacks don't have error reporting. Callback wrappers
318 : : * store exception information on the socket. The handshake, read, write,
319 : : * and shutdown methods check for chained exceptions.
320 : : */
321 : : PyObject *exc;
322 : : } PySSLSocket;
323 : :
324 : : typedef struct {
325 : : PyObject_HEAD
326 : : BIO *bio;
327 : : int eof_written;
328 : : } PySSLMemoryBIO;
329 : :
330 : : typedef struct {
331 : : PyObject_HEAD
332 : : SSL_SESSION *session;
333 : : PySSLContext *ctx;
334 : : } PySSLSession;
335 : :
336 : 0 : static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
337 : : {
338 : 0 : _PySSLError err = { 0 };
339 [ # # ]: 0 : if (failed) {
340 : : #ifdef MS_WINDOWS
341 : : err.ws = WSAGetLastError();
342 : : _PySSL_FIX_ERRNO;
343 : : #endif
344 : 0 : err.c = errno;
345 : 0 : err.ssl = SSL_get_error(ssl, retcode);
346 : : }
347 : 0 : return err;
348 : : }
349 : :
350 : : /*[clinic input]
351 : : module _ssl
352 : : class _ssl._SSLContext "PySSLContext *" "get_state_type(type)->PySSLContext_Type"
353 : : class _ssl._SSLSocket "PySSLSocket *" "get_state_type(type)->PySSLSocket_Type"
354 : : class _ssl.MemoryBIO "PySSLMemoryBIO *" "get_state_type(type)->PySSLMemoryBIO_Type"
355 : : class _ssl.SSLSession "PySSLSession *" "get_state_type(type)->PySSLSession_Type"
356 : : [clinic start generated code]*/
357 : : /*[clinic end generated code: output=da39a3ee5e6b4b0d input=d293bed8bae240fd]*/
358 : :
359 : : #include "clinic/_ssl.c.h"
360 : :
361 : : static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
362 : :
363 : : static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
364 : : static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
365 : :
366 : : typedef enum {
367 : : SOCKET_IS_NONBLOCKING,
368 : : SOCKET_IS_BLOCKING,
369 : : SOCKET_HAS_TIMED_OUT,
370 : : SOCKET_HAS_BEEN_CLOSED,
371 : : SOCKET_TOO_LARGE_FOR_SELECT,
372 : : SOCKET_OPERATION_OK
373 : : } timeout_state;
374 : :
375 : : /* Wrap error strings with filename and line # */
376 : : #define ERRSTR1(x,y,z) (x ":" y ": " z)
377 : : #define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
378 : :
379 : : /* Get the socket from a PySSLSocket, if it has one */
380 : : #define GET_SOCKET(obj) ((obj)->Socket ? \
381 : : (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
382 : :
383 : : /* If sock is NULL, use a timeout of 0 second */
384 : : #define GET_SOCKET_TIMEOUT(sock) \
385 : : ((sock != NULL) ? (sock)->sock_timeout : 0)
386 : :
387 : : #include "_ssl/debughelpers.c"
388 : :
389 : : /*
390 : : * SSL errors.
391 : : */
392 : :
393 : : PyDoc_STRVAR(SSLError_doc,
394 : : "An error occurred in the SSL implementation.");
395 : :
396 : : PyDoc_STRVAR(SSLCertVerificationError_doc,
397 : : "A certificate could not be verified.");
398 : :
399 : : PyDoc_STRVAR(SSLZeroReturnError_doc,
400 : : "SSL/TLS session closed cleanly.");
401 : :
402 : : PyDoc_STRVAR(SSLWantReadError_doc,
403 : : "Non-blocking SSL socket needs to read more data\n"
404 : : "before the requested operation can be completed.");
405 : :
406 : : PyDoc_STRVAR(SSLWantWriteError_doc,
407 : : "Non-blocking SSL socket needs to write more data\n"
408 : : "before the requested operation can be completed.");
409 : :
410 : : PyDoc_STRVAR(SSLSyscallError_doc,
411 : : "System error when attempting SSL operation.");
412 : :
413 : : PyDoc_STRVAR(SSLEOFError_doc,
414 : : "SSL/TLS connection terminated abruptly.");
415 : :
416 : : static PyObject *
417 : 0 : SSLError_str(PyOSErrorObject *self)
418 : : {
419 [ # # # # ]: 0 : if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
420 : 0 : return Py_NewRef(self->strerror);
421 : : }
422 : : else
423 : 0 : return PyObject_Str(self->args);
424 : : }
425 : :
426 : : static PyType_Slot sslerror_type_slots[] = {
427 : : {Py_tp_doc, (void*)SSLError_doc},
428 : : {Py_tp_str, SSLError_str},
429 : : {0, 0},
430 : : };
431 : :
432 : : static PyType_Spec sslerror_type_spec = {
433 : : .name = "ssl.SSLError",
434 : : .basicsize = sizeof(PyOSErrorObject),
435 : : .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_IMMUTABLETYPE),
436 : : .slots = sslerror_type_slots
437 : : };
438 : :
439 : : static void
440 : 0 : fill_and_set_sslerror(_sslmodulestate *state,
441 : : PySSLSocket *sslsock, PyObject *type, int ssl_errno,
442 : : const char *errstr, int lineno, unsigned long errcode)
443 : : {
444 : 0 : PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
445 : 0 : PyObject *verify_obj = NULL, *verify_code_obj = NULL;
446 : : PyObject *init_value, *msg, *key;
447 : :
448 [ # # ]: 0 : if (errcode != 0) {
449 : : int lib, reason;
450 : :
451 : 0 : lib = ERR_GET_LIB(errcode);
452 : 0 : reason = ERR_GET_REASON(errcode);
453 : 0 : key = Py_BuildValue("ii", lib, reason);
454 [ # # ]: 0 : if (key == NULL)
455 : 0 : goto fail;
456 : 0 : reason_obj = PyDict_GetItemWithError(state->err_codes_to_names, key);
457 : 0 : Py_DECREF(key);
458 [ # # # # ]: 0 : if (reason_obj == NULL && PyErr_Occurred()) {
459 : 0 : goto fail;
460 : : }
461 : 0 : key = PyLong_FromLong(lib);
462 [ # # ]: 0 : if (key == NULL)
463 : 0 : goto fail;
464 : 0 : lib_obj = PyDict_GetItemWithError(state->lib_codes_to_names, key);
465 : 0 : Py_DECREF(key);
466 [ # # # # ]: 0 : if (lib_obj == NULL && PyErr_Occurred()) {
467 : 0 : goto fail;
468 : : }
469 [ # # ]: 0 : if (errstr == NULL)
470 : 0 : errstr = ERR_reason_error_string(errcode);
471 : : }
472 [ # # ]: 0 : if (errstr == NULL)
473 : 0 : errstr = "unknown error";
474 : :
475 : : /* verify code for cert validation error */
476 [ # # # # ]: 0 : if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
477 : 0 : const char *verify_str = NULL;
478 : : long verify_code;
479 : :
480 : 0 : verify_code = SSL_get_verify_result(sslsock->ssl);
481 : 0 : verify_code_obj = PyLong_FromLong(verify_code);
482 [ # # ]: 0 : if (verify_code_obj == NULL) {
483 : 0 : goto fail;
484 : : }
485 : :
486 [ # # # ]: 0 : switch (verify_code) {
487 : 0 : case X509_V_ERR_HOSTNAME_MISMATCH:
488 : 0 : verify_obj = PyUnicode_FromFormat(
489 : : "Hostname mismatch, certificate is not valid for '%S'.",
490 : : sslsock->server_hostname
491 : : );
492 : 0 : break;
493 : 0 : case X509_V_ERR_IP_ADDRESS_MISMATCH:
494 : 0 : verify_obj = PyUnicode_FromFormat(
495 : : "IP address mismatch, certificate is not valid for '%S'.",
496 : : sslsock->server_hostname
497 : : );
498 : 0 : break;
499 : 0 : default:
500 : 0 : verify_str = X509_verify_cert_error_string(verify_code);
501 [ # # ]: 0 : if (verify_str != NULL) {
502 : 0 : verify_obj = PyUnicode_FromString(verify_str);
503 : : } else {
504 : 0 : verify_obj = Py_NewRef(Py_None);
505 : : }
506 : 0 : break;
507 : : }
508 [ # # ]: 0 : if (verify_obj == NULL) {
509 : 0 : goto fail;
510 : : }
511 : : }
512 : :
513 [ # # # # : 0 : if (verify_obj && reason_obj && lib_obj)
# # ]
514 : 0 : msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
515 : : lib_obj, reason_obj, errstr, verify_obj,
516 : : lineno);
517 [ # # # # ]: 0 : else if (reason_obj && lib_obj)
518 : 0 : msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
519 : : lib_obj, reason_obj, errstr, lineno);
520 [ # # ]: 0 : else if (lib_obj)
521 : 0 : msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
522 : : lib_obj, errstr, lineno);
523 : : else
524 : 0 : msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
525 [ # # ]: 0 : if (msg == NULL)
526 : 0 : goto fail;
527 : :
528 : 0 : init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
529 [ # # ]: 0 : if (init_value == NULL)
530 : 0 : goto fail;
531 : :
532 : 0 : err_value = PyObject_CallObject(type, init_value);
533 : 0 : Py_DECREF(init_value);
534 [ # # ]: 0 : if (err_value == NULL)
535 : 0 : goto fail;
536 : :
537 [ # # ]: 0 : if (reason_obj == NULL)
538 : 0 : reason_obj = Py_None;
539 [ # # ]: 0 : if (PyObject_SetAttr(err_value, state->str_reason, reason_obj))
540 : 0 : goto fail;
541 : :
542 [ # # ]: 0 : if (lib_obj == NULL)
543 : 0 : lib_obj = Py_None;
544 [ # # ]: 0 : if (PyObject_SetAttr(err_value, state->str_library, lib_obj))
545 : 0 : goto fail;
546 : :
547 [ # # # # ]: 0 : if ((sslsock != NULL) && (type == state->PySSLCertVerificationErrorObject)) {
548 : : /* Only set verify code / message for SSLCertVerificationError */
549 [ # # ]: 0 : if (PyObject_SetAttr(err_value, state->str_verify_code,
550 : : verify_code_obj))
551 : 0 : goto fail;
552 [ # # ]: 0 : if (PyObject_SetAttr(err_value, state->str_verify_message, verify_obj))
553 : 0 : goto fail;
554 : : }
555 : :
556 : 0 : PyErr_SetObject(type, err_value);
557 : 0 : fail:
558 : 0 : Py_XDECREF(err_value);
559 : 0 : Py_XDECREF(verify_code_obj);
560 : 0 : Py_XDECREF(verify_obj);
561 : 0 : }
562 : :
563 : : static int
564 : 0 : PySSL_ChainExceptions(PySSLSocket *sslsock) {
565 [ # # ]: 0 : if (sslsock->exc == NULL)
566 : 0 : return 0;
567 : :
568 : 0 : _PyErr_ChainExceptions1(sslsock->exc);
569 : 0 : sslsock->exc = NULL;
570 : 0 : return -1;
571 : : }
572 : :
573 : : static PyObject *
574 : 0 : PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
575 : : {
576 : : PyObject *type;
577 : 0 : char *errstr = NULL;
578 : : _PySSLError err;
579 : 0 : enum py_ssl_error p = PY_SSL_ERROR_NONE;
580 : 0 : unsigned long e = 0;
581 : :
582 : : assert(sslsock != NULL);
583 : :
584 : 0 : _sslmodulestate *state = get_state_sock(sslsock);
585 : 0 : type = state->PySSLErrorObject;
586 : :
587 : : assert(ret <= 0);
588 : 0 : e = ERR_peek_last_error();
589 : :
590 [ # # ]: 0 : if (sslsock->ssl != NULL) {
591 : 0 : err = sslsock->err;
592 : :
593 [ # # # # : 0 : switch (err.ssl) {
# # # # ]
594 : 0 : case SSL_ERROR_ZERO_RETURN:
595 : 0 : errstr = "TLS/SSL connection has been closed (EOF)";
596 : 0 : type = state->PySSLZeroReturnErrorObject;
597 : 0 : p = PY_SSL_ERROR_ZERO_RETURN;
598 : 0 : break;
599 : 0 : case SSL_ERROR_WANT_READ:
600 : 0 : errstr = "The operation did not complete (read)";
601 : 0 : type = state->PySSLWantReadErrorObject;
602 : 0 : p = PY_SSL_ERROR_WANT_READ;
603 : 0 : break;
604 : 0 : case SSL_ERROR_WANT_WRITE:
605 : 0 : p = PY_SSL_ERROR_WANT_WRITE;
606 : 0 : type = state->PySSLWantWriteErrorObject;
607 : 0 : errstr = "The operation did not complete (write)";
608 : 0 : break;
609 : 0 : case SSL_ERROR_WANT_X509_LOOKUP:
610 : 0 : p = PY_SSL_ERROR_WANT_X509_LOOKUP;
611 : 0 : errstr = "The operation did not complete (X509 lookup)";
612 : 0 : break;
613 : 0 : case SSL_ERROR_WANT_CONNECT:
614 : 0 : p = PY_SSL_ERROR_WANT_CONNECT;
615 : 0 : errstr = "The operation did not complete (connect)";
616 : 0 : break;
617 : 0 : case SSL_ERROR_SYSCALL:
618 : : {
619 [ # # ]: 0 : if (e == 0) {
620 [ # # ]: 0 : PySocketSockObject *s = GET_SOCKET(sslsock);
621 [ # # # # ]: 0 : if (ret == 0 || (((PyObject *)s) == Py_None)) {
622 : 0 : p = PY_SSL_ERROR_EOF;
623 : 0 : type = state->PySSLEOFErrorObject;
624 : 0 : errstr = "EOF occurred in violation of protocol";
625 [ # # # # ]: 0 : } else if (s && ret == -1) {
626 : : /* underlying BIO reported an I/O error */
627 : 0 : ERR_clear_error();
628 : : #ifdef MS_WINDOWS
629 : : if (err.ws) {
630 : : return PyErr_SetFromWindowsErr(err.ws);
631 : : }
632 : : #endif
633 [ # # ]: 0 : if (err.c) {
634 : 0 : errno = err.c;
635 : 0 : return PyErr_SetFromErrno(PyExc_OSError);
636 : : }
637 : : else {
638 : 0 : p = PY_SSL_ERROR_EOF;
639 : 0 : type = state->PySSLEOFErrorObject;
640 : 0 : errstr = "EOF occurred in violation of protocol";
641 : : }
642 : : } else { /* possible? */
643 : 0 : p = PY_SSL_ERROR_SYSCALL;
644 : 0 : type = state->PySSLSyscallErrorObject;
645 : 0 : errstr = "Some I/O error occurred";
646 : : }
647 : : } else {
648 : 0 : p = PY_SSL_ERROR_SYSCALL;
649 : : }
650 : 0 : break;
651 : : }
652 : 0 : case SSL_ERROR_SSL:
653 : : {
654 : 0 : p = PY_SSL_ERROR_SSL;
655 [ # # ]: 0 : if (e == 0) {
656 : : /* possible? */
657 : 0 : errstr = "A failure in the SSL library occurred";
658 : : }
659 [ # # ]: 0 : if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
660 [ # # ]: 0 : ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
661 : 0 : type = state->PySSLCertVerificationErrorObject;
662 : : }
663 : 0 : break;
664 : : }
665 : 0 : default:
666 : 0 : p = PY_SSL_ERROR_INVALID_ERROR_CODE;
667 : 0 : errstr = "Invalid error code";
668 : : }
669 : 0 : }
670 : 0 : fill_and_set_sslerror(state, sslsock, type, p, errstr, lineno, e);
671 : 0 : ERR_clear_error();
672 : 0 : PySSL_ChainExceptions(sslsock);
673 : 0 : return NULL;
674 : : }
675 : :
676 : : static PyObject *
677 : 0 : _setSSLError (_sslmodulestate *state, const char *errstr, int errcode, const char *filename, int lineno)
678 : : {
679 [ # # ]: 0 : if (errstr == NULL)
680 : 0 : errcode = ERR_peek_last_error();
681 : : else
682 : 0 : errcode = 0;
683 : 0 : fill_and_set_sslerror(state, NULL, state->PySSLErrorObject, errcode, errstr, lineno, errcode);
684 : 0 : ERR_clear_error();
685 : 0 : return NULL;
686 : : }
687 : :
688 : : static int
689 : 0 : _ssl_deprecated(const char* msg, int stacklevel) {
690 : 0 : return PyErr_WarnEx(
691 : : PyExc_DeprecationWarning, msg, stacklevel
692 : : );
693 : : }
694 : :
695 : : #define PY_SSL_DEPRECATED(name, stacklevel, ret) \
696 : : if (_ssl_deprecated((name), (stacklevel)) == -1) return (ret)
697 : :
698 : : /*
699 : : * SSL objects
700 : : */
701 : :
702 : : static int
703 : 0 : _ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
704 : : {
705 : 0 : int retval = -1;
706 : : ASN1_OCTET_STRING *ip;
707 : : PyObject *hostname;
708 : : size_t len;
709 : :
710 : : assert(server_hostname);
711 : :
712 : : /* Disable OpenSSL's special mode with leading dot in hostname:
713 : : * When name starts with a dot (e.g ".example.com"), it will be
714 : : * matched by a certificate valid for any sub-domain of name.
715 : : */
716 : 0 : len = strlen(server_hostname);
717 [ # # # # ]: 0 : if (len == 0 || *server_hostname == '.') {
718 : 0 : PyErr_SetString(
719 : : PyExc_ValueError,
720 : : "server_hostname cannot be an empty string or start with a "
721 : : "leading dot.");
722 : 0 : return retval;
723 : : }
724 : :
725 : : /* inet_pton is not available on all platforms. */
726 : 0 : ip = a2i_IPADDRESS(server_hostname);
727 [ # # ]: 0 : if (ip == NULL) {
728 : 0 : ERR_clear_error();
729 : : }
730 : :
731 : 0 : hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
732 [ # # ]: 0 : if (hostname == NULL) {
733 : 0 : goto error;
734 : : }
735 : 0 : self->server_hostname = hostname;
736 : :
737 : : /* Only send SNI extension for non-IP hostnames */
738 [ # # ]: 0 : if (ip == NULL) {
739 [ # # ]: 0 : if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
740 : 0 : _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
741 : 0 : goto error;
742 : : }
743 : : }
744 [ # # ]: 0 : if (self->ctx->check_hostname) {
745 : 0 : X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
746 [ # # ]: 0 : if (ip == NULL) {
747 [ # # ]: 0 : if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
748 : : strlen(server_hostname))) {
749 : 0 : _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
750 : 0 : goto error;
751 : : }
752 : : } else {
753 [ # # ]: 0 : if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_get0_data(ip),
754 : 0 : ASN1_STRING_length(ip))) {
755 : 0 : _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
756 : 0 : goto error;
757 : : }
758 : : }
759 : : }
760 : 0 : retval = 0;
761 : 0 : error:
762 [ # # ]: 0 : if (ip != NULL) {
763 : 0 : ASN1_OCTET_STRING_free(ip);
764 : : }
765 : 0 : return retval;
766 : : }
767 : :
768 : : static PySSLSocket *
769 : 0 : newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
770 : : enum py_ssl_server_or_client socket_type,
771 : : char *server_hostname,
772 : : PyObject *owner, PyObject *session,
773 : : PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
774 : : {
775 : : PySSLSocket *self;
776 : 0 : SSL_CTX *ctx = sslctx->ctx;
777 : 0 : _PySSLError err = { 0 };
778 : :
779 [ # # ]: 0 : if ((socket_type == PY_SSL_SERVER) &&
780 [ # # ]: 0 : (sslctx->protocol == PY_SSL_VERSION_TLS_CLIENT)) {
781 : 0 : _setSSLError(get_state_ctx(sslctx),
782 : : "Cannot create a server socket with a "
783 : : "PROTOCOL_TLS_CLIENT context", 0, __FILE__, __LINE__);
784 : 0 : return NULL;
785 : : }
786 [ # # ]: 0 : if ((socket_type == PY_SSL_CLIENT) &&
787 [ # # ]: 0 : (sslctx->protocol == PY_SSL_VERSION_TLS_SERVER)) {
788 : 0 : _setSSLError(get_state_ctx(sslctx),
789 : : "Cannot create a client socket with a "
790 : : "PROTOCOL_TLS_SERVER context", 0, __FILE__, __LINE__);
791 : 0 : return NULL;
792 : : }
793 : :
794 : 0 : self = PyObject_GC_New(PySSLSocket,
795 : : get_state_ctx(sslctx)->PySSLSocket_Type);
796 [ # # ]: 0 : if (self == NULL)
797 : 0 : return NULL;
798 : :
799 : 0 : self->ssl = NULL;
800 : 0 : self->Socket = NULL;
801 : 0 : self->ctx = (PySSLContext*)Py_NewRef(sslctx);
802 : 0 : self->shutdown_seen_zero = 0;
803 : 0 : self->owner = NULL;
804 : 0 : self->server_hostname = NULL;
805 : 0 : self->err = err;
806 : 0 : self->exc = NULL;
807 : :
808 : : /* Make sure the SSL error state is initialized */
809 : 0 : ERR_clear_error();
810 : :
811 : 0 : PySSL_BEGIN_ALLOW_THREADS
812 : 0 : self->ssl = SSL_new(ctx);
813 : 0 : PySSL_END_ALLOW_THREADS
814 [ # # ]: 0 : if (self->ssl == NULL) {
815 : 0 : Py_DECREF(self);
816 : 0 : _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
817 : 0 : return NULL;
818 : : }
819 : : /* bpo43522 and OpenSSL < 1.1.1l: copy hostflags manually */
820 : : #if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION < 0x101010cf
821 : 0 : X509_VERIFY_PARAM *ssl_params = SSL_get0_param(self->ssl);
822 : 0 : X509_VERIFY_PARAM_set_hostflags(ssl_params, sslctx->hostflags);
823 : : #endif
824 : 0 : SSL_set_app_data(self->ssl, self);
825 [ # # ]: 0 : if (sock) {
826 : 0 : SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
827 : : } else {
828 : : /* BIOs are reference counted and SSL_set_bio borrows our reference.
829 : : * To prevent a double free in memory_bio_dealloc() we need to take an
830 : : * extra reference here. */
831 : 0 : BIO_up_ref(inbio->bio);
832 : 0 : BIO_up_ref(outbio->bio);
833 : 0 : SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
834 : : }
835 : 0 : SSL_set_mode(self->ssl,
836 : : SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
837 : :
838 : : #ifdef TLS1_3_VERSION
839 [ # # ]: 0 : if (sslctx->post_handshake_auth == 1) {
840 [ # # ]: 0 : if (socket_type == PY_SSL_SERVER) {
841 : : /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
842 : : * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
843 : : * only in combination with SSL_VERIFY_PEER flag. */
844 : 0 : int mode = SSL_get_verify_mode(self->ssl);
845 [ # # ]: 0 : if (mode & SSL_VERIFY_PEER) {
846 : 0 : int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
847 : 0 : verify_cb = SSL_get_verify_callback(self->ssl);
848 : 0 : mode |= SSL_VERIFY_POST_HANDSHAKE;
849 : 0 : SSL_set_verify(self->ssl, mode, verify_cb);
850 : : }
851 : : } else {
852 : : /* client socket */
853 : 0 : SSL_set_post_handshake_auth(self->ssl, 1);
854 : : }
855 : : }
856 : : #endif
857 : :
858 [ # # ]: 0 : if (server_hostname != NULL) {
859 [ # # ]: 0 : if (_ssl_configure_hostname(self, server_hostname) < 0) {
860 : 0 : Py_DECREF(self);
861 : 0 : return NULL;
862 : : }
863 : : }
864 : : /* If the socket is in non-blocking mode or timeout mode, set the BIO
865 : : * to non-blocking mode (blocking is the default)
866 : : */
867 [ # # # # ]: 0 : if (sock && sock->sock_timeout >= 0) {
868 : 0 : BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
869 : 0 : BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
870 : : }
871 : :
872 : 0 : PySSL_BEGIN_ALLOW_THREADS
873 [ # # ]: 0 : if (socket_type == PY_SSL_CLIENT)
874 : 0 : SSL_set_connect_state(self->ssl);
875 : : else
876 : 0 : SSL_set_accept_state(self->ssl);
877 : 0 : PySSL_END_ALLOW_THREADS
878 : :
879 : 0 : self->socket_type = socket_type;
880 [ # # ]: 0 : if (sock != NULL) {
881 : 0 : self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
882 [ # # ]: 0 : if (self->Socket == NULL) {
883 : 0 : Py_DECREF(self);
884 : 0 : return NULL;
885 : : }
886 : : }
887 [ # # # # ]: 0 : if (owner && owner != Py_None) {
888 [ # # ]: 0 : if (PySSL_set_owner(self, owner, NULL) == -1) {
889 : 0 : Py_DECREF(self);
890 : 0 : return NULL;
891 : : }
892 : : }
893 [ # # # # ]: 0 : if (session && session != Py_None) {
894 [ # # ]: 0 : if (PySSL_set_session(self, session, NULL) == -1) {
895 : 0 : Py_DECREF(self);
896 : 0 : return NULL;
897 : : }
898 : : }
899 : :
900 : 0 : PyObject_GC_Track(self);
901 : 0 : return self;
902 : : }
903 : :
904 : : /* SSL object methods */
905 : :
906 : : /*[clinic input]
907 : : _ssl._SSLSocket.do_handshake
908 : : [clinic start generated code]*/
909 : :
910 : : static PyObject *
911 : 0 : _ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
912 : : /*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
913 : : {
914 : : int ret;
915 : : _PySSLError err;
916 : : int sockstate, nonblocking;
917 [ # # ]: 0 : PySocketSockObject *sock = GET_SOCKET(self);
918 : 0 : _PyTime_t timeout, deadline = 0;
919 : : int has_timeout;
920 : :
921 [ # # ]: 0 : if (sock) {
922 [ # # ]: 0 : if (((PyObject*)sock) == Py_None) {
923 : 0 : _setSSLError(get_state_sock(self),
924 : : "Underlying socket connection gone",
925 : : PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
926 : 0 : return NULL;
927 : : }
928 : 0 : Py_INCREF(sock);
929 : :
930 : : /* just in case the blocking state of the socket has been changed */
931 : 0 : nonblocking = (sock->sock_timeout >= 0);
932 : 0 : BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
933 : 0 : BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
934 : : }
935 : :
936 [ # # ]: 0 : timeout = GET_SOCKET_TIMEOUT(sock);
937 : 0 : has_timeout = (timeout > 0);
938 [ # # ]: 0 : if (has_timeout) {
939 : 0 : deadline = _PyDeadline_Init(timeout);
940 : : }
941 : :
942 : : /* Actually negotiate SSL connection */
943 : : /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
944 : : do {
945 : 0 : PySSL_BEGIN_ALLOW_THREADS
946 : 0 : ret = SSL_do_handshake(self->ssl);
947 : 0 : err = _PySSL_errno(ret < 1, self->ssl, ret);
948 : 0 : PySSL_END_ALLOW_THREADS
949 : 0 : self->err = err;
950 : :
951 [ # # ]: 0 : if (PyErr_CheckSignals())
952 : 0 : goto error;
953 : :
954 [ # # ]: 0 : if (has_timeout)
955 : 0 : timeout = _PyDeadline_Get(deadline);
956 : :
957 [ # # ]: 0 : if (err.ssl == SSL_ERROR_WANT_READ) {
958 : 0 : sockstate = PySSL_select(sock, 0, timeout);
959 [ # # ]: 0 : } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
960 : 0 : sockstate = PySSL_select(sock, 1, timeout);
961 : : } else {
962 : 0 : sockstate = SOCKET_OPERATION_OK;
963 : : }
964 : :
965 [ # # ]: 0 : if (sockstate == SOCKET_HAS_TIMED_OUT) {
966 : 0 : PyErr_SetString(PyExc_TimeoutError,
967 : : ERRSTR("The handshake operation timed out"));
968 : 0 : goto error;
969 [ # # ]: 0 : } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
970 : 0 : PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
971 : : ERRSTR("Underlying socket has been closed."));
972 : 0 : goto error;
973 [ # # ]: 0 : } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
974 : 0 : PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
975 : : ERRSTR("Underlying socket too large for select()."));
976 : 0 : goto error;
977 [ # # ]: 0 : } else if (sockstate == SOCKET_IS_NONBLOCKING) {
978 : 0 : break;
979 : : }
980 : 0 : } while (err.ssl == SSL_ERROR_WANT_READ ||
981 [ # # # # ]: 0 : err.ssl == SSL_ERROR_WANT_WRITE);
982 : 0 : Py_XDECREF(sock);
983 [ # # ]: 0 : if (ret < 1)
984 : 0 : return PySSL_SetError(self, ret, __FILE__, __LINE__);
985 [ # # ]: 0 : if (PySSL_ChainExceptions(self) < 0)
986 : 0 : return NULL;
987 : 0 : Py_RETURN_NONE;
988 : 0 : error:
989 : 0 : Py_XDECREF(sock);
990 : 0 : PySSL_ChainExceptions(self);
991 : 0 : return NULL;
992 : : }
993 : :
994 : : static PyObject *
995 : 4 : _asn1obj2py(_sslmodulestate *state, const ASN1_OBJECT *name, int no_name)
996 : : {
997 : : char buf[X509_NAME_MAXLEN];
998 : 4 : char *namebuf = buf;
999 : : int buflen;
1000 : 4 : PyObject *name_obj = NULL;
1001 : :
1002 : 4 : buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
1003 [ - + ]: 4 : if (buflen < 0) {
1004 : 0 : _setSSLError(state, NULL, 0, __FILE__, __LINE__);
1005 : 0 : return NULL;
1006 : : }
1007 : : /* initial buffer is too small for oid + terminating null byte */
1008 [ - + ]: 4 : if (buflen > X509_NAME_MAXLEN - 1) {
1009 : : /* make OBJ_obj2txt() calculate the required buflen */
1010 : 0 : buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1011 : : /* allocate len + 1 for terminating NULL byte */
1012 : 0 : namebuf = PyMem_Malloc(buflen + 1);
1013 [ # # ]: 0 : if (namebuf == NULL) {
1014 : 0 : PyErr_NoMemory();
1015 : 0 : return NULL;
1016 : : }
1017 : 0 : buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1018 [ # # ]: 0 : if (buflen < 0) {
1019 : 0 : _setSSLError(state, NULL, 0, __FILE__, __LINE__);
1020 : 0 : goto done;
1021 : : }
1022 : : }
1023 [ - + - - ]: 4 : if (!buflen && no_name) {
1024 : 0 : name_obj = Py_NewRef(Py_None);
1025 : : }
1026 : : else {
1027 : 4 : name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1028 : : }
1029 : :
1030 : 4 : done:
1031 [ - + ]: 4 : if (buf != namebuf) {
1032 : 0 : PyMem_Free(namebuf);
1033 : : }
1034 : 4 : return name_obj;
1035 : : }
1036 : :
1037 : : static PyObject *
1038 : 0 : _create_tuple_for_attribute(_sslmodulestate *state,
1039 : : ASN1_OBJECT *name, ASN1_STRING *value)
1040 : : {
1041 : : Py_ssize_t buflen;
1042 : : PyObject *pyattr;
1043 : 0 : PyObject *pyname = _asn1obj2py(state, name, 0);
1044 : :
1045 [ # # ]: 0 : if (pyname == NULL) {
1046 : 0 : _setSSLError(state, NULL, 0, __FILE__, __LINE__);
1047 : 0 : return NULL;
1048 : : }
1049 : :
1050 [ # # ]: 0 : if (ASN1_STRING_type(value) == V_ASN1_BIT_STRING) {
1051 : 0 : buflen = ASN1_STRING_length(value);
1052 : 0 : pyattr = Py_BuildValue("Ny#", pyname, ASN1_STRING_get0_data(value), buflen);
1053 : : } else {
1054 : 0 : unsigned char *valuebuf = NULL;
1055 : 0 : buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1056 [ # # ]: 0 : if (buflen < 0) {
1057 : 0 : _setSSLError(state, NULL, 0, __FILE__, __LINE__);
1058 : 0 : Py_DECREF(pyname);
1059 : 0 : return NULL;
1060 : : }
1061 : 0 : pyattr = Py_BuildValue("Ns#", pyname, valuebuf, buflen);
1062 : 0 : OPENSSL_free(valuebuf);
1063 : : }
1064 : 0 : return pyattr;
1065 : : }
1066 : :
1067 : : static PyObject *
1068 : 0 : _create_tuple_for_X509_NAME (_sslmodulestate *state, X509_NAME *xname)
1069 : : {
1070 : 0 : PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1071 : 0 : PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1072 : : PyObject *rdnt;
1073 : 0 : PyObject *attr = NULL; /* tuple to hold an attribute */
1074 : 0 : int entry_count = X509_NAME_entry_count(xname);
1075 : : X509_NAME_ENTRY *entry;
1076 : : ASN1_OBJECT *name;
1077 : : ASN1_STRING *value;
1078 : : int index_counter;
1079 : 0 : int rdn_level = -1;
1080 : : int retcode;
1081 : :
1082 : 0 : dn = PyList_New(0);
1083 [ # # ]: 0 : if (dn == NULL)
1084 : 0 : return NULL;
1085 : : /* now create another tuple to hold the top-level RDN */
1086 : 0 : rdn = PyList_New(0);
1087 [ # # ]: 0 : if (rdn == NULL)
1088 : 0 : goto fail0;
1089 : :
1090 [ # # ]: 0 : for (index_counter = 0;
1091 : : index_counter < entry_count;
1092 : 0 : index_counter++)
1093 : : {
1094 : 0 : entry = X509_NAME_get_entry(xname, index_counter);
1095 : :
1096 : : /* check to see if we've gotten to a new RDN */
1097 [ # # ]: 0 : if (rdn_level >= 0) {
1098 [ # # ]: 0 : if (rdn_level != X509_NAME_ENTRY_set(entry)) {
1099 : : /* yes, new RDN */
1100 : : /* add old RDN to DN */
1101 : 0 : rdnt = PyList_AsTuple(rdn);
1102 : 0 : Py_DECREF(rdn);
1103 [ # # ]: 0 : if (rdnt == NULL)
1104 : 0 : goto fail0;
1105 : 0 : retcode = PyList_Append(dn, rdnt);
1106 : 0 : Py_DECREF(rdnt);
1107 [ # # ]: 0 : if (retcode < 0)
1108 : 0 : goto fail0;
1109 : : /* create new RDN */
1110 : 0 : rdn = PyList_New(0);
1111 [ # # ]: 0 : if (rdn == NULL)
1112 : 0 : goto fail0;
1113 : : }
1114 : : }
1115 : 0 : rdn_level = X509_NAME_ENTRY_set(entry);
1116 : :
1117 : : /* now add this attribute to the current RDN */
1118 : 0 : name = X509_NAME_ENTRY_get_object(entry);
1119 : 0 : value = X509_NAME_ENTRY_get_data(entry);
1120 : 0 : attr = _create_tuple_for_attribute(state, name, value);
1121 : : /*
1122 : : fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1123 : : entry->set,
1124 : : PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1125 : : PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1126 : : */
1127 [ # # ]: 0 : if (attr == NULL)
1128 : 0 : goto fail1;
1129 : 0 : retcode = PyList_Append(rdn, attr);
1130 : 0 : Py_DECREF(attr);
1131 [ # # ]: 0 : if (retcode < 0)
1132 : 0 : goto fail1;
1133 : : }
1134 : : /* now, there's typically a dangling RDN */
1135 [ # # ]: 0 : if (rdn != NULL) {
1136 [ # # ]: 0 : if (PyList_GET_SIZE(rdn) > 0) {
1137 : 0 : rdnt = PyList_AsTuple(rdn);
1138 : 0 : Py_DECREF(rdn);
1139 [ # # ]: 0 : if (rdnt == NULL)
1140 : 0 : goto fail0;
1141 : 0 : retcode = PyList_Append(dn, rdnt);
1142 : 0 : Py_DECREF(rdnt);
1143 [ # # ]: 0 : if (retcode < 0)
1144 : 0 : goto fail0;
1145 : : }
1146 : : else {
1147 : 0 : Py_DECREF(rdn);
1148 : : }
1149 : : }
1150 : :
1151 : : /* convert list to tuple */
1152 : 0 : rdnt = PyList_AsTuple(dn);
1153 : 0 : Py_DECREF(dn);
1154 [ # # ]: 0 : if (rdnt == NULL)
1155 : 0 : return NULL;
1156 : 0 : return rdnt;
1157 : :
1158 : 0 : fail1:
1159 : 0 : Py_XDECREF(rdn);
1160 : :
1161 : 0 : fail0:
1162 : 0 : Py_XDECREF(dn);
1163 : 0 : return NULL;
1164 : : }
1165 : :
1166 : : static PyObject *
1167 : 0 : _get_peer_alt_names (_sslmodulestate *state, X509 *certificate) {
1168 : :
1169 : : /* this code follows the procedure outlined in
1170 : : OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1171 : : function to extract the STACK_OF(GENERAL_NAME),
1172 : : then iterates through the stack to add the
1173 : : names. */
1174 : :
1175 : : int j;
1176 : 0 : PyObject *peer_alt_names = Py_None;
1177 : 0 : PyObject *v = NULL, *t;
1178 : 0 : GENERAL_NAMES *names = NULL;
1179 : : GENERAL_NAME *name;
1180 : 0 : BIO *biobuf = NULL;
1181 : : char buf[2048];
1182 : : char *vptr;
1183 : : int len;
1184 : :
1185 [ # # ]: 0 : if (certificate == NULL)
1186 : 0 : return peer_alt_names;
1187 : :
1188 : : /* get a memory buffer */
1189 : 0 : biobuf = BIO_new(BIO_s_mem());
1190 [ # # ]: 0 : if (biobuf == NULL) {
1191 : 0 : PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
1192 : 0 : return NULL;
1193 : : }
1194 : :
1195 : 0 : names = (GENERAL_NAMES *)X509_get_ext_d2i(
1196 : : certificate, NID_subject_alt_name, NULL, NULL);
1197 [ # # ]: 0 : if (names != NULL) {
1198 [ # # ]: 0 : if (peer_alt_names == Py_None) {
1199 : 0 : peer_alt_names = PyList_New(0);
1200 [ # # ]: 0 : if (peer_alt_names == NULL)
1201 : 0 : goto fail;
1202 : : }
1203 : :
1204 [ # # ]: 0 : for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
1205 : : /* get a rendering of each name in the set of names */
1206 : : int gntype;
1207 : 0 : ASN1_STRING *as = NULL;
1208 : :
1209 : 0 : name = sk_GENERAL_NAME_value(names, j);
1210 : 0 : gntype = name->type;
1211 [ # # # # : 0 : switch (gntype) {
# ]
1212 : 0 : case GEN_DIRNAME:
1213 : : /* we special-case DirName as a tuple of
1214 : : tuples of attributes */
1215 : :
1216 : 0 : t = PyTuple_New(2);
1217 [ # # ]: 0 : if (t == NULL) {
1218 : 0 : goto fail;
1219 : : }
1220 : :
1221 : 0 : v = PyUnicode_FromString("DirName");
1222 [ # # ]: 0 : if (v == NULL) {
1223 : 0 : Py_DECREF(t);
1224 : 0 : goto fail;
1225 : : }
1226 : 0 : PyTuple_SET_ITEM(t, 0, v);
1227 : :
1228 : 0 : v = _create_tuple_for_X509_NAME(state, name->d.dirn);
1229 [ # # ]: 0 : if (v == NULL) {
1230 : 0 : Py_DECREF(t);
1231 : 0 : goto fail;
1232 : : }
1233 : 0 : PyTuple_SET_ITEM(t, 1, v);
1234 : 0 : break;
1235 : :
1236 : 0 : case GEN_EMAIL:
1237 : : case GEN_DNS:
1238 : : case GEN_URI:
1239 : : /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1240 : : correctly, CVE-2013-4238 */
1241 : 0 : t = PyTuple_New(2);
1242 [ # # ]: 0 : if (t == NULL)
1243 : 0 : goto fail;
1244 : : switch (gntype) {
1245 : 0 : case GEN_EMAIL:
1246 : 0 : v = PyUnicode_FromString("email");
1247 : 0 : as = name->d.rfc822Name;
1248 : 0 : break;
1249 : 0 : case GEN_DNS:
1250 : 0 : v = PyUnicode_FromString("DNS");
1251 : 0 : as = name->d.dNSName;
1252 : 0 : break;
1253 : 0 : case GEN_URI:
1254 : 0 : v = PyUnicode_FromString("URI");
1255 : 0 : as = name->d.uniformResourceIdentifier;
1256 : 0 : break;
1257 : : }
1258 [ # # ]: 0 : if (v == NULL) {
1259 : 0 : Py_DECREF(t);
1260 : 0 : goto fail;
1261 : : }
1262 : 0 : PyTuple_SET_ITEM(t, 0, v);
1263 : 0 : v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_get0_data(as),
1264 : 0 : ASN1_STRING_length(as));
1265 [ # # ]: 0 : if (v == NULL) {
1266 : 0 : Py_DECREF(t);
1267 : 0 : goto fail;
1268 : : }
1269 : 0 : PyTuple_SET_ITEM(t, 1, v);
1270 : 0 : break;
1271 : :
1272 : 0 : case GEN_RID:
1273 : 0 : t = PyTuple_New(2);
1274 [ # # ]: 0 : if (t == NULL)
1275 : 0 : goto fail;
1276 : :
1277 : 0 : v = PyUnicode_FromString("Registered ID");
1278 [ # # ]: 0 : if (v == NULL) {
1279 : 0 : Py_DECREF(t);
1280 : 0 : goto fail;
1281 : : }
1282 : 0 : PyTuple_SET_ITEM(t, 0, v);
1283 : :
1284 : 0 : len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1285 [ # # ]: 0 : if (len < 0) {
1286 : 0 : Py_DECREF(t);
1287 : 0 : _setSSLError(state, NULL, 0, __FILE__, __LINE__);
1288 : 0 : goto fail;
1289 [ # # ]: 0 : } else if (len >= (int)sizeof(buf)) {
1290 : 0 : v = PyUnicode_FromString("<INVALID>");
1291 : : } else {
1292 : 0 : v = PyUnicode_FromStringAndSize(buf, len);
1293 : : }
1294 [ # # ]: 0 : if (v == NULL) {
1295 : 0 : Py_DECREF(t);
1296 : 0 : goto fail;
1297 : : }
1298 : 0 : PyTuple_SET_ITEM(t, 1, v);
1299 : 0 : break;
1300 : :
1301 : 0 : case GEN_IPADD:
1302 : : /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1303 : : * the trailing newline. Remove it in all versions
1304 : : */
1305 : 0 : t = PyTuple_New(2);
1306 [ # # ]: 0 : if (t == NULL)
1307 : 0 : goto fail;
1308 : :
1309 : 0 : v = PyUnicode_FromString("IP Address");
1310 [ # # ]: 0 : if (v == NULL) {
1311 : 0 : Py_DECREF(t);
1312 : 0 : goto fail;
1313 : : }
1314 : 0 : PyTuple_SET_ITEM(t, 0, v);
1315 : :
1316 [ # # ]: 0 : if (name->d.ip->length == 4) {
1317 : 0 : unsigned char *p = name->d.ip->data;
1318 : 0 : v = PyUnicode_FromFormat(
1319 : : "%d.%d.%d.%d",
1320 : 0 : p[0], p[1], p[2], p[3]
1321 : : );
1322 [ # # ]: 0 : } else if (name->d.ip->length == 16) {
1323 : : /* PyUnicode_FromFormat() does not support %X */
1324 : 0 : unsigned char *p = name->d.ip->data;
1325 : 0 : len = sprintf(
1326 : : buf,
1327 : : "%X:%X:%X:%X:%X:%X:%X:%X",
1328 : 0 : p[0] << 8 | p[1],
1329 : 0 : p[2] << 8 | p[3],
1330 : 0 : p[4] << 8 | p[5],
1331 : 0 : p[6] << 8 | p[7],
1332 : 0 : p[8] << 8 | p[9],
1333 : 0 : p[10] << 8 | p[11],
1334 : 0 : p[12] << 8 | p[13],
1335 : 0 : p[14] << 8 | p[15]
1336 : : );
1337 : 0 : v = PyUnicode_FromStringAndSize(buf, len);
1338 : : } else {
1339 : 0 : v = PyUnicode_FromString("<invalid>");
1340 : : }
1341 : :
1342 [ # # ]: 0 : if (v == NULL) {
1343 : 0 : Py_DECREF(t);
1344 : 0 : goto fail;
1345 : : }
1346 : 0 : PyTuple_SET_ITEM(t, 1, v);
1347 : 0 : break;
1348 : :
1349 [ # # ]: 0 : default:
1350 : : /* for everything else, we use the OpenSSL print form */
1351 : : switch (gntype) {
1352 : : /* check for new general name type */
1353 : 0 : case GEN_OTHERNAME:
1354 : : case GEN_X400:
1355 : : case GEN_EDIPARTY:
1356 : : case GEN_RID:
1357 : 0 : break;
1358 : 0 : default:
1359 [ # # ]: 0 : if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1360 : : "Unknown general name type %d",
1361 : : gntype) == -1) {
1362 : 0 : goto fail;
1363 : : }
1364 : 0 : break;
1365 : : }
1366 : 0 : (void) BIO_reset(biobuf);
1367 : 0 : GENERAL_NAME_print(biobuf, name);
1368 : 0 : len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1369 [ # # ]: 0 : if (len < 0) {
1370 : 0 : _setSSLError(state, NULL, 0, __FILE__, __LINE__);
1371 : 0 : goto fail;
1372 : : }
1373 : 0 : vptr = strchr(buf, ':');
1374 [ # # ]: 0 : if (vptr == NULL) {
1375 : 0 : PyErr_Format(PyExc_ValueError,
1376 : : "Invalid value %.200s",
1377 : : buf);
1378 : 0 : goto fail;
1379 : : }
1380 : 0 : t = PyTuple_New(2);
1381 [ # # ]: 0 : if (t == NULL)
1382 : 0 : goto fail;
1383 : 0 : v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1384 [ # # ]: 0 : if (v == NULL) {
1385 : 0 : Py_DECREF(t);
1386 : 0 : goto fail;
1387 : : }
1388 : 0 : PyTuple_SET_ITEM(t, 0, v);
1389 : 0 : v = PyUnicode_FromStringAndSize((vptr + 1),
1390 : 0 : (len - (vptr - buf + 1)));
1391 [ # # ]: 0 : if (v == NULL) {
1392 : 0 : Py_DECREF(t);
1393 : 0 : goto fail;
1394 : : }
1395 : 0 : PyTuple_SET_ITEM(t, 1, v);
1396 : 0 : break;
1397 : : }
1398 : :
1399 : : /* and add that rendering to the list */
1400 : :
1401 [ # # ]: 0 : if (PyList_Append(peer_alt_names, t) < 0) {
1402 : 0 : Py_DECREF(t);
1403 : 0 : goto fail;
1404 : : }
1405 : 0 : Py_DECREF(t);
1406 : : }
1407 : 0 : sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
1408 : : }
1409 : 0 : BIO_free(biobuf);
1410 [ # # ]: 0 : if (peer_alt_names != Py_None) {
1411 : 0 : v = PyList_AsTuple(peer_alt_names);
1412 : 0 : Py_DECREF(peer_alt_names);
1413 : 0 : return v;
1414 : : } else {
1415 : 0 : return peer_alt_names;
1416 : : }
1417 : :
1418 : :
1419 : 0 : fail:
1420 [ # # ]: 0 : if (biobuf != NULL)
1421 : 0 : BIO_free(biobuf);
1422 : :
1423 [ # # ]: 0 : if (peer_alt_names != Py_None) {
1424 : 0 : Py_XDECREF(peer_alt_names);
1425 : : }
1426 : :
1427 : 0 : return NULL;
1428 : : }
1429 : :
1430 : : static PyObject *
1431 : 0 : _get_aia_uri(X509 *certificate, int nid) {
1432 : 0 : PyObject *lst = NULL, *ostr = NULL;
1433 : : int i, result;
1434 : : AUTHORITY_INFO_ACCESS *info;
1435 : :
1436 : 0 : info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
1437 [ # # ]: 0 : if (info == NULL)
1438 : 0 : return Py_None;
1439 [ # # ]: 0 : if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1440 : 0 : AUTHORITY_INFO_ACCESS_free(info);
1441 : 0 : return Py_None;
1442 : : }
1443 : :
1444 [ # # ]: 0 : if ((lst = PyList_New(0)) == NULL) {
1445 : 0 : goto fail;
1446 : : }
1447 : :
1448 [ # # ]: 0 : for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1449 : 0 : ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1450 : : ASN1_IA5STRING *uri;
1451 : :
1452 [ # # ]: 0 : if ((OBJ_obj2nid(ad->method) != nid) ||
1453 [ # # ]: 0 : (ad->location->type != GEN_URI)) {
1454 : 0 : continue;
1455 : : }
1456 : 0 : uri = ad->location->d.uniformResourceIdentifier;
1457 : 0 : ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1458 : 0 : uri->length);
1459 [ # # ]: 0 : if (ostr == NULL) {
1460 : 0 : goto fail;
1461 : : }
1462 : 0 : result = PyList_Append(lst, ostr);
1463 : 0 : Py_DECREF(ostr);
1464 [ # # ]: 0 : if (result < 0) {
1465 : 0 : goto fail;
1466 : : }
1467 : : }
1468 : 0 : AUTHORITY_INFO_ACCESS_free(info);
1469 : :
1470 : : /* convert to tuple or None */
1471 [ # # ]: 0 : if (PyList_Size(lst) == 0) {
1472 : 0 : Py_DECREF(lst);
1473 : 0 : return Py_None;
1474 : : } else {
1475 : : PyObject *tup;
1476 : 0 : tup = PyList_AsTuple(lst);
1477 : 0 : Py_DECREF(lst);
1478 : 0 : return tup;
1479 : : }
1480 : :
1481 : 0 : fail:
1482 : 0 : AUTHORITY_INFO_ACCESS_free(info);
1483 : 0 : Py_XDECREF(lst);
1484 : 0 : return NULL;
1485 : : }
1486 : :
1487 : : static PyObject *
1488 : 0 : _get_crl_dp(X509 *certificate) {
1489 : : STACK_OF(DIST_POINT) *dps;
1490 : : int i, j;
1491 : 0 : PyObject *lst, *res = NULL;
1492 : :
1493 : 0 : dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
1494 : :
1495 [ # # ]: 0 : if (dps == NULL)
1496 : 0 : return Py_None;
1497 : :
1498 : 0 : lst = PyList_New(0);
1499 [ # # ]: 0 : if (lst == NULL)
1500 : 0 : goto done;
1501 : :
1502 [ # # ]: 0 : for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1503 : : DIST_POINT *dp;
1504 : : STACK_OF(GENERAL_NAME) *gns;
1505 : :
1506 : 0 : dp = sk_DIST_POINT_value(dps, i);
1507 [ # # ]: 0 : if (dp->distpoint == NULL) {
1508 : : /* Ignore empty DP value, CVE-2019-5010 */
1509 : 0 : continue;
1510 : : }
1511 : 0 : gns = dp->distpoint->name.fullname;
1512 : :
1513 [ # # ]: 0 : for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1514 : : GENERAL_NAME *gn;
1515 : : ASN1_IA5STRING *uri;
1516 : : PyObject *ouri;
1517 : : int err;
1518 : :
1519 : 0 : gn = sk_GENERAL_NAME_value(gns, j);
1520 [ # # ]: 0 : if (gn->type != GEN_URI) {
1521 : 0 : continue;
1522 : : }
1523 : 0 : uri = gn->d.uniformResourceIdentifier;
1524 : 0 : ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1525 : 0 : uri->length);
1526 [ # # ]: 0 : if (ouri == NULL)
1527 : 0 : goto done;
1528 : :
1529 : 0 : err = PyList_Append(lst, ouri);
1530 : 0 : Py_DECREF(ouri);
1531 [ # # ]: 0 : if (err < 0)
1532 : 0 : goto done;
1533 : : }
1534 : : }
1535 : :
1536 : : /* Convert to tuple. */
1537 [ # # ]: 0 : res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1538 : :
1539 : 0 : done:
1540 : 0 : Py_XDECREF(lst);
1541 : 0 : CRL_DIST_POINTS_free(dps);
1542 : 0 : return res;
1543 : : }
1544 : :
1545 : : static PyObject *
1546 : 0 : _decode_certificate(_sslmodulestate *state, X509 *certificate) {
1547 : :
1548 : 0 : PyObject *retval = NULL;
1549 : 0 : BIO *biobuf = NULL;
1550 : : PyObject *peer;
1551 : 0 : PyObject *peer_alt_names = NULL;
1552 : : PyObject *issuer;
1553 : : PyObject *version;
1554 : : PyObject *sn_obj;
1555 : : PyObject *obj;
1556 : : ASN1_INTEGER *serialNumber;
1557 : : char buf[2048];
1558 : : int len, result;
1559 : : const ASN1_TIME *notBefore, *notAfter;
1560 : : PyObject *pnotBefore, *pnotAfter;
1561 : :
1562 : 0 : retval = PyDict_New();
1563 [ # # ]: 0 : if (retval == NULL)
1564 : 0 : return NULL;
1565 : :
1566 : 0 : peer = _create_tuple_for_X509_NAME(
1567 : : state,
1568 : : X509_get_subject_name(certificate));
1569 [ # # ]: 0 : if (peer == NULL)
1570 : 0 : goto fail0;
1571 [ # # ]: 0 : if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1572 : 0 : Py_DECREF(peer);
1573 : 0 : goto fail0;
1574 : : }
1575 : 0 : Py_DECREF(peer);
1576 : :
1577 : 0 : issuer = _create_tuple_for_X509_NAME(
1578 : : state,
1579 : : X509_get_issuer_name(certificate));
1580 [ # # ]: 0 : if (issuer == NULL)
1581 : 0 : goto fail0;
1582 [ # # ]: 0 : if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
1583 : 0 : Py_DECREF(issuer);
1584 : 0 : goto fail0;
1585 : : }
1586 : 0 : Py_DECREF(issuer);
1587 : :
1588 : 0 : version = PyLong_FromLong(X509_get_version(certificate) + 1);
1589 [ # # ]: 0 : if (version == NULL)
1590 : 0 : goto fail0;
1591 [ # # ]: 0 : if (PyDict_SetItemString(retval, "version", version) < 0) {
1592 : 0 : Py_DECREF(version);
1593 : 0 : goto fail0;
1594 : : }
1595 : 0 : Py_DECREF(version);
1596 : :
1597 : : /* get a memory buffer */
1598 : 0 : biobuf = BIO_new(BIO_s_mem());
1599 [ # # ]: 0 : if (biobuf == NULL) {
1600 : 0 : PyErr_SetString(state->PySSLErrorObject, "failed to allocate BIO");
1601 : 0 : goto fail0;
1602 : : }
1603 : :
1604 : 0 : (void) BIO_reset(biobuf);
1605 : 0 : serialNumber = X509_get_serialNumber(certificate);
1606 : : /* should not exceed 20 octets, 160 bits, so buf is big enough */
1607 : 0 : i2a_ASN1_INTEGER(biobuf, serialNumber);
1608 : 0 : len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1609 [ # # ]: 0 : if (len < 0) {
1610 : 0 : _setSSLError(state, NULL, 0, __FILE__, __LINE__);
1611 : 0 : goto fail1;
1612 : : }
1613 : 0 : sn_obj = PyUnicode_FromStringAndSize(buf, len);
1614 [ # # ]: 0 : if (sn_obj == NULL)
1615 : 0 : goto fail1;
1616 [ # # ]: 0 : if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1617 : 0 : Py_DECREF(sn_obj);
1618 : 0 : goto fail1;
1619 : : }
1620 : 0 : Py_DECREF(sn_obj);
1621 : :
1622 : 0 : (void) BIO_reset(biobuf);
1623 : 0 : notBefore = X509_get0_notBefore(certificate);
1624 : 0 : ASN1_TIME_print(biobuf, notBefore);
1625 : 0 : len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1626 [ # # ]: 0 : if (len < 0) {
1627 : 0 : _setSSLError(state, NULL, 0, __FILE__, __LINE__);
1628 : 0 : goto fail1;
1629 : : }
1630 : 0 : pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1631 [ # # ]: 0 : if (pnotBefore == NULL)
1632 : 0 : goto fail1;
1633 [ # # ]: 0 : if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1634 : 0 : Py_DECREF(pnotBefore);
1635 : 0 : goto fail1;
1636 : : }
1637 : 0 : Py_DECREF(pnotBefore);
1638 : :
1639 : 0 : (void) BIO_reset(biobuf);
1640 : 0 : notAfter = X509_get0_notAfter(certificate);
1641 : 0 : ASN1_TIME_print(biobuf, notAfter);
1642 : 0 : len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1643 [ # # ]: 0 : if (len < 0) {
1644 : 0 : _setSSLError(state, NULL, 0, __FILE__, __LINE__);
1645 : 0 : goto fail1;
1646 : : }
1647 : 0 : pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1648 [ # # ]: 0 : if (pnotAfter == NULL)
1649 : 0 : goto fail1;
1650 [ # # ]: 0 : if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1651 : 0 : Py_DECREF(pnotAfter);
1652 : 0 : goto fail1;
1653 : : }
1654 : 0 : Py_DECREF(pnotAfter);
1655 : :
1656 : : /* Now look for subjectAltName */
1657 : :
1658 : 0 : peer_alt_names = _get_peer_alt_names(state, certificate);
1659 [ # # ]: 0 : if (peer_alt_names == NULL)
1660 : 0 : goto fail1;
1661 [ # # ]: 0 : else if (peer_alt_names != Py_None) {
1662 [ # # ]: 0 : if (PyDict_SetItemString(retval, "subjectAltName",
1663 : : peer_alt_names) < 0) {
1664 : 0 : Py_DECREF(peer_alt_names);
1665 : 0 : goto fail1;
1666 : : }
1667 : 0 : Py_DECREF(peer_alt_names);
1668 : : }
1669 : :
1670 : : /* Authority Information Access: OCSP URIs */
1671 : 0 : obj = _get_aia_uri(certificate, NID_ad_OCSP);
1672 [ # # ]: 0 : if (obj == NULL) {
1673 : 0 : goto fail1;
1674 [ # # ]: 0 : } else if (obj != Py_None) {
1675 : 0 : result = PyDict_SetItemString(retval, "OCSP", obj);
1676 : 0 : Py_DECREF(obj);
1677 [ # # ]: 0 : if (result < 0) {
1678 : 0 : goto fail1;
1679 : : }
1680 : : }
1681 : :
1682 : 0 : obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1683 [ # # ]: 0 : if (obj == NULL) {
1684 : 0 : goto fail1;
1685 [ # # ]: 0 : } else if (obj != Py_None) {
1686 : 0 : result = PyDict_SetItemString(retval, "caIssuers", obj);
1687 : 0 : Py_DECREF(obj);
1688 [ # # ]: 0 : if (result < 0) {
1689 : 0 : goto fail1;
1690 : : }
1691 : : }
1692 : :
1693 : : /* CDP (CRL distribution points) */
1694 : 0 : obj = _get_crl_dp(certificate);
1695 [ # # ]: 0 : if (obj == NULL) {
1696 : 0 : goto fail1;
1697 [ # # ]: 0 : } else if (obj != Py_None) {
1698 : 0 : result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1699 : 0 : Py_DECREF(obj);
1700 [ # # ]: 0 : if (result < 0) {
1701 : 0 : goto fail1;
1702 : : }
1703 : : }
1704 : :
1705 : 0 : BIO_free(biobuf);
1706 : 0 : return retval;
1707 : :
1708 : 0 : fail1:
1709 [ # # ]: 0 : if (biobuf != NULL)
1710 : 0 : BIO_free(biobuf);
1711 : 0 : fail0:
1712 : 0 : Py_XDECREF(retval);
1713 : 0 : return NULL;
1714 : : }
1715 : :
1716 : : static PyObject *
1717 : 0 : _certificate_to_der(_sslmodulestate *state, X509 *certificate)
1718 : : {
1719 : 0 : unsigned char *bytes_buf = NULL;
1720 : : int len;
1721 : : PyObject *retval;
1722 : :
1723 : 0 : bytes_buf = NULL;
1724 : 0 : len = i2d_X509(certificate, &bytes_buf);
1725 [ # # ]: 0 : if (len < 0) {
1726 : 0 : _setSSLError(state, NULL, 0, __FILE__, __LINE__);
1727 : 0 : return NULL;
1728 : : }
1729 : : /* this is actually an immutable bytes sequence */
1730 : 0 : retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1731 : 0 : OPENSSL_free(bytes_buf);
1732 : 0 : return retval;
1733 : : }
1734 : :
1735 : : #include "_ssl/misc.c"
1736 : : #include "_ssl/cert.c"
1737 : :
1738 : : /*[clinic input]
1739 : : _ssl._test_decode_cert
1740 : : path: object(converter="PyUnicode_FSConverter")
1741 : : /
1742 : :
1743 : : [clinic start generated code]*/
1744 : :
1745 : : static PyObject *
1746 : 0 : _ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1747 : : /*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
1748 : : {
1749 : 0 : PyObject *retval = NULL;
1750 : 0 : X509 *x=NULL;
1751 : : BIO *cert;
1752 : 0 : _sslmodulestate *state = get_ssl_state(module);
1753 : :
1754 [ # # ]: 0 : if ((cert=BIO_new(BIO_s_file())) == NULL) {
1755 : 0 : PyErr_SetString(state->PySSLErrorObject,
1756 : : "Can't malloc memory to read file");
1757 : 0 : goto fail0;
1758 : : }
1759 : :
1760 [ # # ]: 0 : if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
1761 : 0 : PyErr_SetString(state->PySSLErrorObject,
1762 : : "Can't open file");
1763 : 0 : goto fail0;
1764 : : }
1765 : :
1766 : 0 : x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
1767 [ # # ]: 0 : if (x == NULL) {
1768 : 0 : PyErr_SetString(state->PySSLErrorObject,
1769 : : "Error decoding PEM-encoded file");
1770 : 0 : goto fail0;
1771 : : }
1772 : :
1773 : 0 : retval = _decode_certificate(state, x);
1774 : 0 : X509_free(x);
1775 : :
1776 : 0 : fail0:
1777 : 0 : Py_DECREF(path);
1778 [ # # ]: 0 : if (cert != NULL) BIO_free(cert);
1779 : 0 : return retval;
1780 : : }
1781 : :
1782 : :
1783 : : /*[clinic input]
1784 : : _ssl._SSLSocket.getpeercert
1785 : : der as binary_mode: bool = False
1786 : : /
1787 : :
1788 : : Returns the certificate for the peer.
1789 : :
1790 : : If no certificate was provided, returns None. If a certificate was
1791 : : provided, but not validated, returns an empty dictionary. Otherwise
1792 : : returns a dict containing information about the peer certificate.
1793 : :
1794 : : If the optional argument is True, returns a DER-encoded copy of the
1795 : : peer certificate, or None if no certificate was provided. This will
1796 : : return the certificate even if it wasn't validated.
1797 : : [clinic start generated code]*/
1798 : :
1799 : : static PyObject *
1800 : 0 : _ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1801 : : /*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
1802 : : {
1803 : : int verification;
1804 : : X509 *peer_cert;
1805 : : PyObject *result;
1806 : :
1807 [ # # ]: 0 : if (!SSL_is_init_finished(self->ssl)) {
1808 : 0 : PyErr_SetString(PyExc_ValueError,
1809 : : "handshake not done yet");
1810 : 0 : return NULL;
1811 : : }
1812 : 0 : peer_cert = SSL_get_peer_certificate(self->ssl);
1813 [ # # ]: 0 : if (peer_cert == NULL)
1814 : 0 : Py_RETURN_NONE;
1815 : :
1816 [ # # ]: 0 : if (binary_mode) {
1817 : : /* return cert in DER-encoded format */
1818 : 0 : result = _certificate_to_der(get_state_sock(self), peer_cert);
1819 : : } else {
1820 : 0 : verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
1821 [ # # ]: 0 : if ((verification & SSL_VERIFY_PEER) == 0)
1822 : 0 : result = PyDict_New();
1823 : : else
1824 : 0 : result = _decode_certificate(get_state_sock(self), peer_cert);
1825 : : }
1826 : 0 : X509_free(peer_cert);
1827 : 0 : return result;
1828 : : }
1829 : :
1830 : : /*[clinic input]
1831 : : _ssl._SSLSocket.get_verified_chain
1832 : :
1833 : : [clinic start generated code]*/
1834 : :
1835 : : static PyObject *
1836 : 0 : _ssl__SSLSocket_get_verified_chain_impl(PySSLSocket *self)
1837 : : /*[clinic end generated code: output=802421163cdc3110 input=5fb0714f77e2bd51]*/
1838 : : {
1839 : : /* borrowed reference */
1840 : 0 : STACK_OF(X509) *chain = SSL_get0_verified_chain(self->ssl);
1841 [ # # ]: 0 : if (chain == NULL) {
1842 : 0 : Py_RETURN_NONE;
1843 : : }
1844 : 0 : return _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
1845 : : }
1846 : :
1847 : : /*[clinic input]
1848 : : _ssl._SSLSocket.get_unverified_chain
1849 : :
1850 : : [clinic start generated code]*/
1851 : :
1852 : : static PyObject *
1853 : 0 : _ssl__SSLSocket_get_unverified_chain_impl(PySSLSocket *self)
1854 : : /*[clinic end generated code: output=5acdae414e13f913 input=78c33c360c635cb5]*/
1855 : : {
1856 : : PyObject *retval;
1857 : : /* borrowed reference */
1858 : : /* TODO: include SSL_get_peer_certificate() for server-side sockets */
1859 : 0 : STACK_OF(X509) *chain = SSL_get_peer_cert_chain(self->ssl);
1860 [ # # ]: 0 : if (chain == NULL) {
1861 : 0 : Py_RETURN_NONE;
1862 : : }
1863 : 0 : retval = _PySSL_CertificateFromX509Stack(self->ctx->state, chain, 1);
1864 [ # # ]: 0 : if (retval == NULL) {
1865 : 0 : return NULL;
1866 : : }
1867 : : /* OpenSSL does not include peer cert for server side connections */
1868 [ # # ]: 0 : if (self->socket_type == PY_SSL_SERVER) {
1869 : 0 : PyObject *peerobj = NULL;
1870 : 0 : X509 *peer = SSL_get_peer_certificate(self->ssl);
1871 : :
1872 [ # # ]: 0 : if (peer == NULL) {
1873 : 0 : peerobj = Py_NewRef(Py_None);
1874 : : } else {
1875 : : /* consume X509 reference on success */
1876 : 0 : peerobj = _PySSL_CertificateFromX509(self->ctx->state, peer, 0);
1877 [ # # ]: 0 : if (peerobj == NULL) {
1878 : 0 : X509_free(peer);
1879 : 0 : Py_DECREF(retval);
1880 : 0 : return NULL;
1881 : : }
1882 : : }
1883 : 0 : int res = PyList_Insert(retval, 0, peerobj);
1884 : 0 : Py_DECREF(peerobj);
1885 [ # # ]: 0 : if (res < 0) {
1886 : 0 : Py_DECREF(retval);
1887 : 0 : return NULL;
1888 : : }
1889 : : }
1890 : 0 : return retval;
1891 : : }
1892 : :
1893 : : static PyObject *
1894 : 0 : cipher_to_tuple(const SSL_CIPHER *cipher)
1895 : : {
1896 : : const char *cipher_name, *cipher_protocol;
1897 : 0 : PyObject *v, *retval = PyTuple_New(3);
1898 [ # # ]: 0 : if (retval == NULL)
1899 : 0 : return NULL;
1900 : :
1901 : 0 : cipher_name = SSL_CIPHER_get_name(cipher);
1902 [ # # ]: 0 : if (cipher_name == NULL) {
1903 : 0 : PyTuple_SET_ITEM(retval, 0, Py_NewRef(Py_None));
1904 : : } else {
1905 : 0 : v = PyUnicode_FromString(cipher_name);
1906 [ # # ]: 0 : if (v == NULL)
1907 : 0 : goto fail;
1908 : 0 : PyTuple_SET_ITEM(retval, 0, v);
1909 : : }
1910 : :
1911 : 0 : cipher_protocol = SSL_CIPHER_get_version(cipher);
1912 [ # # ]: 0 : if (cipher_protocol == NULL) {
1913 : 0 : PyTuple_SET_ITEM(retval, 1, Py_NewRef(Py_None));
1914 : : } else {
1915 : 0 : v = PyUnicode_FromString(cipher_protocol);
1916 [ # # ]: 0 : if (v == NULL)
1917 : 0 : goto fail;
1918 : 0 : PyTuple_SET_ITEM(retval, 1, v);
1919 : : }
1920 : :
1921 : 0 : v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
1922 [ # # ]: 0 : if (v == NULL)
1923 : 0 : goto fail;
1924 : 0 : PyTuple_SET_ITEM(retval, 2, v);
1925 : :
1926 : 0 : return retval;
1927 : :
1928 : 0 : fail:
1929 : 0 : Py_DECREF(retval);
1930 : 0 : return NULL;
1931 : : }
1932 : :
1933 : : static PyObject *
1934 : 0 : cipher_to_dict(const SSL_CIPHER *cipher)
1935 : : {
1936 : : const char *cipher_name, *cipher_protocol;
1937 : :
1938 : : unsigned long cipher_id;
1939 : : int alg_bits, strength_bits, len;
1940 : 0 : char buf[512] = {0};
1941 : : int aead, nid;
1942 : 0 : const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1943 : :
1944 : : /* can be NULL */
1945 : 0 : cipher_name = SSL_CIPHER_get_name(cipher);
1946 : 0 : cipher_protocol = SSL_CIPHER_get_version(cipher);
1947 : 0 : cipher_id = SSL_CIPHER_get_id(cipher);
1948 : 0 : SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1949 : : /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1950 : 0 : len = (int)strlen(buf);
1951 [ # # # # ]: 0 : if (len > 1 && buf[len-1] == '\n')
1952 : 0 : buf[len-1] = '\0';
1953 : 0 : strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1954 : :
1955 : 0 : aead = SSL_CIPHER_is_aead(cipher);
1956 : 0 : nid = SSL_CIPHER_get_cipher_nid(cipher);
1957 [ # # ]: 0 : skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1958 : 0 : nid = SSL_CIPHER_get_digest_nid(cipher);
1959 [ # # ]: 0 : digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1960 : 0 : nid = SSL_CIPHER_get_kx_nid(cipher);
1961 [ # # ]: 0 : kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1962 : 0 : nid = SSL_CIPHER_get_auth_nid(cipher);
1963 [ # # ]: 0 : auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1964 : :
1965 [ # # ]: 0 : return Py_BuildValue(
1966 : : "{sksssssssisi"
1967 : : "sOssssssss"
1968 : : "}",
1969 : : "id", cipher_id,
1970 : : "name", cipher_name,
1971 : : "protocol", cipher_protocol,
1972 : : "description", buf,
1973 : : "strength_bits", strength_bits,
1974 : : "alg_bits", alg_bits
1975 : : ,"aead", aead ? Py_True : Py_False,
1976 : : "symmetric", skcipher,
1977 : : "digest", digest,
1978 : : "kea", kx,
1979 : : "auth", auth
1980 : : );
1981 : : }
1982 : :
1983 : : /*[clinic input]
1984 : : _ssl._SSLSocket.shared_ciphers
1985 : : [clinic start generated code]*/
1986 : :
1987 : : static PyObject *
1988 : 0 : _ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1989 : : /*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
1990 : : {
1991 : : STACK_OF(SSL_CIPHER) *ciphers;
1992 : : int i;
1993 : : PyObject *res;
1994 : :
1995 : 0 : ciphers = SSL_get_ciphers(self->ssl);
1996 [ # # ]: 0 : if (!ciphers)
1997 : 0 : Py_RETURN_NONE;
1998 : 0 : res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1999 [ # # ]: 0 : if (!res)
2000 : 0 : return NULL;
2001 [ # # ]: 0 : for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2002 : 0 : PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
2003 [ # # ]: 0 : if (!tup) {
2004 : 0 : Py_DECREF(res);
2005 : 0 : return NULL;
2006 : : }
2007 : 0 : PyList_SET_ITEM(res, i, tup);
2008 : : }
2009 : 0 : return res;
2010 : : }
2011 : :
2012 : : /*[clinic input]
2013 : : _ssl._SSLSocket.cipher
2014 : : [clinic start generated code]*/
2015 : :
2016 : : static PyObject *
2017 : 0 : _ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2018 : : /*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
2019 : : {
2020 : : const SSL_CIPHER *current;
2021 : :
2022 [ # # ]: 0 : if (self->ssl == NULL)
2023 : 0 : Py_RETURN_NONE;
2024 : 0 : current = SSL_get_current_cipher(self->ssl);
2025 [ # # ]: 0 : if (current == NULL)
2026 : 0 : Py_RETURN_NONE;
2027 : 0 : return cipher_to_tuple(current);
2028 : : }
2029 : :
2030 : : /*[clinic input]
2031 : : _ssl._SSLSocket.version
2032 : : [clinic start generated code]*/
2033 : :
2034 : : static PyObject *
2035 : 0 : _ssl__SSLSocket_version_impl(PySSLSocket *self)
2036 : : /*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
2037 : : {
2038 : : const char *version;
2039 : :
2040 [ # # ]: 0 : if (self->ssl == NULL)
2041 : 0 : Py_RETURN_NONE;
2042 [ # # ]: 0 : if (!SSL_is_init_finished(self->ssl)) {
2043 : : /* handshake not finished */
2044 : 0 : Py_RETURN_NONE;
2045 : : }
2046 : 0 : version = SSL_get_version(self->ssl);
2047 [ # # ]: 0 : if (!strcmp(version, "unknown"))
2048 : 0 : Py_RETURN_NONE;
2049 : 0 : return PyUnicode_FromString(version);
2050 : : }
2051 : :
2052 : : /*[clinic input]
2053 : : _ssl._SSLSocket.selected_alpn_protocol
2054 : : [clinic start generated code]*/
2055 : :
2056 : : static PyObject *
2057 : 0 : _ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2058 : : /*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2059 : : {
2060 : : const unsigned char *out;
2061 : : unsigned int outlen;
2062 : :
2063 : 0 : SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2064 : :
2065 [ # # ]: 0 : if (out == NULL)
2066 : 0 : Py_RETURN_NONE;
2067 : 0 : return PyUnicode_FromStringAndSize((char *)out, outlen);
2068 : : }
2069 : :
2070 : : /*[clinic input]
2071 : : _ssl._SSLSocket.compression
2072 : : [clinic start generated code]*/
2073 : :
2074 : : static PyObject *
2075 : 0 : _ssl__SSLSocket_compression_impl(PySSLSocket *self)
2076 : : /*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2077 : : {
2078 : : #ifdef OPENSSL_NO_COMP
2079 : : Py_RETURN_NONE;
2080 : : #else
2081 : : const COMP_METHOD *comp_method;
2082 : : const char *short_name;
2083 : :
2084 [ # # ]: 0 : if (self->ssl == NULL)
2085 : 0 : Py_RETURN_NONE;
2086 : 0 : comp_method = SSL_get_current_compression(self->ssl);
2087 [ # # # # ]: 0 : if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
2088 : 0 : Py_RETURN_NONE;
2089 : 0 : short_name = OBJ_nid2sn(COMP_get_type(comp_method));
2090 [ # # ]: 0 : if (short_name == NULL)
2091 : 0 : Py_RETURN_NONE;
2092 : 0 : return PyUnicode_DecodeFSDefault(short_name);
2093 : : #endif
2094 : : }
2095 : :
2096 : 0 : static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2097 : 0 : return (PySSLContext*)Py_NewRef(self->ctx);
2098 : : }
2099 : :
2100 : 0 : static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2101 : : void *closure) {
2102 : :
2103 [ # # ]: 0 : if (PyObject_TypeCheck(value, self->ctx->state->PySSLContext_Type)) {
2104 : 0 : Py_SETREF(self->ctx, (PySSLContext *)Py_NewRef(value));
2105 : 0 : SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
2106 : : /* Set SSL* internal msg_callback to state of new context's state */
2107 : 0 : SSL_set_msg_callback(
2108 : : self->ssl,
2109 [ # # ]: 0 : self->ctx->msg_cb ? _PySSL_msg_callback : NULL
2110 : : );
2111 : : } else {
2112 : 0 : PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
2113 : 0 : return -1;
2114 : : }
2115 : :
2116 : 0 : return 0;
2117 : : }
2118 : :
2119 : : PyDoc_STRVAR(PySSL_set_context_doc,
2120 : : "_setter_context(ctx)\n\
2121 : : \
2122 : : This changes the context associated with the SSLSocket. This is typically\n\
2123 : : used from within a callback function set by the sni_callback\n\
2124 : : on the SSLContext to change the certificate information associated with the\n\
2125 : : SSLSocket before the cryptographic exchange handshake messages\n");
2126 : :
2127 : :
2128 : : static PyObject *
2129 : 0 : PySSL_get_server_side(PySSLSocket *self, void *c)
2130 : : {
2131 : 0 : return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2132 : : }
2133 : :
2134 : : PyDoc_STRVAR(PySSL_get_server_side_doc,
2135 : : "Whether this is a server-side socket.");
2136 : :
2137 : : static PyObject *
2138 : 0 : PySSL_get_server_hostname(PySSLSocket *self, void *c)
2139 : : {
2140 [ # # ]: 0 : if (self->server_hostname == NULL)
2141 : 0 : Py_RETURN_NONE;
2142 : 0 : return Py_NewRef(self->server_hostname);
2143 : : }
2144 : :
2145 : : PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2146 : : "The currently set server hostname (for SNI).");
2147 : :
2148 : : static PyObject *
2149 : 0 : PySSL_get_owner(PySSLSocket *self, void *c)
2150 : : {
2151 : : PyObject *owner;
2152 : :
2153 [ # # ]: 0 : if (self->owner == NULL)
2154 : 0 : Py_RETURN_NONE;
2155 : :
2156 : 0 : owner = PyWeakref_GetObject(self->owner);
2157 : 0 : return Py_NewRef(owner);
2158 : : }
2159 : :
2160 : : static int
2161 : 0 : PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2162 : : {
2163 : 0 : Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
2164 [ # # ]: 0 : if (self->owner == NULL)
2165 : 0 : return -1;
2166 : 0 : return 0;
2167 : : }
2168 : :
2169 : : PyDoc_STRVAR(PySSL_get_owner_doc,
2170 : : "The Python-level owner of this object.\
2171 : : Passed as \"self\" in servername callback.");
2172 : :
2173 : : static int
2174 : 0 : PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2175 : : {
2176 [ # # # # ]: 0 : Py_VISIT(self->exc);
2177 [ # # # # ]: 0 : Py_VISIT(Py_TYPE(self));
2178 : 0 : return 0;
2179 : : }
2180 : :
2181 : : static int
2182 : 0 : PySSL_clear(PySSLSocket *self)
2183 : : {
2184 [ # # ]: 0 : Py_CLEAR(self->exc);
2185 : 0 : return 0;
2186 : : }
2187 : :
2188 : : static void
2189 : 0 : PySSL_dealloc(PySSLSocket *self)
2190 : : {
2191 : 0 : PyTypeObject *tp = Py_TYPE(self);
2192 : 0 : PyObject_GC_UnTrack(self);
2193 [ # # ]: 0 : if (self->ssl) {
2194 : 0 : SSL_free(self->ssl);
2195 : : }
2196 : 0 : Py_XDECREF(self->Socket);
2197 : 0 : Py_XDECREF(self->ctx);
2198 : 0 : Py_XDECREF(self->server_hostname);
2199 : 0 : Py_XDECREF(self->owner);
2200 : 0 : PyObject_GC_Del(self);
2201 : 0 : Py_DECREF(tp);
2202 : 0 : }
2203 : :
2204 : : /* If the socket has a timeout, do a select()/poll() on the socket.
2205 : : The argument writing indicates the direction.
2206 : : Returns one of the possibilities in the timeout_state enum (above).
2207 : : */
2208 : :
2209 : : static int
2210 : 0 : PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
2211 : : {
2212 : : int rc;
2213 : : #ifdef HAVE_POLL
2214 : : struct pollfd pollfd;
2215 : : _PyTime_t ms;
2216 : : #else
2217 : : int nfds;
2218 : : fd_set fds;
2219 : : struct timeval tv;
2220 : : #endif
2221 : :
2222 : : /* Nothing to do unless we're in timeout mode (not non-blocking) */
2223 [ # # # # ]: 0 : if ((s == NULL) || (timeout == 0))
2224 : 0 : return SOCKET_IS_NONBLOCKING;
2225 [ # # ]: 0 : else if (timeout < 0) {
2226 [ # # ]: 0 : if (s->sock_timeout > 0)
2227 : 0 : return SOCKET_HAS_TIMED_OUT;
2228 : : else
2229 : 0 : return SOCKET_IS_BLOCKING;
2230 : : }
2231 : :
2232 : : /* Guard against closed socket */
2233 [ # # ]: 0 : if (s->sock_fd == INVALID_SOCKET)
2234 : 0 : return SOCKET_HAS_BEEN_CLOSED;
2235 : :
2236 : : /* Prefer poll, if available, since you can poll() any fd
2237 : : * which can't be done with select(). */
2238 : : #ifdef HAVE_POLL
2239 : 0 : pollfd.fd = s->sock_fd;
2240 [ # # ]: 0 : pollfd.events = writing ? POLLOUT : POLLIN;
2241 : :
2242 : : /* timeout is in seconds, poll() uses milliseconds */
2243 : 0 : ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
2244 : : assert(ms <= INT_MAX);
2245 : :
2246 : 0 : PySSL_BEGIN_ALLOW_THREADS
2247 : 0 : rc = poll(&pollfd, 1, (int)ms);
2248 : 0 : PySSL_END_ALLOW_THREADS
2249 : : #else
2250 : : /* Guard against socket too large for select*/
2251 : : if (!_PyIsSelectable_fd(s->sock_fd))
2252 : : return SOCKET_TOO_LARGE_FOR_SELECT;
2253 : :
2254 : : _PyTime_AsTimeval_clamp(timeout, &tv, _PyTime_ROUND_CEILING);
2255 : :
2256 : : FD_ZERO(&fds);
2257 : : FD_SET(s->sock_fd, &fds);
2258 : :
2259 : : /* Wait until the socket becomes ready */
2260 : : PySSL_BEGIN_ALLOW_THREADS
2261 : : nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
2262 : : if (writing)
2263 : : rc = select(nfds, NULL, &fds, NULL, &tv);
2264 : : else
2265 : : rc = select(nfds, &fds, NULL, NULL, &tv);
2266 : : PySSL_END_ALLOW_THREADS
2267 : : #endif
2268 : :
2269 : : /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2270 : : (when we are able to write or when there's something to read) */
2271 [ # # ]: 0 : return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
2272 : : }
2273 : :
2274 : : /*[clinic input]
2275 : : _ssl._SSLSocket.write
2276 : : b: Py_buffer
2277 : : /
2278 : :
2279 : : Writes the bytes-like object b into the SSL object.
2280 : :
2281 : : Returns the number of bytes written.
2282 : : [clinic start generated code]*/
2283 : :
2284 : : static PyObject *
2285 : 0 : _ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2286 : : /*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
2287 : : {
2288 : 0 : size_t count = 0;
2289 : : int retval;
2290 : : int sockstate;
2291 : : _PySSLError err;
2292 : : int nonblocking;
2293 [ # # ]: 0 : PySocketSockObject *sock = GET_SOCKET(self);
2294 : 0 : _PyTime_t timeout, deadline = 0;
2295 : : int has_timeout;
2296 : :
2297 [ # # ]: 0 : if (sock != NULL) {
2298 [ # # ]: 0 : if (((PyObject*)sock) == Py_None) {
2299 : 0 : _setSSLError(get_state_sock(self),
2300 : : "Underlying socket connection gone",
2301 : : PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2302 : 0 : return NULL;
2303 : : }
2304 : 0 : Py_INCREF(sock);
2305 : : }
2306 : :
2307 [ # # ]: 0 : if (sock != NULL) {
2308 : : /* just in case the blocking state of the socket has been changed */
2309 : 0 : nonblocking = (sock->sock_timeout >= 0);
2310 : 0 : BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2311 : 0 : BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2312 : : }
2313 : :
2314 [ # # ]: 0 : timeout = GET_SOCKET_TIMEOUT(sock);
2315 : 0 : has_timeout = (timeout > 0);
2316 [ # # ]: 0 : if (has_timeout) {
2317 : 0 : deadline = _PyDeadline_Init(timeout);
2318 : : }
2319 : :
2320 : 0 : sockstate = PySSL_select(sock, 1, timeout);
2321 [ # # ]: 0 : if (sockstate == SOCKET_HAS_TIMED_OUT) {
2322 : 0 : PyErr_SetString(PyExc_TimeoutError,
2323 : : "The write operation timed out");
2324 : 0 : goto error;
2325 [ # # ]: 0 : } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2326 : 0 : PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
2327 : : "Underlying socket has been closed.");
2328 : 0 : goto error;
2329 [ # # ]: 0 : } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2330 : 0 : PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
2331 : : "Underlying socket too large for select().");
2332 : 0 : goto error;
2333 : : }
2334 : :
2335 : : do {
2336 : 0 : PySSL_BEGIN_ALLOW_THREADS
2337 : 0 : retval = SSL_write_ex(self->ssl, b->buf, (size_t)b->len, &count);
2338 : 0 : err = _PySSL_errno(retval == 0, self->ssl, retval);
2339 : 0 : PySSL_END_ALLOW_THREADS
2340 : 0 : self->err = err;
2341 : :
2342 [ # # ]: 0 : if (PyErr_CheckSignals())
2343 : 0 : goto error;
2344 : :
2345 [ # # ]: 0 : if (has_timeout) {
2346 : 0 : timeout = _PyDeadline_Get(deadline);
2347 : : }
2348 : :
2349 [ # # ]: 0 : if (err.ssl == SSL_ERROR_WANT_READ) {
2350 : 0 : sockstate = PySSL_select(sock, 0, timeout);
2351 [ # # ]: 0 : } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
2352 : 0 : sockstate = PySSL_select(sock, 1, timeout);
2353 : : } else {
2354 : 0 : sockstate = SOCKET_OPERATION_OK;
2355 : : }
2356 : :
2357 [ # # ]: 0 : if (sockstate == SOCKET_HAS_TIMED_OUT) {
2358 : 0 : PyErr_SetString(PyExc_TimeoutError,
2359 : : "The write operation timed out");
2360 : 0 : goto error;
2361 [ # # ]: 0 : } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2362 : 0 : PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
2363 : : "Underlying socket has been closed.");
2364 : 0 : goto error;
2365 [ # # ]: 0 : } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2366 : 0 : break;
2367 : : }
2368 : 0 : } while (err.ssl == SSL_ERROR_WANT_READ ||
2369 [ # # # # ]: 0 : err.ssl == SSL_ERROR_WANT_WRITE);
2370 : :
2371 : 0 : Py_XDECREF(sock);
2372 [ # # ]: 0 : if (retval == 0)
2373 : 0 : return PySSL_SetError(self, retval, __FILE__, __LINE__);
2374 [ # # ]: 0 : if (PySSL_ChainExceptions(self) < 0)
2375 : 0 : return NULL;
2376 : 0 : return PyLong_FromSize_t(count);
2377 : 0 : error:
2378 : 0 : Py_XDECREF(sock);
2379 : 0 : PySSL_ChainExceptions(self);
2380 : 0 : return NULL;
2381 : : }
2382 : :
2383 : : /*[clinic input]
2384 : : _ssl._SSLSocket.pending
2385 : :
2386 : : Returns the number of already decrypted bytes available for read, pending on the connection.
2387 : : [clinic start generated code]*/
2388 : :
2389 : : static PyObject *
2390 : 0 : _ssl__SSLSocket_pending_impl(PySSLSocket *self)
2391 : : /*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
2392 : : {
2393 : 0 : int count = 0;
2394 : : _PySSLError err;
2395 : :
2396 : 0 : PySSL_BEGIN_ALLOW_THREADS
2397 : 0 : count = SSL_pending(self->ssl);
2398 : 0 : err = _PySSL_errno(count < 0, self->ssl, count);
2399 : 0 : PySSL_END_ALLOW_THREADS
2400 : 0 : self->err = err;
2401 : :
2402 [ # # ]: 0 : if (count < 0)
2403 : 0 : return PySSL_SetError(self, count, __FILE__, __LINE__);
2404 : : else
2405 : 0 : return PyLong_FromLong(count);
2406 : : }
2407 : :
2408 : : /*[clinic input]
2409 : : _ssl._SSLSocket.read
2410 : : size as len: Py_ssize_t
2411 : : [
2412 : : buffer: Py_buffer(accept={rwbuffer})
2413 : : ]
2414 : : /
2415 : :
2416 : : Read up to size bytes from the SSL socket.
2417 : : [clinic start generated code]*/
2418 : :
2419 : : static PyObject *
2420 : 0 : _ssl__SSLSocket_read_impl(PySSLSocket *self, Py_ssize_t len,
2421 : : int group_right_1, Py_buffer *buffer)
2422 : : /*[clinic end generated code: output=49b16e6406023734 input=ec48bf622be1c4a1]*/
2423 : : {
2424 : 0 : PyObject *dest = NULL;
2425 : : char *mem;
2426 : 0 : size_t count = 0;
2427 : : int retval;
2428 : : int sockstate;
2429 : : _PySSLError err;
2430 : : int nonblocking;
2431 [ # # ]: 0 : PySocketSockObject *sock = GET_SOCKET(self);
2432 : 0 : _PyTime_t timeout, deadline = 0;
2433 : : int has_timeout;
2434 : :
2435 [ # # # # ]: 0 : if (!group_right_1 && len < 0) {
2436 : 0 : PyErr_SetString(PyExc_ValueError, "size should not be negative");
2437 : 0 : return NULL;
2438 : : }
2439 : :
2440 [ # # ]: 0 : if (sock != NULL) {
2441 [ # # ]: 0 : if (((PyObject*)sock) == Py_None) {
2442 : 0 : _setSSLError(get_state_sock(self),
2443 : : "Underlying socket connection gone",
2444 : : PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2445 : 0 : return NULL;
2446 : : }
2447 : 0 : Py_INCREF(sock);
2448 : : }
2449 : :
2450 [ # # ]: 0 : if (!group_right_1) {
2451 : 0 : dest = PyBytes_FromStringAndSize(NULL, len);
2452 [ # # ]: 0 : if (dest == NULL)
2453 : 0 : goto error;
2454 [ # # ]: 0 : if (len == 0) {
2455 : 0 : Py_XDECREF(sock);
2456 : 0 : return dest;
2457 : : }
2458 : 0 : mem = PyBytes_AS_STRING(dest);
2459 : : }
2460 : : else {
2461 : 0 : mem = buffer->buf;
2462 [ # # # # ]: 0 : if (len <= 0 || len > buffer->len) {
2463 : 0 : len = (int) buffer->len;
2464 [ # # ]: 0 : if (buffer->len != len) {
2465 : 0 : PyErr_SetString(PyExc_OverflowError,
2466 : : "maximum length can't fit in a C 'int'");
2467 : 0 : goto error;
2468 : : }
2469 [ # # ]: 0 : if (len == 0) {
2470 : 0 : count = 0;
2471 : 0 : goto done;
2472 : : }
2473 : : }
2474 : : }
2475 : :
2476 [ # # ]: 0 : if (sock != NULL) {
2477 : : /* just in case the blocking state of the socket has been changed */
2478 : 0 : nonblocking = (sock->sock_timeout >= 0);
2479 : 0 : BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2480 : 0 : BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2481 : : }
2482 : :
2483 [ # # ]: 0 : timeout = GET_SOCKET_TIMEOUT(sock);
2484 : 0 : has_timeout = (timeout > 0);
2485 [ # # ]: 0 : if (has_timeout)
2486 : 0 : deadline = _PyDeadline_Init(timeout);
2487 : :
2488 : : do {
2489 : 0 : PySSL_BEGIN_ALLOW_THREADS
2490 : 0 : retval = SSL_read_ex(self->ssl, mem, (size_t)len, &count);
2491 : 0 : err = _PySSL_errno(retval == 0, self->ssl, retval);
2492 : 0 : PySSL_END_ALLOW_THREADS
2493 : 0 : self->err = err;
2494 : :
2495 [ # # ]: 0 : if (PyErr_CheckSignals())
2496 : 0 : goto error;
2497 : :
2498 [ # # ]: 0 : if (has_timeout) {
2499 : 0 : timeout = _PyDeadline_Get(deadline);
2500 : : }
2501 : :
2502 [ # # ]: 0 : if (err.ssl == SSL_ERROR_WANT_READ) {
2503 : 0 : sockstate = PySSL_select(sock, 0, timeout);
2504 [ # # ]: 0 : } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
2505 : 0 : sockstate = PySSL_select(sock, 1, timeout);
2506 [ # # # # ]: 0 : } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
2507 : 0 : SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
2508 : : {
2509 : 0 : count = 0;
2510 : 0 : goto done;
2511 : : }
2512 : : else
2513 : 0 : sockstate = SOCKET_OPERATION_OK;
2514 : :
2515 [ # # ]: 0 : if (sockstate == SOCKET_HAS_TIMED_OUT) {
2516 : 0 : PyErr_SetString(PyExc_TimeoutError,
2517 : : "The read operation timed out");
2518 : 0 : goto error;
2519 [ # # ]: 0 : } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2520 : 0 : break;
2521 : : }
2522 : 0 : } while (err.ssl == SSL_ERROR_WANT_READ ||
2523 [ # # # # ]: 0 : err.ssl == SSL_ERROR_WANT_WRITE);
2524 : :
2525 [ # # ]: 0 : if (retval == 0) {
2526 : 0 : PySSL_SetError(self, retval, __FILE__, __LINE__);
2527 : 0 : goto error;
2528 : : }
2529 [ # # ]: 0 : if (self->exc != NULL)
2530 : 0 : goto error;
2531 : :
2532 : 0 : done:
2533 : 0 : Py_XDECREF(sock);
2534 [ # # ]: 0 : if (!group_right_1) {
2535 : 0 : _PyBytes_Resize(&dest, count);
2536 : 0 : return dest;
2537 : : }
2538 : : else {
2539 : 0 : return PyLong_FromSize_t(count);
2540 : : }
2541 : :
2542 : 0 : error:
2543 : 0 : PySSL_ChainExceptions(self);
2544 : 0 : Py_XDECREF(sock);
2545 [ # # ]: 0 : if (!group_right_1)
2546 : 0 : Py_XDECREF(dest);
2547 : 0 : return NULL;
2548 : : }
2549 : :
2550 : : /*[clinic input]
2551 : : _ssl._SSLSocket.shutdown
2552 : :
2553 : : Does the SSL shutdown handshake with the remote end.
2554 : : [clinic start generated code]*/
2555 : :
2556 : : static PyObject *
2557 : 0 : _ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2558 : : /*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
2559 : : {
2560 : : _PySSLError err;
2561 : : int sockstate, nonblocking, ret;
2562 : 0 : int zeros = 0;
2563 [ # # ]: 0 : PySocketSockObject *sock = GET_SOCKET(self);
2564 : 0 : _PyTime_t timeout, deadline = 0;
2565 : : int has_timeout;
2566 : :
2567 [ # # ]: 0 : if (sock != NULL) {
2568 : : /* Guard against closed socket */
2569 [ # # # # ]: 0 : if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
2570 : 0 : _setSSLError(get_state_sock(self),
2571 : : "Underlying socket connection gone",
2572 : : PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2573 : 0 : return NULL;
2574 : : }
2575 : 0 : Py_INCREF(sock);
2576 : :
2577 : : /* Just in case the blocking state of the socket has been changed */
2578 : 0 : nonblocking = (sock->sock_timeout >= 0);
2579 : 0 : BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2580 : 0 : BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2581 : : }
2582 : :
2583 [ # # ]: 0 : timeout = GET_SOCKET_TIMEOUT(sock);
2584 : 0 : has_timeout = (timeout > 0);
2585 [ # # ]: 0 : if (has_timeout) {
2586 : 0 : deadline = _PyDeadline_Init(timeout);
2587 : : }
2588 : :
2589 : : while (1) {
2590 : 0 : PySSL_BEGIN_ALLOW_THREADS
2591 : : /* Disable read-ahead so that unwrap can work correctly.
2592 : : * Otherwise OpenSSL might read in too much data,
2593 : : * eating clear text data that happens to be
2594 : : * transmitted after the SSL shutdown.
2595 : : * Should be safe to call repeatedly every time this
2596 : : * function is used and the shutdown_seen_zero != 0
2597 : : * condition is met.
2598 : : */
2599 [ # # ]: 0 : if (self->shutdown_seen_zero)
2600 : 0 : SSL_set_read_ahead(self->ssl, 0);
2601 : 0 : ret = SSL_shutdown(self->ssl);
2602 : 0 : err = _PySSL_errno(ret < 0, self->ssl, ret);
2603 : 0 : PySSL_END_ALLOW_THREADS
2604 : 0 : self->err = err;
2605 : :
2606 : : /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2607 [ # # ]: 0 : if (ret > 0)
2608 : 0 : break;
2609 [ # # ]: 0 : if (ret == 0) {
2610 : : /* Don't loop endlessly; instead preserve legacy
2611 : : behaviour of trying SSL_shutdown() only twice.
2612 : : This looks necessary for OpenSSL < 0.9.8m */
2613 [ # # ]: 0 : if (++zeros > 1)
2614 : 0 : break;
2615 : : /* Shutdown was sent, now try receiving */
2616 : 0 : self->shutdown_seen_zero = 1;
2617 : 0 : continue;
2618 : : }
2619 : :
2620 [ # # ]: 0 : if (has_timeout) {
2621 : 0 : timeout = _PyDeadline_Get(deadline);
2622 : : }
2623 : :
2624 : : /* Possibly retry shutdown until timeout or failure */
2625 [ # # ]: 0 : if (err.ssl == SSL_ERROR_WANT_READ)
2626 : 0 : sockstate = PySSL_select(sock, 0, timeout);
2627 [ # # ]: 0 : else if (err.ssl == SSL_ERROR_WANT_WRITE)
2628 : 0 : sockstate = PySSL_select(sock, 1, timeout);
2629 : : else
2630 : 0 : break;
2631 : :
2632 [ # # ]: 0 : if (sockstate == SOCKET_HAS_TIMED_OUT) {
2633 [ # # ]: 0 : if (err.ssl == SSL_ERROR_WANT_READ)
2634 : 0 : PyErr_SetString(PyExc_TimeoutError,
2635 : : "The read operation timed out");
2636 : : else
2637 : 0 : PyErr_SetString(PyExc_TimeoutError,
2638 : : "The write operation timed out");
2639 : 0 : goto error;
2640 : : }
2641 [ # # ]: 0 : else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2642 : 0 : PyErr_SetString(get_state_sock(self)->PySSLErrorObject,
2643 : : "Underlying socket too large for select().");
2644 : 0 : goto error;
2645 : : }
2646 [ # # ]: 0 : else if (sockstate != SOCKET_OPERATION_OK)
2647 : : /* Retain the SSL error code */
2648 : 0 : break;
2649 : : }
2650 [ # # ]: 0 : if (ret < 0) {
2651 : 0 : Py_XDECREF(sock);
2652 : 0 : PySSL_SetError(self, ret, __FILE__, __LINE__);
2653 : 0 : return NULL;
2654 : : }
2655 [ # # ]: 0 : if (self->exc != NULL)
2656 : 0 : goto error;
2657 [ # # ]: 0 : if (sock)
2658 : : /* It's already INCREF'ed */
2659 : 0 : return (PyObject *) sock;
2660 : : else
2661 : 0 : Py_RETURN_NONE;
2662 : :
2663 : 0 : error:
2664 : 0 : Py_XDECREF(sock);
2665 : 0 : PySSL_ChainExceptions(self);
2666 : 0 : return NULL;
2667 : : }
2668 : :
2669 : : /*[clinic input]
2670 : : _ssl._SSLSocket.get_channel_binding
2671 : : cb_type: str = "tls-unique"
2672 : :
2673 : : Get channel binding data for current connection.
2674 : :
2675 : : Raise ValueError if the requested `cb_type` is not supported. Return bytes
2676 : : of the data or None if the data is not available (e.g. before the handshake).
2677 : : Only 'tls-unique' channel binding data from RFC 5929 is supported.
2678 : : [clinic start generated code]*/
2679 : :
2680 : : static PyObject *
2681 : 0 : _ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2682 : : const char *cb_type)
2683 : : /*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
2684 : : {
2685 : : char buf[PySSL_CB_MAXLEN];
2686 : : size_t len;
2687 : :
2688 [ # # ]: 0 : if (strcmp(cb_type, "tls-unique") == 0) {
2689 [ # # ]: 0 : if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2690 : : /* if session is resumed XOR we are the client */
2691 : 0 : len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2692 : : }
2693 : : else {
2694 : : /* if a new session XOR we are the server */
2695 : 0 : len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2696 : : }
2697 : : }
2698 : : else {
2699 : 0 : PyErr_Format(
2700 : : PyExc_ValueError,
2701 : : "'%s' channel binding type not implemented",
2702 : : cb_type
2703 : : );
2704 : 0 : return NULL;
2705 : : }
2706 : :
2707 : : /* It cannot be negative in current OpenSSL version as of July 2011 */
2708 [ # # ]: 0 : if (len == 0)
2709 : 0 : Py_RETURN_NONE;
2710 : :
2711 : 0 : return PyBytes_FromStringAndSize(buf, len);
2712 : : }
2713 : :
2714 : : /*[clinic input]
2715 : : _ssl._SSLSocket.verify_client_post_handshake
2716 : :
2717 : : Initiate TLS 1.3 post-handshake authentication
2718 : : [clinic start generated code]*/
2719 : :
2720 : : static PyObject *
2721 : 0 : _ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2722 : : /*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2723 : : {
2724 : : #ifdef TLS1_3_VERSION
2725 : 0 : int err = SSL_verify_client_post_handshake(self->ssl);
2726 [ # # ]: 0 : if (err == 0)
2727 : 0 : return _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
2728 : : else
2729 : 0 : Py_RETURN_NONE;
2730 : : #else
2731 : : PyErr_SetString(PyExc_NotImplementedError,
2732 : : "Post-handshake auth is not supported by your "
2733 : : "OpenSSL version.");
2734 : : return NULL;
2735 : : #endif
2736 : : }
2737 : :
2738 : : static SSL_SESSION*
2739 : 0 : _ssl_session_dup(SSL_SESSION *session) {
2740 : 0 : SSL_SESSION *newsession = NULL;
2741 : : int slen;
2742 : 0 : unsigned char *senc = NULL, *p;
2743 : : const unsigned char *const_p;
2744 : :
2745 [ # # ]: 0 : if (session == NULL) {
2746 : 0 : PyErr_SetString(PyExc_ValueError, "Invalid session");
2747 : 0 : goto error;
2748 : : }
2749 : :
2750 : : /* get length */
2751 : 0 : slen = i2d_SSL_SESSION(session, NULL);
2752 [ # # # # ]: 0 : if (slen == 0 || slen > 0xFF00) {
2753 : 0 : PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2754 : 0 : goto error;
2755 : : }
2756 [ # # ]: 0 : if ((senc = PyMem_Malloc(slen)) == NULL) {
2757 : 0 : PyErr_NoMemory();
2758 : 0 : goto error;
2759 : : }
2760 : 0 : p = senc;
2761 [ # # ]: 0 : if (!i2d_SSL_SESSION(session, &p)) {
2762 : 0 : PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2763 : 0 : goto error;
2764 : : }
2765 : 0 : const_p = senc;
2766 : 0 : newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2767 [ # # ]: 0 : if (session == NULL) {
2768 : 0 : goto error;
2769 : : }
2770 : 0 : PyMem_Free(senc);
2771 : 0 : return newsession;
2772 : 0 : error:
2773 [ # # ]: 0 : if (senc != NULL) {
2774 : 0 : PyMem_Free(senc);
2775 : : }
2776 : 0 : return NULL;
2777 : : }
2778 : :
2779 : : static PyObject *
2780 : 0 : PySSL_get_session(PySSLSocket *self, void *closure) {
2781 : : /* get_session can return sessions from a server-side connection,
2782 : : * it does not check for handshake done or client socket. */
2783 : : PySSLSession *pysess;
2784 : : SSL_SESSION *session;
2785 : :
2786 : : /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2787 : : * https://github.com/openssl/openssl/issues/1550 */
2788 : 0 : session = SSL_get0_session(self->ssl); /* borrowed reference */
2789 [ # # ]: 0 : if (session == NULL) {
2790 : 0 : Py_RETURN_NONE;
2791 : : }
2792 [ # # ]: 0 : if ((session = _ssl_session_dup(session)) == NULL) {
2793 : 0 : return NULL;
2794 : : }
2795 : 0 : session = SSL_get1_session(self->ssl);
2796 [ # # ]: 0 : if (session == NULL) {
2797 : 0 : Py_RETURN_NONE;
2798 : : }
2799 : 0 : pysess = PyObject_GC_New(PySSLSession, self->ctx->state->PySSLSession_Type);
2800 [ # # ]: 0 : if (pysess == NULL) {
2801 : 0 : SSL_SESSION_free(session);
2802 : 0 : return NULL;
2803 : : }
2804 : :
2805 : : assert(self->ctx);
2806 : 0 : pysess->ctx = (PySSLContext*)Py_NewRef(self->ctx);
2807 : 0 : pysess->session = session;
2808 : 0 : PyObject_GC_Track(pysess);
2809 : 0 : return (PyObject *)pysess;
2810 : : }
2811 : :
2812 : 0 : static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2813 : : void *closure)
2814 : : {
2815 : : PySSLSession *pysess;
2816 : : SSL_SESSION *session;
2817 : : int result;
2818 : :
2819 [ # # ]: 0 : if (!Py_IS_TYPE(value, get_state_sock(self)->PySSLSession_Type)) {
2820 : 0 : PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2821 : 0 : return -1;
2822 : : }
2823 : 0 : pysess = (PySSLSession *)value;
2824 : :
2825 [ # # ]: 0 : if (self->ctx->ctx != pysess->ctx->ctx) {
2826 : 0 : PyErr_SetString(PyExc_ValueError,
2827 : : "Session refers to a different SSLContext.");
2828 : 0 : return -1;
2829 : : }
2830 [ # # ]: 0 : if (self->socket_type != PY_SSL_CLIENT) {
2831 : 0 : PyErr_SetString(PyExc_ValueError,
2832 : : "Cannot set session for server-side SSLSocket.");
2833 : 0 : return -1;
2834 : : }
2835 [ # # ]: 0 : if (SSL_is_init_finished(self->ssl)) {
2836 : 0 : PyErr_SetString(PyExc_ValueError,
2837 : : "Cannot set session after handshake.");
2838 : 0 : return -1;
2839 : : }
2840 : : /* duplicate session */
2841 [ # # ]: 0 : if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2842 : 0 : return -1;
2843 : : }
2844 : 0 : result = SSL_set_session(self->ssl, session);
2845 : : /* free duplicate, SSL_set_session() bumps ref count */
2846 : 0 : SSL_SESSION_free(session);
2847 [ # # ]: 0 : if (result == 0) {
2848 : 0 : _setSSLError(get_state_sock(self), NULL, 0, __FILE__, __LINE__);
2849 : 0 : return -1;
2850 : : }
2851 : 0 : return 0;
2852 : : }
2853 : :
2854 : : PyDoc_STRVAR(PySSL_set_session_doc,
2855 : : "_setter_session(session)\n\
2856 : : \
2857 : : Get / set SSLSession.");
2858 : :
2859 : : static PyObject *
2860 : 0 : PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2861 [ # # ]: 0 : if (SSL_session_reused(self->ssl)) {
2862 : 0 : Py_RETURN_TRUE;
2863 : : } else {
2864 : 0 : Py_RETURN_FALSE;
2865 : : }
2866 : : }
2867 : :
2868 : : PyDoc_STRVAR(PySSL_get_session_reused_doc,
2869 : : "Was the client session reused during handshake?");
2870 : :
2871 : : static PyGetSetDef ssl_getsetlist[] = {
2872 : : {"context", (getter) PySSL_get_context,
2873 : : (setter) PySSL_set_context, PySSL_set_context_doc},
2874 : : {"server_side", (getter) PySSL_get_server_side, NULL,
2875 : : PySSL_get_server_side_doc},
2876 : : {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2877 : : PySSL_get_server_hostname_doc},
2878 : : {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2879 : : PySSL_get_owner_doc},
2880 : : {"session", (getter) PySSL_get_session,
2881 : : (setter) PySSL_set_session, PySSL_set_session_doc},
2882 : : {"session_reused", (getter) PySSL_get_session_reused, NULL,
2883 : : PySSL_get_session_reused_doc},
2884 : : {NULL}, /* sentinel */
2885 : : };
2886 : :
2887 : : static PyMethodDef PySSLMethods[] = {
2888 : : _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2889 : : _SSL__SSLSOCKET_WRITE_METHODDEF
2890 : : _SSL__SSLSOCKET_READ_METHODDEF
2891 : : _SSL__SSLSOCKET_PENDING_METHODDEF
2892 : : _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2893 : : _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
2894 : : _SSL__SSLSOCKET_CIPHER_METHODDEF
2895 : : _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2896 : : _SSL__SSLSOCKET_VERSION_METHODDEF
2897 : : _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2898 : : _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2899 : : _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2900 : : _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
2901 : : _SSL__SSLSOCKET_GET_UNVERIFIED_CHAIN_METHODDEF
2902 : : _SSL__SSLSOCKET_GET_VERIFIED_CHAIN_METHODDEF
2903 : : {NULL, NULL}
2904 : : };
2905 : :
2906 : : static PyType_Slot PySSLSocket_slots[] = {
2907 : : {Py_tp_methods, PySSLMethods},
2908 : : {Py_tp_getset, ssl_getsetlist},
2909 : : {Py_tp_dealloc, PySSL_dealloc},
2910 : : {Py_tp_traverse, PySSL_traverse},
2911 : : {Py_tp_clear, PySSL_clear},
2912 : : {0, 0},
2913 : : };
2914 : :
2915 : : static PyType_Spec PySSLSocket_spec = {
2916 : : .name = "_ssl._SSLSocket",
2917 : : .basicsize = sizeof(PySSLSocket),
2918 : : .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
2919 : : Py_TPFLAGS_HAVE_GC),
2920 : : .slots = PySSLSocket_slots,
2921 : : };
2922 : :
2923 : : /*
2924 : : * _SSLContext objects
2925 : : */
2926 : :
2927 : : static int
2928 : 0 : _set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
2929 : : {
2930 : : int mode;
2931 : 0 : int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2932 : :
2933 [ # # # # ]: 0 : switch(n) {
2934 : 0 : case PY_SSL_CERT_NONE:
2935 : 0 : mode = SSL_VERIFY_NONE;
2936 : 0 : break;
2937 : 0 : case PY_SSL_CERT_OPTIONAL:
2938 : 0 : mode = SSL_VERIFY_PEER;
2939 : 0 : break;
2940 : 0 : case PY_SSL_CERT_REQUIRED:
2941 : 0 : mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2942 : 0 : break;
2943 : 0 : default:
2944 : 0 : PyErr_SetString(PyExc_ValueError,
2945 : : "invalid value for verify_mode");
2946 : 0 : return -1;
2947 : : }
2948 : :
2949 : : /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
2950 : : * server sockets and SSL_set_post_handshake_auth() for client. */
2951 : :
2952 : : /* keep current verify cb */
2953 : 0 : verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2954 : 0 : SSL_CTX_set_verify(self->ctx, mode, verify_cb);
2955 : 0 : return 0;
2956 : : }
2957 : :
2958 : : /*[clinic input]
2959 : : @classmethod
2960 : : _ssl._SSLContext.__new__
2961 : : protocol as proto_version: int
2962 : : /
2963 : : [clinic start generated code]*/
2964 : :
2965 : : static PyObject *
2966 : 0 : _ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2967 : : /*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
2968 : : {
2969 : : PySSLContext *self;
2970 : : long options;
2971 : 0 : const SSL_METHOD *method = NULL;
2972 : 0 : SSL_CTX *ctx = NULL;
2973 : : X509_VERIFY_PARAM *params;
2974 : : int result;
2975 : :
2976 : : /* slower approach, walk MRO and get borrowed reference to module.
2977 : : * PyType_GetModuleByDef is required for SSLContext subclasses */
2978 : 0 : PyObject *module = PyType_GetModuleByDef(type, &_sslmodule_def);
2979 [ # # ]: 0 : if (module == NULL) {
2980 : 0 : PyErr_SetString(PyExc_RuntimeError,
2981 : : "Cannot find internal module state");
2982 : 0 : return NULL;
2983 : : }
2984 : :
2985 [ # # # # : 0 : switch(proto_version) {
# # # ]
2986 : : #if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
2987 : : case PY_SSL_VERSION_SSL3:
2988 : : PY_SSL_DEPRECATED("ssl.PROTOCOL_SSLv3 is deprecated", 2, NULL);
2989 : : method = SSLv3_method();
2990 : : break;
2991 : : #endif
2992 : : #if (defined(TLS1_VERSION) && \
2993 : : !defined(OPENSSL_NO_TLS1) && \
2994 : : !defined(OPENSSL_NO_TLS1_METHOD))
2995 : 0 : case PY_SSL_VERSION_TLS1:
2996 [ # # ]: 0 : PY_SSL_DEPRECATED("ssl.PROTOCOL_TLSv1 is deprecated", 2, NULL);
2997 : 0 : method = TLSv1_method();
2998 : 0 : break;
2999 : : #endif
3000 : : #if (defined(TLS1_1_VERSION) && \
3001 : : !defined(OPENSSL_NO_TLS1_1) && \
3002 : : !defined(OPENSSL_NO_TLS1_1_METHOD))
3003 : 0 : case PY_SSL_VERSION_TLS1_1:
3004 [ # # ]: 0 : PY_SSL_DEPRECATED("ssl.PROTOCOL_TLSv1_1 is deprecated", 2, NULL);
3005 : 0 : method = TLSv1_1_method();
3006 : 0 : break;
3007 : : #endif
3008 : : #if (defined(TLS1_2_VERSION) && \
3009 : : !defined(OPENSSL_NO_TLS1_2) && \
3010 : : !defined(OPENSSL_NO_TLS1_2_METHOD))
3011 : 0 : case PY_SSL_VERSION_TLS1_2:
3012 [ # # ]: 0 : PY_SSL_DEPRECATED("ssl.PROTOCOL_TLSv1_2 is deprecated", 2, NULL);
3013 : 0 : method = TLSv1_2_method();
3014 : 0 : break;
3015 : : #endif
3016 : 0 : case PY_SSL_VERSION_TLS:
3017 [ # # ]: 0 : PY_SSL_DEPRECATED("ssl.PROTOCOL_TLS is deprecated", 2, NULL);
3018 : 0 : method = TLS_method();
3019 : 0 : break;
3020 : 0 : case PY_SSL_VERSION_TLS_CLIENT:
3021 : 0 : method = TLS_client_method();
3022 : 0 : break;
3023 : 0 : case PY_SSL_VERSION_TLS_SERVER:
3024 : 0 : method = TLS_server_method();
3025 : 0 : break;
3026 : 0 : default:
3027 : 0 : method = NULL;
3028 : : }
3029 : :
3030 [ # # ]: 0 : if (method == NULL) {
3031 : 0 : PyErr_Format(PyExc_ValueError,
3032 : : "invalid or unsupported protocol version %i",
3033 : : proto_version);
3034 : 0 : return NULL;
3035 : : }
3036 : :
3037 : 0 : PySSL_BEGIN_ALLOW_THREADS
3038 : 0 : ctx = SSL_CTX_new(method);
3039 : 0 : PySSL_END_ALLOW_THREADS
3040 : :
3041 [ # # ]: 0 : if (ctx == NULL) {
3042 : 0 : _setSSLError(get_ssl_state(module), NULL, 0, __FILE__, __LINE__);
3043 : 0 : return NULL;
3044 : : }
3045 : :
3046 : : assert(type != NULL && type->tp_alloc != NULL);
3047 : 0 : self = (PySSLContext *) type->tp_alloc(type, 0);
3048 [ # # ]: 0 : if (self == NULL) {
3049 : 0 : SSL_CTX_free(ctx);
3050 : 0 : return NULL;
3051 : : }
3052 : 0 : self->ctx = ctx;
3053 : 0 : self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
3054 : 0 : self->protocol = proto_version;
3055 : 0 : self->msg_cb = NULL;
3056 : 0 : self->keylog_filename = NULL;
3057 : 0 : self->keylog_bio = NULL;
3058 : 0 : self->alpn_protocols = NULL;
3059 : 0 : self->set_sni_cb = NULL;
3060 : 0 : self->state = get_ssl_state(module);
3061 : :
3062 : : /* Don't check host name by default */
3063 [ # # ]: 0 : if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3064 : 0 : self->check_hostname = 1;
3065 [ # # ]: 0 : if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
3066 : 0 : Py_DECREF(self);
3067 : 0 : return NULL;
3068 : : }
3069 : : } else {
3070 : 0 : self->check_hostname = 0;
3071 [ # # ]: 0 : if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
3072 : 0 : Py_DECREF(self);
3073 : 0 : return NULL;
3074 : : }
3075 : : }
3076 : : /* Defaults */
3077 : 0 : options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3078 [ # # ]: 0 : if (proto_version != PY_SSL_VERSION_SSL2)
3079 : 0 : options |= SSL_OP_NO_SSLv2;
3080 [ # # ]: 0 : if (proto_version != PY_SSL_VERSION_SSL3)
3081 : 0 : options |= SSL_OP_NO_SSLv3;
3082 : : /* Minimal security flags for server and client side context.
3083 : : * Client sockets ignore server-side parameters. */
3084 : : #ifdef SSL_OP_NO_COMPRESSION
3085 : 0 : options |= SSL_OP_NO_COMPRESSION;
3086 : : #endif
3087 : : #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3088 : 0 : options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3089 : : #endif
3090 : : #ifdef SSL_OP_SINGLE_DH_USE
3091 : 0 : options |= SSL_OP_SINGLE_DH_USE;
3092 : : #endif
3093 : : #ifdef SSL_OP_SINGLE_ECDH_USE
3094 : 0 : options |= SSL_OP_SINGLE_ECDH_USE;
3095 : : #endif
3096 : : #ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
3097 : : /* Make OpenSSL 3.0.0 behave like 1.1.1 */
3098 : : options |= SSL_OP_IGNORE_UNEXPECTED_EOF;
3099 : : #endif
3100 : 0 : SSL_CTX_set_options(self->ctx, options);
3101 : :
3102 : : /* A bare minimum cipher list without completely broken cipher suites.
3103 : : * It's far from perfect but gives users a better head start. */
3104 [ # # ]: 0 : if (proto_version != PY_SSL_VERSION_SSL2) {
3105 : : #if PY_SSL_DEFAULT_CIPHERS == 2
3106 : : /* stick to OpenSSL's default settings */
3107 : : result = 1;
3108 : : #else
3109 : 0 : result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3110 : : #endif
3111 : : } else {
3112 : : /* SSLv2 needs MD5 */
3113 : 0 : result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3114 : : }
3115 [ # # ]: 0 : if (result == 0) {
3116 : 0 : Py_DECREF(self);
3117 : 0 : ERR_clear_error();
3118 : 0 : PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
3119 : : "No cipher can be selected.");
3120 : 0 : goto error;
3121 : : }
3122 : : #ifdef PY_SSL_MIN_PROTOCOL
3123 [ # # ]: 0 : switch(proto_version) {
3124 : 0 : case PY_SSL_VERSION_TLS:
3125 : : case PY_SSL_VERSION_TLS_CLIENT:
3126 : : case PY_SSL_VERSION_TLS_SERVER:
3127 : 0 : result = SSL_CTX_set_min_proto_version(ctx, PY_SSL_MIN_PROTOCOL);
3128 [ # # ]: 0 : if (result == 0) {
3129 : 0 : PyErr_Format(PyExc_ValueError,
3130 : : "Failed to set minimum protocol 0x%x",
3131 : : PY_SSL_MIN_PROTOCOL);
3132 : 0 : goto error;
3133 : : }
3134 : 0 : break;
3135 : 0 : default:
3136 : 0 : break;
3137 : : }
3138 : : #endif
3139 : :
3140 : : /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3141 : : usage for no cost at all. */
3142 : 0 : SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3143 : :
3144 : : #define SID_CTX "Python"
3145 : 0 : SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3146 : : sizeof(SID_CTX));
3147 : : #undef SID_CTX
3148 : :
3149 : 0 : params = SSL_CTX_get0_param(self->ctx);
3150 : : /* Improve trust chain building when cross-signed intermediate
3151 : : certificates are present. See https://bugs.python.org/issue23476. */
3152 : 0 : X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
3153 : 0 : X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
3154 : :
3155 : : #ifdef TLS1_3_VERSION
3156 : 0 : self->post_handshake_auth = 0;
3157 : 0 : SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3158 : : #endif
3159 : :
3160 : 0 : return (PyObject *)self;
3161 : 0 : error:
3162 : 0 : Py_XDECREF(self);
3163 : 0 : ERR_clear_error();
3164 : 0 : return NULL;
3165 : : }
3166 : :
3167 : : static int
3168 : 0 : context_traverse(PySSLContext *self, visitproc visit, void *arg)
3169 : : {
3170 [ # # # # ]: 0 : Py_VISIT(self->set_sni_cb);
3171 [ # # # # ]: 0 : Py_VISIT(self->msg_cb);
3172 [ # # # # ]: 0 : Py_VISIT(Py_TYPE(self));
3173 : 0 : return 0;
3174 : : }
3175 : :
3176 : : static int
3177 : 0 : context_clear(PySSLContext *self)
3178 : : {
3179 [ # # ]: 0 : Py_CLEAR(self->set_sni_cb);
3180 [ # # ]: 0 : Py_CLEAR(self->msg_cb);
3181 [ # # ]: 0 : Py_CLEAR(self->keylog_filename);
3182 [ # # ]: 0 : if (self->keylog_bio != NULL) {
3183 : 0 : PySSL_BEGIN_ALLOW_THREADS
3184 : 0 : BIO_free_all(self->keylog_bio);
3185 : 0 : PySSL_END_ALLOW_THREADS
3186 : 0 : self->keylog_bio = NULL;
3187 : : }
3188 : 0 : return 0;
3189 : : }
3190 : :
3191 : : static void
3192 : 0 : context_dealloc(PySSLContext *self)
3193 : : {
3194 : 0 : PyTypeObject *tp = Py_TYPE(self);
3195 : : /* bpo-31095: UnTrack is needed before calling any callbacks */
3196 : 0 : PyObject_GC_UnTrack(self);
3197 : 0 : context_clear(self);
3198 : 0 : SSL_CTX_free(self->ctx);
3199 : 0 : PyMem_FREE(self->alpn_protocols);
3200 : 0 : Py_TYPE(self)->tp_free(self);
3201 : 0 : Py_DECREF(tp);
3202 : 0 : }
3203 : :
3204 : : /*[clinic input]
3205 : : _ssl._SSLContext.set_ciphers
3206 : : cipherlist: str
3207 : : /
3208 : : [clinic start generated code]*/
3209 : :
3210 : : static PyObject *
3211 : 0 : _ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3212 : : /*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3213 : : {
3214 : 0 : int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
3215 [ # # ]: 0 : if (ret == 0) {
3216 : : /* Clearing the error queue is necessary on some OpenSSL versions,
3217 : : otherwise the error will be reported again when another SSL call
3218 : : is done. */
3219 : 0 : ERR_clear_error();
3220 : 0 : PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
3221 : : "No cipher can be selected.");
3222 : 0 : return NULL;
3223 : : }
3224 : 0 : Py_RETURN_NONE;
3225 : : }
3226 : :
3227 : : /*[clinic input]
3228 : : _ssl._SSLContext.get_ciphers
3229 : : [clinic start generated code]*/
3230 : :
3231 : : static PyObject *
3232 : 0 : _ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3233 : : /*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3234 : : {
3235 : 0 : SSL *ssl = NULL;
3236 : 0 : STACK_OF(SSL_CIPHER) *sk = NULL;
3237 : : const SSL_CIPHER *cipher;
3238 : 0 : int i=0;
3239 : 0 : PyObject *result = NULL, *dct;
3240 : :
3241 : 0 : ssl = SSL_new(self->ctx);
3242 [ # # ]: 0 : if (ssl == NULL) {
3243 : 0 : _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
3244 : 0 : goto exit;
3245 : : }
3246 : 0 : sk = SSL_get_ciphers(ssl);
3247 : :
3248 : 0 : result = PyList_New(sk_SSL_CIPHER_num(sk));
3249 [ # # ]: 0 : if (result == NULL) {
3250 : 0 : goto exit;
3251 : : }
3252 : :
3253 [ # # ]: 0 : for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3254 : 0 : cipher = sk_SSL_CIPHER_value(sk, i);
3255 : 0 : dct = cipher_to_dict(cipher);
3256 [ # # ]: 0 : if (dct == NULL) {
3257 [ # # ]: 0 : Py_CLEAR(result);
3258 : 0 : goto exit;
3259 : : }
3260 : 0 : PyList_SET_ITEM(result, i, dct);
3261 : : }
3262 : :
3263 : 0 : exit:
3264 [ # # ]: 0 : if (ssl != NULL)
3265 : 0 : SSL_free(ssl);
3266 : 0 : return result;
3267 : :
3268 : : }
3269 : :
3270 : :
3271 : : static int
3272 : 0 : do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3273 : : const unsigned char *server_protocols, unsigned int server_protocols_len,
3274 : : const unsigned char *client_protocols, unsigned int client_protocols_len)
3275 : : {
3276 : : int ret;
3277 [ # # ]: 0 : if (client_protocols == NULL) {
3278 : 0 : client_protocols = (unsigned char *)"";
3279 : 0 : client_protocols_len = 0;
3280 : : }
3281 [ # # ]: 0 : if (server_protocols == NULL) {
3282 : 0 : server_protocols = (unsigned char *)"";
3283 : 0 : server_protocols_len = 0;
3284 : : }
3285 : :
3286 : 0 : ret = SSL_select_next_proto(out, outlen,
3287 : : server_protocols, server_protocols_len,
3288 : : client_protocols, client_protocols_len);
3289 [ # # # # ]: 0 : if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3290 : 0 : return SSL_TLSEXT_ERR_NOACK;
3291 : :
3292 : 0 : return SSL_TLSEXT_ERR_OK;
3293 : : }
3294 : :
3295 : : static int
3296 : 0 : _selectALPN_cb(SSL *s,
3297 : : const unsigned char **out, unsigned char *outlen,
3298 : : const unsigned char *client_protocols, unsigned int client_protocols_len,
3299 : : void *args)
3300 : : {
3301 : 0 : PySSLContext *ctx = (PySSLContext *)args;
3302 : 0 : return do_protocol_selection(1, (unsigned char **)out, outlen,
3303 : 0 : ctx->alpn_protocols, ctx->alpn_protocols_len,
3304 : : client_protocols, client_protocols_len);
3305 : : }
3306 : :
3307 : : /*[clinic input]
3308 : : _ssl._SSLContext._set_alpn_protocols
3309 : : protos: Py_buffer
3310 : : /
3311 : : [clinic start generated code]*/
3312 : :
3313 : : static PyObject *
3314 : 0 : _ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3315 : : Py_buffer *protos)
3316 : : /*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
3317 : : {
3318 [ # # ]: 0 : if ((size_t)protos->len > UINT_MAX) {
3319 : 0 : PyErr_Format(PyExc_OverflowError,
3320 : : "protocols longer than %u bytes", UINT_MAX);
3321 : 0 : return NULL;
3322 : : }
3323 : :
3324 : 0 : PyMem_Free(self->alpn_protocols);
3325 : 0 : self->alpn_protocols = PyMem_Malloc(protos->len);
3326 [ # # ]: 0 : if (!self->alpn_protocols)
3327 : 0 : return PyErr_NoMemory();
3328 : 0 : memcpy(self->alpn_protocols, protos->buf, protos->len);
3329 : 0 : self->alpn_protocols_len = (unsigned int)protos->len;
3330 : :
3331 [ # # ]: 0 : if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3332 : 0 : return PyErr_NoMemory();
3333 : 0 : SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3334 : :
3335 : 0 : Py_RETURN_NONE;
3336 : : }
3337 : :
3338 : : static PyObject *
3339 : 0 : get_verify_mode(PySSLContext *self, void *c)
3340 : : {
3341 : : /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3342 : 0 : int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3343 : : SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3344 [ # # # # ]: 0 : switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
3345 : 0 : case SSL_VERIFY_NONE:
3346 : 0 : return PyLong_FromLong(PY_SSL_CERT_NONE);
3347 : 0 : case SSL_VERIFY_PEER:
3348 : 0 : return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3349 : 0 : case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3350 : 0 : return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3351 : : }
3352 : 0 : PyErr_SetString(get_state_ctx(self)->PySSLErrorObject,
3353 : : "invalid return value from SSL_CTX_get_verify_mode");
3354 : 0 : return NULL;
3355 : : }
3356 : :
3357 : : static int
3358 : 0 : set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3359 : : {
3360 : : int n;
3361 [ # # ]: 0 : if (!PyArg_Parse(arg, "i", &n))
3362 : 0 : return -1;
3363 [ # # # # ]: 0 : if (n == PY_SSL_CERT_NONE && self->check_hostname) {
3364 : 0 : PyErr_SetString(PyExc_ValueError,
3365 : : "Cannot set verify_mode to CERT_NONE when "
3366 : : "check_hostname is enabled.");
3367 : 0 : return -1;
3368 : : }
3369 : 0 : return _set_verify_mode(self, n);
3370 : : }
3371 : :
3372 : : static PyObject *
3373 : 0 : get_verify_flags(PySSLContext *self, void *c)
3374 : : {
3375 : : X509_VERIFY_PARAM *param;
3376 : : unsigned long flags;
3377 : :
3378 : 0 : param = SSL_CTX_get0_param(self->ctx);
3379 : 0 : flags = X509_VERIFY_PARAM_get_flags(param);
3380 : 0 : return PyLong_FromUnsignedLong(flags);
3381 : : }
3382 : :
3383 : : static int
3384 : 0 : set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3385 : : {
3386 : : X509_VERIFY_PARAM *param;
3387 : : unsigned long new_flags, flags, set, clear;
3388 : :
3389 [ # # ]: 0 : if (!PyArg_Parse(arg, "k", &new_flags))
3390 : 0 : return -1;
3391 : 0 : param = SSL_CTX_get0_param(self->ctx);
3392 : 0 : flags = X509_VERIFY_PARAM_get_flags(param);
3393 : 0 : clear = flags & ~new_flags;
3394 : 0 : set = ~flags & new_flags;
3395 [ # # ]: 0 : if (clear) {
3396 [ # # ]: 0 : if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
3397 : 0 : _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
3398 : 0 : return -1;
3399 : : }
3400 : : }
3401 [ # # ]: 0 : if (set) {
3402 [ # # ]: 0 : if (!X509_VERIFY_PARAM_set_flags(param, set)) {
3403 : 0 : _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
3404 : 0 : return -1;
3405 : : }
3406 : : }
3407 : 0 : return 0;
3408 : : }
3409 : :
3410 : : /* Getter and setter for protocol version */
3411 : : static int
3412 : 0 : set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3413 : : {
3414 : : long v;
3415 : : int result;
3416 : :
3417 [ # # ]: 0 : if (!PyArg_Parse(arg, "l", &v))
3418 : 0 : return -1;
3419 [ # # ]: 0 : if (v > INT_MAX) {
3420 : 0 : PyErr_SetString(PyExc_OverflowError, "Option is too long");
3421 : 0 : return -1;
3422 : : }
3423 : :
3424 [ # # ]: 0 : switch(self->protocol) {
3425 : 0 : case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3426 : : case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3427 : : case PY_SSL_VERSION_TLS:
3428 : 0 : break;
3429 : 0 : default:
3430 : 0 : PyErr_SetString(
3431 : : PyExc_ValueError,
3432 : : "The context's protocol doesn't support modification of "
3433 : : "highest and lowest version."
3434 : : );
3435 : 0 : return -1;
3436 : : }
3437 : :
3438 : : /* check for deprecations and supported values */
3439 [ # # # # : 0 : switch(v) {
# ]
3440 : 0 : case PY_PROTO_SSLv3:
3441 [ # # ]: 0 : PY_SSL_DEPRECATED("ssl.TLSVersion.SSLv3 is deprecated", 2, -1);
3442 : 0 : break;
3443 : 0 : case PY_PROTO_TLSv1:
3444 [ # # ]: 0 : PY_SSL_DEPRECATED("ssl.TLSVersion.TLSv1 is deprecated", 2, -1);
3445 : 0 : break;
3446 : 0 : case PY_PROTO_TLSv1_1:
3447 [ # # ]: 0 : PY_SSL_DEPRECATED("ssl.TLSVersion.TLSv1_1 is deprecated", 2, -1);
3448 : 0 : break;
3449 : 0 : case PY_PROTO_MINIMUM_SUPPORTED:
3450 : : case PY_PROTO_MAXIMUM_SUPPORTED:
3451 : : case PY_PROTO_TLSv1_2:
3452 : : case PY_PROTO_TLSv1_3:
3453 : : /* ok */
3454 : 0 : break;
3455 : 0 : default:
3456 : 0 : PyErr_Format(PyExc_ValueError,
3457 : : "Unsupported TLS/SSL version 0x%x", v);
3458 : 0 : return -1;
3459 : : }
3460 : :
3461 [ # # ]: 0 : if (what == 0) {
3462 [ # # # ]: 0 : switch(v) {
3463 : 0 : case PY_PROTO_MINIMUM_SUPPORTED:
3464 : 0 : v = 0;
3465 : 0 : break;
3466 : 0 : case PY_PROTO_MAXIMUM_SUPPORTED:
3467 : : /* Emulate max for set_min_proto_version */
3468 : 0 : v = PY_PROTO_MAXIMUM_AVAILABLE;
3469 : 0 : break;
3470 : 0 : default:
3471 : 0 : break;
3472 : : }
3473 : 0 : result = SSL_CTX_set_min_proto_version(self->ctx, v);
3474 : : }
3475 : : else {
3476 [ # # # ]: 0 : switch(v) {
3477 : 0 : case PY_PROTO_MAXIMUM_SUPPORTED:
3478 : 0 : v = 0;
3479 : 0 : break;
3480 : 0 : case PY_PROTO_MINIMUM_SUPPORTED:
3481 : : /* Emulate max for set_min_proto_version */
3482 : 0 : v = PY_PROTO_MINIMUM_AVAILABLE;
3483 : 0 : break;
3484 : 0 : default:
3485 : 0 : break;
3486 : : }
3487 : 0 : result = SSL_CTX_set_max_proto_version(self->ctx, v);
3488 : : }
3489 [ # # ]: 0 : if (result == 0) {
3490 : 0 : PyErr_Format(PyExc_ValueError,
3491 : : "Unsupported protocol version 0x%x", v);
3492 : 0 : return -1;
3493 : : }
3494 : 0 : return 0;
3495 : : }
3496 : :
3497 : : static PyObject *
3498 : 0 : get_minimum_version(PySSLContext *self, void *c)
3499 : : {
3500 : 0 : int v = SSL_CTX_get_min_proto_version(self->ctx);
3501 [ # # ]: 0 : if (v == 0) {
3502 : 0 : v = PY_PROTO_MINIMUM_SUPPORTED;
3503 : : }
3504 : 0 : return PyLong_FromLong(v);
3505 : : }
3506 : :
3507 : : static int
3508 : 0 : set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3509 : : {
3510 : 0 : return set_min_max_proto_version(self, arg, 0);
3511 : : }
3512 : :
3513 : : static PyObject *
3514 : 0 : get_maximum_version(PySSLContext *self, void *c)
3515 : : {
3516 : 0 : int v = SSL_CTX_get_max_proto_version(self->ctx);
3517 [ # # ]: 0 : if (v == 0) {
3518 : 0 : v = PY_PROTO_MAXIMUM_SUPPORTED;
3519 : : }
3520 : 0 : return PyLong_FromLong(v);
3521 : : }
3522 : :
3523 : : static int
3524 : 0 : set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3525 : : {
3526 : 0 : return set_min_max_proto_version(self, arg, 1);
3527 : : }
3528 : :
3529 : : #ifdef TLS1_3_VERSION
3530 : : static PyObject *
3531 : 0 : get_num_tickets(PySSLContext *self, void *c)
3532 : : {
3533 : 0 : return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
3534 : : }
3535 : :
3536 : : static int
3537 : 0 : set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3538 : : {
3539 : : long num;
3540 [ # # ]: 0 : if (!PyArg_Parse(arg, "l", &num))
3541 : 0 : return -1;
3542 [ # # ]: 0 : if (num < 0) {
3543 : 0 : PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3544 : 0 : return -1;
3545 : : }
3546 [ # # ]: 0 : if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3547 : 0 : PyErr_SetString(PyExc_ValueError,
3548 : : "SSLContext is not a server context.");
3549 : 0 : return -1;
3550 : : }
3551 [ # # ]: 0 : if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3552 : 0 : PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3553 : 0 : return -1;
3554 : : }
3555 : 0 : return 0;
3556 : : }
3557 : :
3558 : : PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3559 : : "Control the number of TLSv1.3 session tickets");
3560 : : #endif /* TLS1_3_VERSION */
3561 : :
3562 : : static PyObject *
3563 : 0 : get_security_level(PySSLContext *self, void *c)
3564 : : {
3565 : 0 : return PyLong_FromLong(SSL_CTX_get_security_level(self->ctx));
3566 : : }
3567 : : PyDoc_STRVAR(PySSLContext_security_level_doc, "The current security level");
3568 : :
3569 : : static PyObject *
3570 : 0 : get_options(PySSLContext *self, void *c)
3571 : : {
3572 : 0 : return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3573 : : }
3574 : :
3575 : : static int
3576 : 0 : set_options(PySSLContext *self, PyObject *arg, void *c)
3577 : : {
3578 : : long new_opts, opts, set, clear;
3579 : 0 : long opt_no = (
3580 : : SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 |
3581 : : SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_3
3582 : : );
3583 : :
3584 [ # # ]: 0 : if (!PyArg_Parse(arg, "l", &new_opts))
3585 : 0 : return -1;
3586 : 0 : opts = SSL_CTX_get_options(self->ctx);
3587 : 0 : clear = opts & ~new_opts;
3588 : 0 : set = ~opts & new_opts;
3589 : :
3590 [ # # ]: 0 : if ((set & opt_no) != 0) {
3591 [ # # ]: 0 : if (_ssl_deprecated("ssl.OP_NO_SSL*/ssl.OP_NO_TLS* options are "
3592 : : "deprecated", 2) < 0) {
3593 : 0 : return -1;
3594 : : }
3595 : : }
3596 [ # # ]: 0 : if (clear) {
3597 : 0 : SSL_CTX_clear_options(self->ctx, clear);
3598 : : }
3599 [ # # ]: 0 : if (set)
3600 : 0 : SSL_CTX_set_options(self->ctx, set);
3601 : 0 : return 0;
3602 : : }
3603 : :
3604 : : static PyObject *
3605 : 0 : get_host_flags(PySSLContext *self, void *c)
3606 : : {
3607 : 0 : return PyLong_FromUnsignedLong(self->hostflags);
3608 : : }
3609 : :
3610 : : static int
3611 : 0 : set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3612 : : {
3613 : : X509_VERIFY_PARAM *param;
3614 : 0 : unsigned int new_flags = 0;
3615 : :
3616 [ # # ]: 0 : if (!PyArg_Parse(arg, "I", &new_flags))
3617 : 0 : return -1;
3618 : :
3619 : 0 : param = SSL_CTX_get0_param(self->ctx);
3620 : 0 : self->hostflags = new_flags;
3621 : 0 : X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3622 : 0 : return 0;
3623 : : }
3624 : :
3625 : : static PyObject *
3626 : 0 : get_check_hostname(PySSLContext *self, void *c)
3627 : : {
3628 : 0 : return PyBool_FromLong(self->check_hostname);
3629 : : }
3630 : :
3631 : : static int
3632 : 0 : set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3633 : : {
3634 : : int check_hostname;
3635 [ # # ]: 0 : if (!PyArg_Parse(arg, "p", &check_hostname))
3636 : 0 : return -1;
3637 [ # # # # ]: 0 : if (check_hostname &&
3638 : 0 : SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3639 : : /* check_hostname = True sets verify_mode = CERT_REQUIRED */
3640 [ # # ]: 0 : if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
3641 : 0 : return -1;
3642 : : }
3643 : : }
3644 : 0 : self->check_hostname = check_hostname;
3645 : 0 : return 0;
3646 : : }
3647 : :
3648 : : static PyObject *
3649 : 0 : get_post_handshake_auth(PySSLContext *self, void *c) {
3650 : : #if TLS1_3_VERSION
3651 : 0 : return PyBool_FromLong(self->post_handshake_auth);
3652 : : #else
3653 : : Py_RETURN_NONE;
3654 : : #endif
3655 : : }
3656 : :
3657 : : #if TLS1_3_VERSION
3658 : : static int
3659 : 0 : set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
3660 [ # # ]: 0 : if (arg == NULL) {
3661 : 0 : PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3662 : 0 : return -1;
3663 : : }
3664 : 0 : int pha = PyObject_IsTrue(arg);
3665 : :
3666 [ # # ]: 0 : if (pha == -1) {
3667 : 0 : return -1;
3668 : : }
3669 : 0 : self->post_handshake_auth = pha;
3670 : :
3671 : : /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3672 : : * server sockets and SSL_set_post_handshake_auth() for client. */
3673 : :
3674 : 0 : return 0;
3675 : : }
3676 : : #endif
3677 : :
3678 : : static PyObject *
3679 : 0 : get_protocol(PySSLContext *self, void *c) {
3680 : 0 : return PyLong_FromLong(self->protocol);
3681 : : }
3682 : :
3683 : : typedef struct {
3684 : : PyThreadState *thread_state;
3685 : : PyObject *callable;
3686 : : char *password;
3687 : : int size;
3688 : : int error;
3689 : : } _PySSLPasswordInfo;
3690 : :
3691 : : static int
3692 : 0 : _pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3693 : : const char *bad_type_error)
3694 : : {
3695 : : /* Set the password and size fields of a _PySSLPasswordInfo struct
3696 : : from a unicode, bytes, or byte array object.
3697 : : The password field will be dynamically allocated and must be freed
3698 : : by the caller */
3699 : 0 : PyObject *password_bytes = NULL;
3700 : 0 : const char *data = NULL;
3701 : : Py_ssize_t size;
3702 : :
3703 [ # # ]: 0 : if (PyUnicode_Check(password)) {
3704 : 0 : password_bytes = PyUnicode_AsUTF8String(password);
3705 [ # # ]: 0 : if (!password_bytes) {
3706 : 0 : goto error;
3707 : : }
3708 : 0 : data = PyBytes_AS_STRING(password_bytes);
3709 : 0 : size = PyBytes_GET_SIZE(password_bytes);
3710 [ # # ]: 0 : } else if (PyBytes_Check(password)) {
3711 : 0 : data = PyBytes_AS_STRING(password);
3712 : 0 : size = PyBytes_GET_SIZE(password);
3713 [ # # ]: 0 : } else if (PyByteArray_Check(password)) {
3714 : 0 : data = PyByteArray_AS_STRING(password);
3715 : 0 : size = PyByteArray_GET_SIZE(password);
3716 : : } else {
3717 : 0 : PyErr_SetString(PyExc_TypeError, bad_type_error);
3718 : 0 : goto error;
3719 : : }
3720 : :
3721 [ # # ]: 0 : if (size > (Py_ssize_t)INT_MAX) {
3722 : 0 : PyErr_Format(PyExc_ValueError,
3723 : : "password cannot be longer than %d bytes", INT_MAX);
3724 : 0 : goto error;
3725 : : }
3726 : :
3727 : 0 : PyMem_Free(pw_info->password);
3728 : 0 : pw_info->password = PyMem_Malloc(size);
3729 [ # # ]: 0 : if (!pw_info->password) {
3730 : 0 : PyErr_SetString(PyExc_MemoryError,
3731 : : "unable to allocate password buffer");
3732 : 0 : goto error;
3733 : : }
3734 : 0 : memcpy(pw_info->password, data, size);
3735 : 0 : pw_info->size = (int)size;
3736 : :
3737 : 0 : Py_XDECREF(password_bytes);
3738 : 0 : return 1;
3739 : :
3740 : 0 : error:
3741 : 0 : Py_XDECREF(password_bytes);
3742 : 0 : return 0;
3743 : : }
3744 : :
3745 : : static int
3746 : 0 : _password_callback(char *buf, int size, int rwflag, void *userdata)
3747 : : {
3748 : 0 : _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3749 : 0 : PyObject *fn_ret = NULL;
3750 : :
3751 : 0 : PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3752 : :
3753 [ # # ]: 0 : if (pw_info->error) {
3754 : : /* already failed previously. OpenSSL 3.0.0-alpha14 invokes the
3755 : : * callback multiple times which can lead to fatal Python error in
3756 : : * exception check. */
3757 : 0 : goto error;
3758 : : }
3759 : :
3760 [ # # ]: 0 : if (pw_info->callable) {
3761 : 0 : fn_ret = PyObject_CallNoArgs(pw_info->callable);
3762 [ # # ]: 0 : if (!fn_ret) {
3763 : : /* TODO: It would be nice to move _ctypes_add_traceback() into the
3764 : : core python API, so we could use it to add a frame here */
3765 : 0 : goto error;
3766 : : }
3767 : :
3768 [ # # ]: 0 : if (!_pwinfo_set(pw_info, fn_ret,
3769 : : "password callback must return a string")) {
3770 : 0 : goto error;
3771 : : }
3772 [ # # ]: 0 : Py_CLEAR(fn_ret);
3773 : : }
3774 : :
3775 [ # # ]: 0 : if (pw_info->size > size) {
3776 : 0 : PyErr_Format(PyExc_ValueError,
3777 : : "password cannot be longer than %d bytes", size);
3778 : 0 : goto error;
3779 : : }
3780 : :
3781 : 0 : PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3782 : 0 : memcpy(buf, pw_info->password, pw_info->size);
3783 : 0 : return pw_info->size;
3784 : :
3785 : 0 : error:
3786 : 0 : Py_XDECREF(fn_ret);
3787 : 0 : PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3788 : 0 : pw_info->error = 1;
3789 : 0 : return -1;
3790 : : }
3791 : :
3792 : : /*[clinic input]
3793 : : _ssl._SSLContext.load_cert_chain
3794 : : certfile: object
3795 : : keyfile: object = None
3796 : : password: object = None
3797 : :
3798 : : [clinic start generated code]*/
3799 : :
3800 : : static PyObject *
3801 : 0 : _ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3802 : : PyObject *keyfile, PyObject *password)
3803 : : /*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
3804 : : {
3805 : 0 : PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
3806 : 0 : pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3807 : 0 : void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
3808 : 0 : _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
3809 : : int r;
3810 : :
3811 : 0 : errno = 0;
3812 : 0 : ERR_clear_error();
3813 [ # # ]: 0 : if (keyfile == Py_None)
3814 : 0 : keyfile = NULL;
3815 [ # # ]: 0 : if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3816 [ # # ]: 0 : if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3817 : 0 : PyErr_SetString(PyExc_TypeError,
3818 : : "certfile should be a valid filesystem path");
3819 : : }
3820 : 0 : return NULL;
3821 : : }
3822 [ # # # # ]: 0 : if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3823 [ # # ]: 0 : if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3824 : 0 : PyErr_SetString(PyExc_TypeError,
3825 : : "keyfile should be a valid filesystem path");
3826 : : }
3827 : 0 : goto error;
3828 : : }
3829 [ # # ]: 0 : if (password != Py_None) {
3830 [ # # ]: 0 : if (PyCallable_Check(password)) {
3831 : 0 : pw_info.callable = password;
3832 [ # # ]: 0 : } else if (!_pwinfo_set(&pw_info, password,
3833 : : "password should be a string or callable")) {
3834 : 0 : goto error;
3835 : : }
3836 : 0 : SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3837 : 0 : SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3838 : : }
3839 : 0 : PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
3840 : 0 : r = SSL_CTX_use_certificate_chain_file(self->ctx,
3841 : 0 : PyBytes_AS_STRING(certfile_bytes));
3842 : 0 : PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3843 [ # # ]: 0 : if (r != 1) {
3844 [ # # ]: 0 : if (pw_info.error) {
3845 : 0 : ERR_clear_error();
3846 : : /* the password callback has already set the error information */
3847 : : }
3848 [ # # ]: 0 : else if (errno != 0) {
3849 : 0 : ERR_clear_error();
3850 : 0 : PyErr_SetFromErrno(PyExc_OSError);
3851 : : }
3852 : : else {
3853 : 0 : _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
3854 : : }
3855 : 0 : goto error;
3856 : : }
3857 : 0 : PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
3858 : 0 : r = SSL_CTX_use_PrivateKey_file(self->ctx,
3859 [ # # ]: 0 : PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3860 : : SSL_FILETYPE_PEM);
3861 : 0 : PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3862 [ # # ]: 0 : Py_CLEAR(keyfile_bytes);
3863 [ # # ]: 0 : Py_CLEAR(certfile_bytes);
3864 [ # # ]: 0 : if (r != 1) {
3865 [ # # ]: 0 : if (pw_info.error) {
3866 : 0 : ERR_clear_error();
3867 : : /* the password callback has already set the error information */
3868 : : }
3869 [ # # ]: 0 : else if (errno != 0) {
3870 : 0 : ERR_clear_error();
3871 : 0 : PyErr_SetFromErrno(PyExc_OSError);
3872 : : }
3873 : : else {
3874 : 0 : _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
3875 : : }
3876 : 0 : goto error;
3877 : : }
3878 : 0 : PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
3879 : 0 : r = SSL_CTX_check_private_key(self->ctx);
3880 : 0 : PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3881 [ # # ]: 0 : if (r != 1) {
3882 : 0 : _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
3883 : 0 : goto error;
3884 : : }
3885 : 0 : SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3886 : 0 : SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
3887 : 0 : PyMem_Free(pw_info.password);
3888 : 0 : Py_RETURN_NONE;
3889 : :
3890 : 0 : error:
3891 : 0 : SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3892 : 0 : SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
3893 : 0 : PyMem_Free(pw_info.password);
3894 : 0 : Py_XDECREF(keyfile_bytes);
3895 : 0 : Py_XDECREF(certfile_bytes);
3896 : 0 : return NULL;
3897 : : }
3898 : :
3899 : : /* internal helper function, returns -1 on error
3900 : : */
3901 : : static int
3902 : 0 : _add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
3903 : : int filetype)
3904 : : {
3905 : 0 : BIO *biobuf = NULL;
3906 : : X509_STORE *store;
3907 : 0 : int retval = -1, err, loaded = 0;
3908 : :
3909 : : assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3910 : :
3911 [ # # ]: 0 : if (len <= 0) {
3912 : 0 : PyErr_SetString(PyExc_ValueError,
3913 : : "Empty certificate data");
3914 : 0 : return -1;
3915 [ # # ]: 0 : } else if (len > INT_MAX) {
3916 : 0 : PyErr_SetString(PyExc_OverflowError,
3917 : : "Certificate data is too long.");
3918 : 0 : return -1;
3919 : : }
3920 : :
3921 : 0 : biobuf = BIO_new_mem_buf(data, (int)len);
3922 [ # # ]: 0 : if (biobuf == NULL) {
3923 : 0 : _setSSLError(get_state_ctx(self), "Can't allocate buffer", 0, __FILE__, __LINE__);
3924 : 0 : return -1;
3925 : : }
3926 : :
3927 : 0 : store = SSL_CTX_get_cert_store(self->ctx);
3928 : : assert(store != NULL);
3929 : :
3930 : 0 : while (1) {
3931 : 0 : X509 *cert = NULL;
3932 : : int r;
3933 : :
3934 [ # # ]: 0 : if (filetype == SSL_FILETYPE_ASN1) {
3935 : 0 : cert = d2i_X509_bio(biobuf, NULL);
3936 : : } else {
3937 : 0 : cert = PEM_read_bio_X509(biobuf, NULL,
3938 : : SSL_CTX_get_default_passwd_cb(self->ctx),
3939 : : SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3940 : : );
3941 : : }
3942 [ # # ]: 0 : if (cert == NULL) {
3943 : 0 : break;
3944 : : }
3945 : 0 : r = X509_STORE_add_cert(store, cert);
3946 : 0 : X509_free(cert);
3947 [ # # ]: 0 : if (!r) {
3948 : 0 : err = ERR_peek_last_error();
3949 [ # # ]: 0 : if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3950 [ # # ]: 0 : (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3951 : : /* cert already in hash table, not an error */
3952 : 0 : ERR_clear_error();
3953 : : } else {
3954 : : break;
3955 : : }
3956 : : }
3957 : 0 : loaded++;
3958 : : }
3959 : :
3960 : 0 : err = ERR_peek_last_error();
3961 [ # # ]: 0 : if (loaded == 0) {
3962 : 0 : const char *msg = NULL;
3963 [ # # ]: 0 : if (filetype == SSL_FILETYPE_PEM) {
3964 : 0 : msg = "no start line: cadata does not contain a certificate";
3965 : : } else {
3966 : 0 : msg = "not enough data: cadata does not contain a certificate";
3967 : : }
3968 : 0 : _setSSLError(get_state_ctx(self), msg, 0, __FILE__, __LINE__);
3969 : 0 : retval = -1;
3970 [ # # ]: 0 : } else if ((filetype == SSL_FILETYPE_ASN1) &&
3971 [ # # ]: 0 : (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3972 [ # # ]: 0 : (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3973 : : /* EOF ASN1 file, not an error */
3974 : 0 : ERR_clear_error();
3975 : 0 : retval = 0;
3976 [ # # ]: 0 : } else if ((filetype == SSL_FILETYPE_PEM) &&
3977 [ # # ]: 0 : (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3978 [ # # ]: 0 : (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3979 : : /* EOF PEM file, not an error */
3980 : 0 : ERR_clear_error();
3981 : 0 : retval = 0;
3982 [ # # ]: 0 : } else if (err != 0) {
3983 : 0 : _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
3984 : 0 : retval = -1;
3985 : : } else {
3986 : 0 : retval = 0;
3987 : : }
3988 : :
3989 : 0 : BIO_free(biobuf);
3990 : 0 : return retval;
3991 : : }
3992 : :
3993 : :
3994 : : /*[clinic input]
3995 : : _ssl._SSLContext.load_verify_locations
3996 : : cafile: object = None
3997 : : capath: object = None
3998 : : cadata: object = None
3999 : :
4000 : : [clinic start generated code]*/
4001 : :
4002 : : static PyObject *
4003 : 0 : _ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4004 : : PyObject *cafile,
4005 : : PyObject *capath,
4006 : : PyObject *cadata)
4007 : : /*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
4008 : : {
4009 : 0 : PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4010 : 0 : const char *cafile_buf = NULL, *capath_buf = NULL;
4011 : 0 : int r = 0, ok = 1;
4012 : :
4013 : 0 : errno = 0;
4014 [ # # ]: 0 : if (cafile == Py_None)
4015 : 0 : cafile = NULL;
4016 [ # # ]: 0 : if (capath == Py_None)
4017 : 0 : capath = NULL;
4018 [ # # ]: 0 : if (cadata == Py_None)
4019 : 0 : cadata = NULL;
4020 : :
4021 [ # # # # : 0 : if (cafile == NULL && capath == NULL && cadata == NULL) {
# # ]
4022 : 0 : PyErr_SetString(PyExc_TypeError,
4023 : : "cafile, capath and cadata cannot be all omitted");
4024 : 0 : goto error;
4025 : : }
4026 [ # # # # ]: 0 : if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
4027 [ # # ]: 0 : if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4028 : 0 : PyErr_SetString(PyExc_TypeError,
4029 : : "cafile should be a valid filesystem path");
4030 : : }
4031 : 0 : goto error;
4032 : : }
4033 [ # # # # ]: 0 : if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
4034 [ # # ]: 0 : if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4035 : 0 : PyErr_SetString(PyExc_TypeError,
4036 : : "capath should be a valid filesystem path");
4037 : : }
4038 : 0 : goto error;
4039 : : }
4040 : :
4041 : : /* validate cadata type and load cadata */
4042 [ # # ]: 0 : if (cadata) {
4043 [ # # ]: 0 : if (PyUnicode_Check(cadata)) {
4044 : 0 : PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4045 [ # # ]: 0 : if (cadata_ascii == NULL) {
4046 [ # # ]: 0 : if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4047 : 0 : goto invalid_cadata;
4048 : : }
4049 : 0 : goto error;
4050 : : }
4051 : 0 : r = _add_ca_certs(self,
4052 : 0 : PyBytes_AS_STRING(cadata_ascii),
4053 : : PyBytes_GET_SIZE(cadata_ascii),
4054 : : SSL_FILETYPE_PEM);
4055 : 0 : Py_DECREF(cadata_ascii);
4056 [ # # ]: 0 : if (r == -1) {
4057 : 0 : goto error;
4058 : : }
4059 : : }
4060 [ # # ]: 0 : else if (PyObject_CheckBuffer(cadata)) {
4061 : : Py_buffer buf;
4062 [ # # ]: 0 : if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4063 : 0 : goto error;
4064 : : }
4065 [ # # # # ]: 0 : if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4066 : 0 : PyBuffer_Release(&buf);
4067 : 0 : PyErr_SetString(PyExc_TypeError,
4068 : : "cadata should be a contiguous buffer with "
4069 : : "a single dimension");
4070 : 0 : goto error;
4071 : : }
4072 : 0 : r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4073 : 0 : PyBuffer_Release(&buf);
4074 [ # # ]: 0 : if (r == -1) {
4075 : 0 : goto error;
4076 : : }
4077 : : }
4078 : : else {
4079 : 0 : invalid_cadata:
4080 : 0 : PyErr_SetString(PyExc_TypeError,
4081 : : "cadata should be an ASCII string or a "
4082 : : "bytes-like object");
4083 : 0 : goto error;
4084 : : }
4085 : : }
4086 : :
4087 : : /* load cafile or capath */
4088 [ # # # # ]: 0 : if (cafile || capath) {
4089 [ # # ]: 0 : if (cafile)
4090 : 0 : cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4091 [ # # ]: 0 : if (capath)
4092 : 0 : capath_buf = PyBytes_AS_STRING(capath_bytes);
4093 : 0 : PySSL_BEGIN_ALLOW_THREADS
4094 : 0 : r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4095 : 0 : PySSL_END_ALLOW_THREADS
4096 [ # # ]: 0 : if (r != 1) {
4097 [ # # ]: 0 : if (errno != 0) {
4098 : 0 : ERR_clear_error();
4099 : 0 : PyErr_SetFromErrno(PyExc_OSError);
4100 : : }
4101 : : else {
4102 : 0 : _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
4103 : : }
4104 : 0 : goto error;
4105 : : }
4106 : : }
4107 : 0 : goto end;
4108 : :
4109 : 0 : error:
4110 : 0 : ok = 0;
4111 : 0 : end:
4112 : 0 : Py_XDECREF(cafile_bytes);
4113 : 0 : Py_XDECREF(capath_bytes);
4114 [ # # ]: 0 : if (ok) {
4115 : 0 : Py_RETURN_NONE;
4116 : : } else {
4117 : 0 : return NULL;
4118 : : }
4119 : : }
4120 : :
4121 : : /*[clinic input]
4122 : : _ssl._SSLContext.load_dh_params
4123 : : path as filepath: object
4124 : : /
4125 : :
4126 : : [clinic start generated code]*/
4127 : :
4128 : : static PyObject *
4129 : 0 : _ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4130 : : /*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
4131 : : {
4132 : : FILE *f;
4133 : : DH *dh;
4134 : :
4135 : 0 : f = _Py_fopen_obj(filepath, "rb");
4136 [ # # ]: 0 : if (f == NULL)
4137 : 0 : return NULL;
4138 : :
4139 : 0 : errno = 0;
4140 : 0 : PySSL_BEGIN_ALLOW_THREADS
4141 : 0 : dh = PEM_read_DHparams(f, NULL, NULL, NULL);
4142 : 0 : fclose(f);
4143 : 0 : PySSL_END_ALLOW_THREADS
4144 [ # # ]: 0 : if (dh == NULL) {
4145 [ # # ]: 0 : if (errno != 0) {
4146 : 0 : ERR_clear_error();
4147 : 0 : PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4148 : : }
4149 : : else {
4150 : 0 : _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
4151 : : }
4152 : 0 : return NULL;
4153 : : }
4154 [ # # ]: 0 : if (!SSL_CTX_set_tmp_dh(self->ctx, dh)) {
4155 : 0 : DH_free(dh);
4156 : 0 : return _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
4157 : : }
4158 : 0 : DH_free(dh);
4159 : 0 : Py_RETURN_NONE;
4160 : : }
4161 : :
4162 : : /*[clinic input]
4163 : : _ssl._SSLContext._wrap_socket
4164 : : sock: object(subclass_of="get_state_ctx(self)->Sock_Type")
4165 : : server_side: bool
4166 : : server_hostname as hostname_obj: object = None
4167 : : *
4168 : : owner: object = None
4169 : : session: object = None
4170 : :
4171 : : [clinic start generated code]*/
4172 : :
4173 : : static PyObject *
4174 : 0 : _ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
4175 : : int server_side, PyObject *hostname_obj,
4176 : : PyObject *owner, PyObject *session)
4177 : : /*[clinic end generated code: output=f103f238633940b4 input=700ca8fedff53994]*/
4178 : : {
4179 : 0 : char *hostname = NULL;
4180 : : PyObject *res;
4181 : :
4182 : : /* server_hostname is either None (or absent), or to be encoded
4183 : : as IDN A-label (ASCII str) without NULL bytes. */
4184 [ # # ]: 0 : if (hostname_obj != Py_None) {
4185 [ # # ]: 0 : if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
4186 : 0 : return NULL;
4187 : : }
4188 : :
4189 : 0 : res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4190 : : server_side, hostname,
4191 : : owner, session,
4192 : : NULL, NULL);
4193 [ # # ]: 0 : if (hostname != NULL)
4194 : 0 : PyMem_Free(hostname);
4195 : 0 : return res;
4196 : : }
4197 : :
4198 : : /*[clinic input]
4199 : : _ssl._SSLContext._wrap_bio
4200 : : incoming: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4201 : : outgoing: object(subclass_of="get_state_ctx(self)->PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4202 : : server_side: bool
4203 : : server_hostname as hostname_obj: object = None
4204 : : *
4205 : : owner: object = None
4206 : : session: object = None
4207 : :
4208 : : [clinic start generated code]*/
4209 : :
4210 : : static PyObject *
4211 : 0 : _ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4212 : : PySSLMemoryBIO *outgoing, int server_side,
4213 : : PyObject *hostname_obj, PyObject *owner,
4214 : : PyObject *session)
4215 : : /*[clinic end generated code: output=5c5d6d9b41f99332 input=a9205d097fd45a82]*/
4216 : : {
4217 : 0 : char *hostname = NULL;
4218 : : PyObject *res;
4219 : :
4220 : : /* server_hostname is either None (or absent), or to be encoded
4221 : : as IDN A-label (ASCII str) without NULL bytes. */
4222 [ # # ]: 0 : if (hostname_obj != Py_None) {
4223 [ # # ]: 0 : if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
4224 : 0 : return NULL;
4225 : : }
4226 : :
4227 : 0 : res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
4228 : : owner, session,
4229 : : incoming, outgoing);
4230 : :
4231 : 0 : PyMem_Free(hostname);
4232 : 0 : return res;
4233 : : }
4234 : :
4235 : : /*[clinic input]
4236 : : _ssl._SSLContext.session_stats
4237 : : [clinic start generated code]*/
4238 : :
4239 : : static PyObject *
4240 : 0 : _ssl__SSLContext_session_stats_impl(PySSLContext *self)
4241 : : /*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
4242 : : {
4243 : : int r;
4244 : 0 : PyObject *value, *stats = PyDict_New();
4245 [ # # ]: 0 : if (!stats)
4246 : 0 : return NULL;
4247 : :
4248 : : #define ADD_STATS(SSL_NAME, KEY_NAME) \
4249 : : value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4250 : : if (value == NULL) \
4251 : : goto error; \
4252 : : r = PyDict_SetItemString(stats, KEY_NAME, value); \
4253 : : Py_DECREF(value); \
4254 : : if (r < 0) \
4255 : : goto error;
4256 : :
4257 [ # # # # ]: 0 : ADD_STATS(number, "number");
4258 [ # # # # ]: 0 : ADD_STATS(connect, "connect");
4259 [ # # # # ]: 0 : ADD_STATS(connect_good, "connect_good");
4260 [ # # # # ]: 0 : ADD_STATS(connect_renegotiate, "connect_renegotiate");
4261 [ # # # # ]: 0 : ADD_STATS(accept, "accept");
4262 [ # # # # ]: 0 : ADD_STATS(accept_good, "accept_good");
4263 [ # # # # ]: 0 : ADD_STATS(accept_renegotiate, "accept_renegotiate");
4264 [ # # # # ]: 0 : ADD_STATS(accept, "accept");
4265 [ # # # # ]: 0 : ADD_STATS(hits, "hits");
4266 [ # # # # ]: 0 : ADD_STATS(misses, "misses");
4267 [ # # # # ]: 0 : ADD_STATS(timeouts, "timeouts");
4268 [ # # # # ]: 0 : ADD_STATS(cache_full, "cache_full");
4269 : :
4270 : : #undef ADD_STATS
4271 : :
4272 : 0 : return stats;
4273 : :
4274 : 0 : error:
4275 : 0 : Py_DECREF(stats);
4276 : 0 : return NULL;
4277 : : }
4278 : :
4279 : : /*[clinic input]
4280 : : _ssl._SSLContext.set_default_verify_paths
4281 : : [clinic start generated code]*/
4282 : :
4283 : : static PyObject *
4284 : 0 : _ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4285 : : /*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
4286 : : {
4287 : : int rc;
4288 : 0 : Py_BEGIN_ALLOW_THREADS
4289 : 0 : rc = SSL_CTX_set_default_verify_paths(self->ctx);
4290 : 0 : Py_END_ALLOW_THREADS
4291 [ # # ]: 0 : if (!rc) {
4292 : 0 : _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
4293 : 0 : return NULL;
4294 : : }
4295 : 0 : Py_RETURN_NONE;
4296 : : }
4297 : :
4298 : : /*[clinic input]
4299 : : _ssl._SSLContext.set_ecdh_curve
4300 : : name: object
4301 : : /
4302 : :
4303 : : [clinic start generated code]*/
4304 : :
4305 : : static PyObject *
4306 : 0 : _ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4307 : : /*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
4308 : : {
4309 : : PyObject *name_bytes;
4310 : : int nid;
4311 : : EC_KEY *key;
4312 : :
4313 [ # # ]: 0 : if (!PyUnicode_FSConverter(name, &name_bytes))
4314 : 0 : return NULL;
4315 : : assert(PyBytes_Check(name_bytes));
4316 : 0 : nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4317 : 0 : Py_DECREF(name_bytes);
4318 [ # # ]: 0 : if (nid == 0) {
4319 : 0 : PyErr_Format(PyExc_ValueError,
4320 : : "unknown elliptic curve name %R", name);
4321 : 0 : return NULL;
4322 : : }
4323 : 0 : key = EC_KEY_new_by_curve_name(nid);
4324 [ # # ]: 0 : if (key == NULL) {
4325 : 0 : _setSSLError(get_state_ctx(self), NULL, 0, __FILE__, __LINE__);
4326 : 0 : return NULL;
4327 : : }
4328 : 0 : SSL_CTX_set_tmp_ecdh(self->ctx, key);
4329 : 0 : EC_KEY_free(key);
4330 : 0 : Py_RETURN_NONE;
4331 : : }
4332 : :
4333 : : static int
4334 : 0 : _servername_callback(SSL *s, int *al, void *args)
4335 : : {
4336 : : int ret;
4337 : 0 : PySSLContext *sslctx = (PySSLContext *) args;
4338 : : PySSLSocket *ssl;
4339 : : PyObject *result;
4340 : : /* The high-level ssl.SSLSocket object */
4341 : : PyObject *ssl_socket;
4342 : 0 : const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
4343 : 0 : PyGILState_STATE gstate = PyGILState_Ensure();
4344 : :
4345 [ # # ]: 0 : if (sslctx->set_sni_cb == NULL) {
4346 : : /* remove race condition in this the call back while if removing the
4347 : : * callback is in progress */
4348 : 0 : PyGILState_Release(gstate);
4349 : 0 : return SSL_TLSEXT_ERR_OK;
4350 : : }
4351 : :
4352 : 0 : ssl = SSL_get_app_data(s);
4353 : : assert(Py_IS_TYPE(ssl, get_state_ctx(sslctx)->PySSLSocket_Type));
4354 : :
4355 : : /* The servername callback expects an argument that represents the current
4356 : : * SSL connection and that has a .context attribute that can be changed to
4357 : : * identify the requested hostname. Since the official API is the Python
4358 : : * level API we want to pass the callback a Python level object rather than
4359 : : * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4360 : : * SSLObject) that will be passed. Otherwise if there's a socket then that
4361 : : * will be passed. If both do not exist only then the C-level object is
4362 : : * passed. */
4363 [ # # ]: 0 : if (ssl->owner)
4364 : 0 : ssl_socket = PyWeakref_GetObject(ssl->owner);
4365 [ # # ]: 0 : else if (ssl->Socket)
4366 : 0 : ssl_socket = PyWeakref_GetObject(ssl->Socket);
4367 : : else
4368 : 0 : ssl_socket = (PyObject *) ssl;
4369 : :
4370 : 0 : Py_INCREF(ssl_socket);
4371 [ # # ]: 0 : if (ssl_socket == Py_None)
4372 : 0 : goto error;
4373 : :
4374 [ # # ]: 0 : if (servername == NULL) {
4375 : 0 : result = PyObject_CallFunctionObjArgs(sslctx->set_sni_cb, ssl_socket,
4376 : : Py_None, sslctx, NULL);
4377 : : }
4378 : : else {
4379 : : PyObject *servername_bytes;
4380 : : PyObject *servername_str;
4381 : :
4382 : 0 : servername_bytes = PyBytes_FromString(servername);
4383 [ # # ]: 0 : if (servername_bytes == NULL) {
4384 : 0 : PyErr_WriteUnraisable((PyObject *) sslctx);
4385 : 0 : goto error;
4386 : : }
4387 : : /* server_hostname was encoded to an A-label by our caller; put it
4388 : : * back into a str object, but still as an A-label (bpo-28414)
4389 : : */
4390 : 0 : servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4391 [ # # ]: 0 : if (servername_str == NULL) {
4392 : 0 : PyErr_WriteUnraisable(servername_bytes);
4393 : 0 : Py_DECREF(servername_bytes);
4394 : 0 : goto error;
4395 : : }
4396 : 0 : Py_DECREF(servername_bytes);
4397 : 0 : result = PyObject_CallFunctionObjArgs(
4398 : : sslctx->set_sni_cb, ssl_socket, servername_str,
4399 : : sslctx, NULL);
4400 : 0 : Py_DECREF(servername_str);
4401 : : }
4402 : 0 : Py_DECREF(ssl_socket);
4403 : :
4404 [ # # ]: 0 : if (result == NULL) {
4405 : 0 : PyErr_WriteUnraisable(sslctx->set_sni_cb);
4406 : 0 : *al = SSL_AD_HANDSHAKE_FAILURE;
4407 : 0 : ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4408 : : }
4409 : : else {
4410 : : /* Result may be None, a SSLContext or an integer
4411 : : * None and SSLContext are OK, integer or other values are an error.
4412 : : */
4413 [ # # ]: 0 : if (result == Py_None) {
4414 : 0 : ret = SSL_TLSEXT_ERR_OK;
4415 : : } else {
4416 : 0 : *al = (int) PyLong_AsLong(result);
4417 [ # # ]: 0 : if (PyErr_Occurred()) {
4418 : 0 : PyErr_WriteUnraisable(result);
4419 : 0 : *al = SSL_AD_INTERNAL_ERROR;
4420 : : }
4421 : 0 : ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4422 : : }
4423 : 0 : Py_DECREF(result);
4424 : : }
4425 : :
4426 : 0 : PyGILState_Release(gstate);
4427 : 0 : return ret;
4428 : :
4429 : 0 : error:
4430 : 0 : Py_DECREF(ssl_socket);
4431 : 0 : *al = SSL_AD_INTERNAL_ERROR;
4432 : 0 : ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4433 : 0 : PyGILState_Release(gstate);
4434 : 0 : return ret;
4435 : : }
4436 : :
4437 : : static PyObject *
4438 : 0 : get_sni_callback(PySSLContext *self, void *c)
4439 : : {
4440 : 0 : PyObject *cb = self->set_sni_cb;
4441 [ # # ]: 0 : if (cb == NULL) {
4442 : 0 : Py_RETURN_NONE;
4443 : : }
4444 : 0 : return Py_NewRef(cb);
4445 : : }
4446 : :
4447 : : static int
4448 : 0 : set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4449 : : {
4450 [ # # ]: 0 : if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4451 : 0 : PyErr_SetString(PyExc_ValueError,
4452 : : "sni_callback cannot be set on TLS_CLIENT context");
4453 : 0 : return -1;
4454 : : }
4455 [ # # ]: 0 : Py_CLEAR(self->set_sni_cb);
4456 [ # # ]: 0 : if (arg == Py_None) {
4457 : 0 : SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4458 : : }
4459 : : else {
4460 [ # # ]: 0 : if (!PyCallable_Check(arg)) {
4461 : 0 : SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4462 : 0 : PyErr_SetString(PyExc_TypeError,
4463 : : "not a callable object");
4464 : 0 : return -1;
4465 : : }
4466 : 0 : self->set_sni_cb = Py_NewRef(arg);
4467 : 0 : SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4468 : 0 : SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4469 : : }
4470 : 0 : return 0;
4471 : : }
4472 : :
4473 : : PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4474 : : "Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4475 : : \n\
4476 : : If the argument is None then the callback is disabled. The method is called\n\
4477 : : with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4478 : : See RFC 6066 for details of the SNI extension.");
4479 : :
4480 : : /*[clinic input]
4481 : : _ssl._SSLContext.cert_store_stats
4482 : :
4483 : : Returns quantities of loaded X.509 certificates.
4484 : :
4485 : : X.509 certificates with a CA extension and certificate revocation lists
4486 : : inside the context's cert store.
4487 : :
4488 : : NOTE: Certificates in a capath directory aren't loaded unless they have
4489 : : been used at least once.
4490 : : [clinic start generated code]*/
4491 : :
4492 : : static PyObject *
4493 : 0 : _ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4494 : : /*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
4495 : : {
4496 : : X509_STORE *store;
4497 : : STACK_OF(X509_OBJECT) *objs;
4498 : : X509_OBJECT *obj;
4499 : 0 : int x509 = 0, crl = 0, ca = 0, i;
4500 : :
4501 : 0 : store = SSL_CTX_get_cert_store(self->ctx);
4502 : 0 : objs = X509_STORE_get0_objects(store);
4503 [ # # ]: 0 : for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4504 : 0 : obj = sk_X509_OBJECT_value(objs, i);
4505 [ # # # ]: 0 : switch (X509_OBJECT_get_type(obj)) {
4506 : 0 : case X509_LU_X509:
4507 : 0 : x509++;
4508 [ # # ]: 0 : if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
4509 : 0 : ca++;
4510 : : }
4511 : 0 : break;
4512 : 0 : case X509_LU_CRL:
4513 : 0 : crl++;
4514 : 0 : break;
4515 : 0 : default:
4516 : : /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4517 : : * As far as I can tell they are internal states and never
4518 : : * stored in a cert store */
4519 : 0 : break;
4520 : : }
4521 : : }
4522 : 0 : return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4523 : : "x509_ca", ca);
4524 : : }
4525 : :
4526 : : /*[clinic input]
4527 : : _ssl._SSLContext.get_ca_certs
4528 : : binary_form: bool = False
4529 : :
4530 : : Returns a list of dicts with information of loaded CA certs.
4531 : :
4532 : : If the optional argument is True, returns a DER-encoded copy of the CA
4533 : : certificate.
4534 : :
4535 : : NOTE: Certificates in a capath directory aren't loaded unless they have
4536 : : been used at least once.
4537 : : [clinic start generated code]*/
4538 : :
4539 : : static PyObject *
4540 : 0 : _ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4541 : : /*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
4542 : : {
4543 : : X509_STORE *store;
4544 : : STACK_OF(X509_OBJECT) *objs;
4545 : 0 : PyObject *ci = NULL, *rlist = NULL;
4546 : : int i;
4547 : :
4548 [ # # ]: 0 : if ((rlist = PyList_New(0)) == NULL) {
4549 : 0 : return NULL;
4550 : : }
4551 : :
4552 : 0 : store = SSL_CTX_get_cert_store(self->ctx);
4553 : 0 : objs = X509_STORE_get0_objects(store);
4554 [ # # ]: 0 : for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4555 : : X509_OBJECT *obj;
4556 : : X509 *cert;
4557 : :
4558 : 0 : obj = sk_X509_OBJECT_value(objs, i);
4559 [ # # ]: 0 : if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
4560 : : /* not a x509 cert */
4561 : 0 : continue;
4562 : : }
4563 : : /* CA for any purpose */
4564 : 0 : cert = X509_OBJECT_get0_X509(obj);
4565 [ # # ]: 0 : if (!X509_check_ca(cert)) {
4566 : 0 : continue;
4567 : : }
4568 [ # # ]: 0 : if (binary_form) {
4569 : 0 : ci = _certificate_to_der(get_state_ctx(self), cert);
4570 : : } else {
4571 : 0 : ci = _decode_certificate(get_state_ctx(self), cert);
4572 : : }
4573 [ # # ]: 0 : if (ci == NULL) {
4574 : 0 : goto error;
4575 : : }
4576 [ # # ]: 0 : if (PyList_Append(rlist, ci) == -1) {
4577 : 0 : goto error;
4578 : : }
4579 [ # # ]: 0 : Py_CLEAR(ci);
4580 : : }
4581 : 0 : return rlist;
4582 : :
4583 : 0 : error:
4584 : 0 : Py_XDECREF(ci);
4585 : 0 : Py_XDECREF(rlist);
4586 : 0 : return NULL;
4587 : : }
4588 : :
4589 : :
4590 : : static PyGetSetDef context_getsetlist[] = {
4591 : : {"check_hostname", (getter) get_check_hostname,
4592 : : (setter) set_check_hostname, NULL},
4593 : : {"_host_flags", (getter) get_host_flags,
4594 : : (setter) set_host_flags, NULL},
4595 : : {"minimum_version", (getter) get_minimum_version,
4596 : : (setter) set_minimum_version, NULL},
4597 : : {"maximum_version", (getter) get_maximum_version,
4598 : : (setter) set_maximum_version, NULL},
4599 : : {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4600 : : (setter) _PySSLContext_set_keylog_filename, NULL},
4601 : : {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4602 : : (setter) _PySSLContext_set_msg_callback, NULL},
4603 : : {"sni_callback", (getter) get_sni_callback,
4604 : : (setter) set_sni_callback, PySSLContext_sni_callback_doc},
4605 : : #ifdef TLS1_3_VERSION
4606 : : {"num_tickets", (getter) get_num_tickets,
4607 : : (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4608 : : #endif
4609 : : {"options", (getter) get_options,
4610 : : (setter) set_options, NULL},
4611 : : {"post_handshake_auth", (getter) get_post_handshake_auth,
4612 : : #ifdef TLS1_3_VERSION
4613 : : (setter) set_post_handshake_auth,
4614 : : #else
4615 : : NULL,
4616 : : #endif
4617 : : NULL},
4618 : : {"protocol", (getter) get_protocol,
4619 : : NULL, NULL},
4620 : : {"verify_flags", (getter) get_verify_flags,
4621 : : (setter) set_verify_flags, NULL},
4622 : : {"verify_mode", (getter) get_verify_mode,
4623 : : (setter) set_verify_mode, NULL},
4624 : : {"security_level", (getter) get_security_level,
4625 : : NULL, PySSLContext_security_level_doc},
4626 : : {NULL}, /* sentinel */
4627 : : };
4628 : :
4629 : : static struct PyMethodDef context_methods[] = {
4630 : : _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4631 : : _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4632 : : _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4633 : : _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4634 : : _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4635 : : _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4636 : : _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4637 : : _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4638 : : _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4639 : : _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4640 : : _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4641 : : _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
4642 : : _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
4643 : : {NULL, NULL} /* sentinel */
4644 : : };
4645 : :
4646 : : static PyType_Slot PySSLContext_slots[] = {
4647 : : {Py_tp_methods, context_methods},
4648 : : {Py_tp_getset, context_getsetlist},
4649 : : {Py_tp_new, _ssl__SSLContext},
4650 : : {Py_tp_dealloc, context_dealloc},
4651 : : {Py_tp_traverse, context_traverse},
4652 : : {Py_tp_clear, context_clear},
4653 : : {0, 0},
4654 : : };
4655 : :
4656 : : static PyType_Spec PySSLContext_spec = {
4657 : : .name = "_ssl._SSLContext",
4658 : : .basicsize = sizeof(PySSLContext),
4659 : : .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
4660 : : Py_TPFLAGS_IMMUTABLETYPE),
4661 : : .slots = PySSLContext_slots,
4662 : : };
4663 : :
4664 : :
4665 : : /*
4666 : : * MemoryBIO objects
4667 : : */
4668 : :
4669 : : /*[clinic input]
4670 : : @classmethod
4671 : : _ssl.MemoryBIO.__new__
4672 : :
4673 : : [clinic start generated code]*/
4674 : :
4675 : : static PyObject *
4676 : 0 : _ssl_MemoryBIO_impl(PyTypeObject *type)
4677 : : /*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
4678 : : {
4679 : : BIO *bio;
4680 : : PySSLMemoryBIO *self;
4681 : :
4682 : 0 : bio = BIO_new(BIO_s_mem());
4683 [ # # ]: 0 : if (bio == NULL) {
4684 : 0 : PyErr_SetString(PyExc_MemoryError, "failed to allocate BIO");
4685 : 0 : return NULL;
4686 : : }
4687 : : /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4688 : : * just that no data is currently available. The SSL routines should retry
4689 : : * the read, which we can achieve by calling BIO_set_retry_read(). */
4690 : 0 : BIO_set_retry_read(bio);
4691 : 0 : BIO_set_mem_eof_return(bio, -1);
4692 : :
4693 : : assert(type != NULL && type->tp_alloc != NULL);
4694 : 0 : self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4695 [ # # ]: 0 : if (self == NULL) {
4696 : 0 : BIO_free(bio);
4697 : 0 : return NULL;
4698 : : }
4699 : 0 : self->bio = bio;
4700 : 0 : self->eof_written = 0;
4701 : :
4702 : 0 : return (PyObject *) self;
4703 : : }
4704 : :
4705 : : static int
4706 : 0 : memory_bio_traverse(PySSLMemoryBIO *self, visitproc visit, void *arg)
4707 : : {
4708 [ # # # # ]: 0 : Py_VISIT(Py_TYPE(self));
4709 : 0 : return 0;
4710 : : }
4711 : :
4712 : : static void
4713 : 0 : memory_bio_dealloc(PySSLMemoryBIO *self)
4714 : : {
4715 : 0 : PyTypeObject *tp = Py_TYPE(self);
4716 : 0 : PyObject_GC_UnTrack(self);
4717 : 0 : BIO_free(self->bio);
4718 : 0 : Py_TYPE(self)->tp_free(self);
4719 : 0 : Py_DECREF(tp);
4720 : 0 : }
4721 : :
4722 : : static PyObject *
4723 : 0 : memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4724 : : {
4725 : 0 : return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
4726 : : }
4727 : :
4728 : : PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4729 : : "The number of bytes pending in the memory BIO.");
4730 : :
4731 : : static PyObject *
4732 : 0 : memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4733 : : {
4734 : 0 : return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4735 [ # # # # ]: 0 : && self->eof_written);
4736 : : }
4737 : :
4738 : : PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4739 : : "Whether the memory BIO is at EOF.");
4740 : :
4741 : : /*[clinic input]
4742 : : _ssl.MemoryBIO.read
4743 : : size as len: int = -1
4744 : : /
4745 : :
4746 : : Read up to size bytes from the memory BIO.
4747 : :
4748 : : If size is not specified, read the entire buffer.
4749 : : If the return value is an empty bytes instance, this means either
4750 : : EOF or that no data is available. Use the "eof" property to
4751 : : distinguish between the two.
4752 : : [clinic start generated code]*/
4753 : :
4754 : : static PyObject *
4755 : 0 : _ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4756 : : /*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4757 : : {
4758 : : int avail, nbytes;
4759 : : PyObject *result;
4760 : :
4761 [ # # ]: 0 : avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
4762 [ # # # # ]: 0 : if ((len < 0) || (len > avail))
4763 : 0 : len = avail;
4764 : :
4765 : 0 : result = PyBytes_FromStringAndSize(NULL, len);
4766 [ # # # # ]: 0 : if ((result == NULL) || (len == 0))
4767 : 0 : return result;
4768 : :
4769 : 0 : nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4770 [ # # ]: 0 : if (nbytes < 0) {
4771 : 0 : _sslmodulestate *state = get_state_mbio(self);
4772 : 0 : Py_DECREF(result);
4773 : 0 : _setSSLError(state, NULL, 0, __FILE__, __LINE__);
4774 : 0 : return NULL;
4775 : : }
4776 : :
4777 : : /* There should never be any short reads but check anyway. */
4778 [ # # ]: 0 : if (nbytes < len) {
4779 : 0 : _PyBytes_Resize(&result, nbytes);
4780 : : }
4781 : :
4782 : 0 : return result;
4783 : : }
4784 : :
4785 : : /*[clinic input]
4786 : : _ssl.MemoryBIO.write
4787 : : b: Py_buffer
4788 : : /
4789 : :
4790 : : Writes the bytes b into the memory BIO.
4791 : :
4792 : : Returns the number of bytes written.
4793 : : [clinic start generated code]*/
4794 : :
4795 : : static PyObject *
4796 : 0 : _ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4797 : : /*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
4798 : : {
4799 : : int nbytes;
4800 : :
4801 [ # # ]: 0 : if (b->len > INT_MAX) {
4802 : 0 : PyErr_Format(PyExc_OverflowError,
4803 : : "string longer than %d bytes", INT_MAX);
4804 : 0 : return NULL;
4805 : : }
4806 : :
4807 [ # # ]: 0 : if (self->eof_written) {
4808 : 0 : PyObject *module = PyType_GetModule(Py_TYPE(self));
4809 [ # # ]: 0 : if (module == NULL)
4810 : 0 : return NULL;
4811 : 0 : PyErr_SetString(get_ssl_state(module)->PySSLErrorObject,
4812 : : "cannot write() after write_eof()");
4813 : 0 : return NULL;
4814 : : }
4815 : :
4816 : 0 : nbytes = BIO_write(self->bio, b->buf, (int)b->len);
4817 [ # # ]: 0 : if (nbytes < 0) {
4818 : 0 : _sslmodulestate *state = get_state_mbio(self);
4819 : 0 : _setSSLError(state, NULL, 0, __FILE__, __LINE__);
4820 : 0 : return NULL;
4821 : : }
4822 : :
4823 : 0 : return PyLong_FromLong(nbytes);
4824 : : }
4825 : :
4826 : : /*[clinic input]
4827 : : _ssl.MemoryBIO.write_eof
4828 : :
4829 : : Write an EOF marker to the memory BIO.
4830 : :
4831 : : When all data has been read, the "eof" property will be True.
4832 : : [clinic start generated code]*/
4833 : :
4834 : : static PyObject *
4835 : 0 : _ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4836 : : /*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
4837 : : {
4838 : 0 : self->eof_written = 1;
4839 : : /* After an EOF is written, a zero return from read() should be a real EOF
4840 : : * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4841 : 0 : BIO_clear_retry_flags(self->bio);
4842 : 0 : BIO_set_mem_eof_return(self->bio, 0);
4843 : :
4844 : 0 : Py_RETURN_NONE;
4845 : : }
4846 : :
4847 : : static PyGetSetDef memory_bio_getsetlist[] = {
4848 : : {"pending", (getter) memory_bio_get_pending, NULL,
4849 : : PySSL_memory_bio_pending_doc},
4850 : : {"eof", (getter) memory_bio_get_eof, NULL,
4851 : : PySSL_memory_bio_eof_doc},
4852 : : {NULL}, /* sentinel */
4853 : : };
4854 : :
4855 : : static struct PyMethodDef memory_bio_methods[] = {
4856 : : _SSL_MEMORYBIO_READ_METHODDEF
4857 : : _SSL_MEMORYBIO_WRITE_METHODDEF
4858 : : _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
4859 : : {NULL, NULL} /* sentinel */
4860 : : };
4861 : :
4862 : : static PyType_Slot PySSLMemoryBIO_slots[] = {
4863 : : {Py_tp_methods, memory_bio_methods},
4864 : : {Py_tp_getset, memory_bio_getsetlist},
4865 : : {Py_tp_new, _ssl_MemoryBIO},
4866 : : {Py_tp_dealloc, memory_bio_dealloc},
4867 : : {Py_tp_traverse, memory_bio_traverse},
4868 : : {0, 0},
4869 : : };
4870 : :
4871 : : static PyType_Spec PySSLMemoryBIO_spec = {
4872 : : .name = "_ssl.MemoryBIO",
4873 : : .basicsize = sizeof(PySSLMemoryBIO),
4874 : : .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_IMMUTABLETYPE |
4875 : : Py_TPFLAGS_HAVE_GC),
4876 : : .slots = PySSLMemoryBIO_slots,
4877 : : };
4878 : :
4879 : : /*
4880 : : * SSL Session object
4881 : : */
4882 : :
4883 : : static void
4884 : 0 : PySSLSession_dealloc(PySSLSession *self)
4885 : : {
4886 : 0 : PyTypeObject *tp = Py_TYPE(self);
4887 : : /* bpo-31095: UnTrack is needed before calling any callbacks */
4888 : 0 : PyObject_GC_UnTrack(self);
4889 : 0 : Py_XDECREF(self->ctx);
4890 [ # # ]: 0 : if (self->session != NULL) {
4891 : 0 : SSL_SESSION_free(self->session);
4892 : : }
4893 : 0 : PyObject_GC_Del(self);
4894 : 0 : Py_DECREF(tp);
4895 : 0 : }
4896 : :
4897 : : static PyObject *
4898 : 0 : PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4899 : : {
4900 : : int result;
4901 : 0 : PyTypeObject *sesstype = ((PySSLSession*)left)->ctx->state->PySSLSession_Type;
4902 : :
4903 [ # # # # ]: 0 : if (left == NULL || right == NULL) {
4904 : 0 : PyErr_BadInternalCall();
4905 : 0 : return NULL;
4906 : : }
4907 : :
4908 [ # # # # ]: 0 : if (!Py_IS_TYPE(left, sesstype) || !Py_IS_TYPE(right, sesstype)) {
4909 : 0 : Py_RETURN_NOTIMPLEMENTED;
4910 : : }
4911 : :
4912 [ # # ]: 0 : if (left == right) {
4913 : 0 : result = 0;
4914 : : } else {
4915 : : const unsigned char *left_id, *right_id;
4916 : : unsigned int left_len, right_len;
4917 : 0 : left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4918 : : &left_len);
4919 : 0 : right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4920 : : &right_len);
4921 [ # # ]: 0 : if (left_len == right_len) {
4922 : 0 : result = memcmp(left_id, right_id, left_len);
4923 : : } else {
4924 : 0 : result = 1;
4925 : : }
4926 : : }
4927 : :
4928 [ # # # # ]: 0 : switch (op) {
4929 : 0 : case Py_EQ:
4930 [ # # ]: 0 : if (result == 0) {
4931 : 0 : Py_RETURN_TRUE;
4932 : : } else {
4933 : 0 : Py_RETURN_FALSE;
4934 : : }
4935 : : break;
4936 : 0 : case Py_NE:
4937 [ # # ]: 0 : if (result != 0) {
4938 : 0 : Py_RETURN_TRUE;
4939 : : } else {
4940 : 0 : Py_RETURN_FALSE;
4941 : : }
4942 : : break;
4943 : 0 : case Py_LT:
4944 : : case Py_LE:
4945 : : case Py_GT:
4946 : : case Py_GE:
4947 : 0 : Py_RETURN_NOTIMPLEMENTED;
4948 : : break;
4949 : 0 : default:
4950 : 0 : PyErr_BadArgument();
4951 : 0 : return NULL;
4952 : : }
4953 : : }
4954 : :
4955 : : static int
4956 : 0 : PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4957 : : {
4958 [ # # # # ]: 0 : Py_VISIT(self->ctx);
4959 [ # # # # ]: 0 : Py_VISIT(Py_TYPE(self));
4960 : 0 : return 0;
4961 : : }
4962 : :
4963 : : static int
4964 : 0 : PySSLSession_clear(PySSLSession *self)
4965 : : {
4966 [ # # ]: 0 : Py_CLEAR(self->ctx);
4967 : 0 : return 0;
4968 : : }
4969 : :
4970 : :
4971 : : static PyObject *
4972 : 0 : PySSLSession_get_time(PySSLSession *self, void *closure) {
4973 : 0 : return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4974 : : }
4975 : :
4976 : : PyDoc_STRVAR(PySSLSession_get_time_doc,
4977 : : "Session creation time (seconds since epoch).");
4978 : :
4979 : :
4980 : : static PyObject *
4981 : 0 : PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4982 : 0 : return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4983 : : }
4984 : :
4985 : : PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4986 : : "Session timeout (delta in seconds).");
4987 : :
4988 : :
4989 : : static PyObject *
4990 : 0 : PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4991 : 0 : unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4992 : 0 : return PyLong_FromUnsignedLong(hint);
4993 : : }
4994 : :
4995 : : PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4996 : : "Ticket life time hint.");
4997 : :
4998 : :
4999 : : static PyObject *
5000 : 0 : PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5001 : : const unsigned char *id;
5002 : : unsigned int len;
5003 : 0 : id = SSL_SESSION_get_id(self->session, &len);
5004 : 0 : return PyBytes_FromStringAndSize((const char *)id, len);
5005 : : }
5006 : :
5007 : : PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5008 : : "Session id");
5009 : :
5010 : :
5011 : : static PyObject *
5012 : 0 : PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5013 [ # # ]: 0 : if (SSL_SESSION_has_ticket(self->session)) {
5014 : 0 : Py_RETURN_TRUE;
5015 : : } else {
5016 : 0 : Py_RETURN_FALSE;
5017 : : }
5018 : : }
5019 : :
5020 : : PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5021 : : "Does the session contain a ticket?");
5022 : :
5023 : :
5024 : : static PyGetSetDef PySSLSession_getsetlist[] = {
5025 : : {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5026 : : PySSLSession_get_has_ticket_doc},
5027 : : {"id", (getter) PySSLSession_get_session_id, NULL,
5028 : : PySSLSession_get_session_id_doc},
5029 : : {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5030 : : NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5031 : : {"time", (getter) PySSLSession_get_time, NULL,
5032 : : PySSLSession_get_time_doc},
5033 : : {"timeout", (getter) PySSLSession_get_timeout, NULL,
5034 : : PySSLSession_get_timeout_doc},
5035 : : {NULL}, /* sentinel */
5036 : : };
5037 : :
5038 : : static PyType_Slot PySSLSession_slots[] = {
5039 : : {Py_tp_getset,PySSLSession_getsetlist},
5040 : : {Py_tp_richcompare, PySSLSession_richcompare},
5041 : : {Py_tp_dealloc, PySSLSession_dealloc},
5042 : : {Py_tp_traverse, PySSLSession_traverse},
5043 : : {Py_tp_clear, PySSLSession_clear},
5044 : : {0, 0},
5045 : : };
5046 : :
5047 : : static PyType_Spec PySSLSession_spec = {
5048 : : .name = "_ssl.SSLSession",
5049 : : .basicsize = sizeof(PySSLSession),
5050 : : .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
5051 : : Py_TPFLAGS_IMMUTABLETYPE |
5052 : : Py_TPFLAGS_DISALLOW_INSTANTIATION),
5053 : : .slots = PySSLSession_slots,
5054 : : };
5055 : :
5056 : :
5057 : : /* helper routines for seeding the SSL PRNG */
5058 : : /*[clinic input]
5059 : : _ssl.RAND_add
5060 : : string as view: Py_buffer(accept={str, buffer})
5061 : : entropy: double
5062 : : /
5063 : :
5064 : : Mix string into the OpenSSL PRNG state.
5065 : :
5066 : : entropy (a float) is a lower bound on the entropy contained in
5067 : : string. See RFC 4086.
5068 : : [clinic start generated code]*/
5069 : :
5070 : : static PyObject *
5071 : 0 : _ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
5072 : : /*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
5073 : : {
5074 : : const char *buf;
5075 : : Py_ssize_t len, written;
5076 : :
5077 : 0 : buf = (const char *)view->buf;
5078 : 0 : len = view->len;
5079 : : do {
5080 : 0 : written = Py_MIN(len, INT_MAX);
5081 : 0 : RAND_add(buf, (int)written, entropy);
5082 : 0 : buf += written;
5083 : 0 : len -= written;
5084 [ # # ]: 0 : } while (len);
5085 : 0 : Py_RETURN_NONE;
5086 : : }
5087 : :
5088 : : static PyObject *
5089 : 0 : PySSL_RAND(PyObject *module, int len, int pseudo)
5090 : : {
5091 : : int ok;
5092 : : PyObject *bytes;
5093 : : unsigned long err;
5094 : : const char *errstr;
5095 : : PyObject *v;
5096 : :
5097 [ # # ]: 0 : if (len < 0) {
5098 : 0 : PyErr_SetString(PyExc_ValueError, "num must be positive");
5099 : 0 : return NULL;
5100 : : }
5101 : :
5102 : 0 : bytes = PyBytes_FromStringAndSize(NULL, len);
5103 [ # # ]: 0 : if (bytes == NULL)
5104 : 0 : return NULL;
5105 [ # # ]: 0 : if (pseudo) {
5106 : 0 : ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5107 [ # # # # ]: 0 : if (ok == 0 || ok == 1)
5108 [ # # ]: 0 : return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5109 : : }
5110 : : else {
5111 : 0 : ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5112 [ # # ]: 0 : if (ok == 1)
5113 : 0 : return bytes;
5114 : : }
5115 : 0 : Py_DECREF(bytes);
5116 : :
5117 : 0 : err = ERR_get_error();
5118 : 0 : errstr = ERR_reason_error_string(err);
5119 : 0 : v = Py_BuildValue("(ks)", err, errstr);
5120 [ # # ]: 0 : if (v != NULL) {
5121 : 0 : PyErr_SetObject(get_ssl_state(module)->PySSLErrorObject, v);
5122 : 0 : Py_DECREF(v);
5123 : : }
5124 : 0 : return NULL;
5125 : : }
5126 : :
5127 : : /*[clinic input]
5128 : : _ssl.RAND_bytes
5129 : : n: int
5130 : : /
5131 : :
5132 : : Generate n cryptographically strong pseudo-random bytes.
5133 : : [clinic start generated code]*/
5134 : :
5135 : : static PyObject *
5136 : 0 : _ssl_RAND_bytes_impl(PyObject *module, int n)
5137 : : /*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
5138 : : {
5139 : 0 : return PySSL_RAND(module, n, 0);
5140 : : }
5141 : :
5142 : :
5143 : : /*[clinic input]
5144 : : _ssl.RAND_status
5145 : :
5146 : : Returns True if the OpenSSL PRNG has been seeded with enough data and False if not.
5147 : :
5148 : : It is necessary to seed the PRNG with RAND_add() on some platforms before
5149 : : using the ssl() function.
5150 : : [clinic start generated code]*/
5151 : :
5152 : : static PyObject *
5153 : 0 : _ssl_RAND_status_impl(PyObject *module)
5154 : : /*[clinic end generated code: output=7e0aaa2d39fdc1ad input=d5ae5aea52f36e01]*/
5155 : : {
5156 : 0 : return PyBool_FromLong(RAND_status());
5157 : : }
5158 : :
5159 : : /*[clinic input]
5160 : : _ssl.get_default_verify_paths
5161 : :
5162 : : Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5163 : :
5164 : : The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5165 : : [clinic start generated code]*/
5166 : :
5167 : : static PyObject *
5168 : 0 : _ssl_get_default_verify_paths_impl(PyObject *module)
5169 : : /*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
5170 : : {
5171 : 0 : PyObject *ofile_env = NULL;
5172 : 0 : PyObject *ofile = NULL;
5173 : 0 : PyObject *odir_env = NULL;
5174 : 0 : PyObject *odir = NULL;
5175 : :
5176 : : #define CONVERT(info, target) { \
5177 : : const char *tmp = (info); \
5178 : : target = NULL; \
5179 : : if (!tmp) { target = Py_NewRef(Py_None); } \
5180 : : else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5181 : : target = PyBytes_FromString(tmp); } \
5182 : : if (!target) goto error; \
5183 : : }
5184 : :
5185 [ # # # # : 0 : CONVERT(X509_get_default_cert_file_env(), ofile_env);
# # ]
5186 [ # # # # : 0 : CONVERT(X509_get_default_cert_file(), ofile);
# # ]
5187 [ # # # # : 0 : CONVERT(X509_get_default_cert_dir_env(), odir_env);
# # ]
5188 [ # # # # : 0 : CONVERT(X509_get_default_cert_dir(), odir);
# # ]
5189 : : #undef CONVERT
5190 : :
5191 : 0 : return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
5192 : :
5193 : 0 : error:
5194 : 0 : Py_XDECREF(ofile_env);
5195 : 0 : Py_XDECREF(ofile);
5196 : 0 : Py_XDECREF(odir_env);
5197 : 0 : Py_XDECREF(odir);
5198 : 0 : return NULL;
5199 : : }
5200 : :
5201 : : static PyObject*
5202 : 4 : asn1obj2py(_sslmodulestate *state, ASN1_OBJECT *obj)
5203 : : {
5204 : : int nid;
5205 : : const char *ln, *sn;
5206 : :
5207 : 4 : nid = OBJ_obj2nid(obj);
5208 [ - + ]: 4 : if (nid == NID_undef) {
5209 : 0 : PyErr_Format(PyExc_ValueError, "Unknown object");
5210 : 0 : return NULL;
5211 : : }
5212 : 4 : sn = OBJ_nid2sn(nid);
5213 : 4 : ln = OBJ_nid2ln(nid);
5214 : 4 : return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(state, obj, 1));
5215 : : }
5216 : :
5217 : : /*[clinic input]
5218 : : _ssl.txt2obj
5219 : : txt: str
5220 : : name: bool = False
5221 : :
5222 : : Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5223 : :
5224 : : By default objects are looked up by OID. With name=True short and
5225 : : long name are also matched.
5226 : : [clinic start generated code]*/
5227 : :
5228 : : static PyObject *
5229 : 4 : _ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5230 : : /*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
5231 : : {
5232 : 4 : PyObject *result = NULL;
5233 : : ASN1_OBJECT *obj;
5234 : :
5235 : 4 : obj = OBJ_txt2obj(txt, name ? 0 : 1);
5236 [ - + ]: 4 : if (obj == NULL) {
5237 : 0 : PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
5238 : 0 : return NULL;
5239 : : }
5240 : 4 : result = asn1obj2py(get_ssl_state(module), obj);
5241 : 4 : ASN1_OBJECT_free(obj);
5242 : 4 : return result;
5243 : : }
5244 : :
5245 : : /*[clinic input]
5246 : : _ssl.nid2obj
5247 : : nid: int
5248 : : /
5249 : :
5250 : : Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5251 : : [clinic start generated code]*/
5252 : :
5253 : : static PyObject *
5254 : 0 : _ssl_nid2obj_impl(PyObject *module, int nid)
5255 : : /*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
5256 : : {
5257 : 0 : PyObject *result = NULL;
5258 : : ASN1_OBJECT *obj;
5259 : :
5260 [ # # ]: 0 : if (nid < NID_undef) {
5261 : 0 : PyErr_SetString(PyExc_ValueError, "NID must be positive.");
5262 : 0 : return NULL;
5263 : : }
5264 : 0 : obj = OBJ_nid2obj(nid);
5265 [ # # ]: 0 : if (obj == NULL) {
5266 : 0 : PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
5267 : 0 : return NULL;
5268 : : }
5269 : 0 : result = asn1obj2py(get_ssl_state(module), obj);
5270 : 0 : ASN1_OBJECT_free(obj);
5271 : 0 : return result;
5272 : : }
5273 : :
5274 : : #ifdef _MSC_VER
5275 : :
5276 : : static PyObject*
5277 : : certEncodingType(DWORD encodingType)
5278 : : {
5279 : : static PyObject *x509_asn = NULL;
5280 : : static PyObject *pkcs_7_asn = NULL;
5281 : :
5282 : : if (x509_asn == NULL) {
5283 : : x509_asn = PyUnicode_InternFromString("x509_asn");
5284 : : if (x509_asn == NULL)
5285 : : return NULL;
5286 : : }
5287 : : if (pkcs_7_asn == NULL) {
5288 : : pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5289 : : if (pkcs_7_asn == NULL)
5290 : : return NULL;
5291 : : }
5292 : : switch(encodingType) {
5293 : : case X509_ASN_ENCODING:
5294 : : return Py_NewRef(x509_asn);
5295 : : case PKCS_7_ASN_ENCODING:
5296 : : return Py_NewRef(pkcs_7_asn);
5297 : : default:
5298 : : return PyLong_FromLong(encodingType);
5299 : : }
5300 : : }
5301 : :
5302 : : static PyObject*
5303 : : parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5304 : : {
5305 : : CERT_ENHKEY_USAGE *usage;
5306 : : DWORD size, error, i;
5307 : : PyObject *retval;
5308 : :
5309 : : if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5310 : : error = GetLastError();
5311 : : if (error == CRYPT_E_NOT_FOUND) {
5312 : : Py_RETURN_TRUE;
5313 : : }
5314 : : return PyErr_SetFromWindowsErr(error);
5315 : : }
5316 : :
5317 : : usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5318 : : if (usage == NULL) {
5319 : : return PyErr_NoMemory();
5320 : : }
5321 : :
5322 : : /* Now get the actual enhanced usage property */
5323 : : if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5324 : : PyMem_Free(usage);
5325 : : error = GetLastError();
5326 : : if (error == CRYPT_E_NOT_FOUND) {
5327 : : Py_RETURN_TRUE;
5328 : : }
5329 : : return PyErr_SetFromWindowsErr(error);
5330 : : }
5331 : : retval = PyFrozenSet_New(NULL);
5332 : : if (retval == NULL) {
5333 : : goto error;
5334 : : }
5335 : : for (i = 0; i < usage->cUsageIdentifier; ++i) {
5336 : : if (usage->rgpszUsageIdentifier[i]) {
5337 : : PyObject *oid;
5338 : : int err;
5339 : : oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5340 : : if (oid == NULL) {
5341 : : Py_CLEAR(retval);
5342 : : goto error;
5343 : : }
5344 : : err = PySet_Add(retval, oid);
5345 : : Py_DECREF(oid);
5346 : : if (err == -1) {
5347 : : Py_CLEAR(retval);
5348 : : goto error;
5349 : : }
5350 : : }
5351 : : }
5352 : : error:
5353 : : PyMem_Free(usage);
5354 : : return retval;
5355 : : }
5356 : :
5357 : : static HCERTSTORE
5358 : : ssl_collect_certificates(const char *store_name)
5359 : : {
5360 : : /* this function collects the system certificate stores listed in
5361 : : * system_stores into a collection certificate store for being
5362 : : * enumerated. The store must be readable to be added to the
5363 : : * store collection.
5364 : : */
5365 : :
5366 : : HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5367 : : static DWORD system_stores[] = {
5368 : : CERT_SYSTEM_STORE_LOCAL_MACHINE,
5369 : : CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5370 : : CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5371 : : CERT_SYSTEM_STORE_CURRENT_USER,
5372 : : CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5373 : : CERT_SYSTEM_STORE_SERVICES,
5374 : : CERT_SYSTEM_STORE_USERS};
5375 : : size_t i, storesAdded;
5376 : : BOOL result;
5377 : :
5378 : : hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5379 : : (HCRYPTPROV)NULL, 0, NULL);
5380 : : if (!hCollectionStore) {
5381 : : return NULL;
5382 : : }
5383 : : storesAdded = 0;
5384 : : for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5385 : : hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5386 : : (HCRYPTPROV)NULL,
5387 : : CERT_STORE_READONLY_FLAG |
5388 : : system_stores[i], store_name);
5389 : : if (hSystemStore) {
5390 : : result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5391 : : CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5392 : : if (result) {
5393 : : ++storesAdded;
5394 : : }
5395 : : CertCloseStore(hSystemStore, 0); /* flag must be 0 */
5396 : : }
5397 : : }
5398 : : if (storesAdded == 0) {
5399 : : CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5400 : : return NULL;
5401 : : }
5402 : :
5403 : : return hCollectionStore;
5404 : : }
5405 : :
5406 : : /*[clinic input]
5407 : : _ssl.enum_certificates
5408 : : store_name: str
5409 : :
5410 : : Retrieve certificates from Windows' cert store.
5411 : :
5412 : : store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5413 : : more cert storages, too. The function returns a list of (bytes,
5414 : : encoding_type, trust) tuples. The encoding_type flag can be interpreted
5415 : : with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5416 : : a set of OIDs or the boolean True.
5417 : : [clinic start generated code]*/
5418 : :
5419 : : static PyObject *
5420 : : _ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5421 : : /*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
5422 : : {
5423 : : HCERTSTORE hCollectionStore = NULL;
5424 : : PCCERT_CONTEXT pCertCtx = NULL;
5425 : : PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
5426 : : PyObject *result = NULL;
5427 : :
5428 : : result = PySet_New(NULL);
5429 : : if (result == NULL) {
5430 : : return NULL;
5431 : : }
5432 : : hCollectionStore = ssl_collect_certificates(store_name);
5433 : : if (hCollectionStore == NULL) {
5434 : : Py_DECREF(result);
5435 : : return PyErr_SetFromWindowsErr(GetLastError());
5436 : : }
5437 : :
5438 : : while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
5439 : : cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5440 : : pCertCtx->cbCertEncoded);
5441 : : if (!cert) {
5442 : : Py_CLEAR(result);
5443 : : break;
5444 : : }
5445 : : if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5446 : : Py_CLEAR(result);
5447 : : break;
5448 : : }
5449 : : keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5450 : : if (keyusage == Py_True) {
5451 : : Py_DECREF(keyusage);
5452 : : keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
5453 : : }
5454 : : if (keyusage == NULL) {
5455 : : Py_CLEAR(result);
5456 : : break;
5457 : : }
5458 : : if ((tup = PyTuple_New(3)) == NULL) {
5459 : : Py_CLEAR(result);
5460 : : break;
5461 : : }
5462 : : PyTuple_SET_ITEM(tup, 0, cert);
5463 : : cert = NULL;
5464 : : PyTuple_SET_ITEM(tup, 1, enc);
5465 : : enc = NULL;
5466 : : PyTuple_SET_ITEM(tup, 2, keyusage);
5467 : : keyusage = NULL;
5468 : : if (PySet_Add(result, tup) == -1) {
5469 : : Py_CLEAR(result);
5470 : : Py_CLEAR(tup);
5471 : : break;
5472 : : }
5473 : : Py_CLEAR(tup);
5474 : : }
5475 : : if (pCertCtx) {
5476 : : /* loop ended with an error, need to clean up context manually */
5477 : : CertFreeCertificateContext(pCertCtx);
5478 : : }
5479 : :
5480 : : /* In error cases cert, enc and tup may not be NULL */
5481 : : Py_XDECREF(cert);
5482 : : Py_XDECREF(enc);
5483 : : Py_XDECREF(keyusage);
5484 : : Py_XDECREF(tup);
5485 : :
5486 : : /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5487 : : associated with the store, in this case our collection store and the
5488 : : associated system stores. */
5489 : : if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
5490 : : /* This error case might shadow another exception.*/
5491 : : Py_XDECREF(result);
5492 : : return PyErr_SetFromWindowsErr(GetLastError());
5493 : : }
5494 : :
5495 : : /* convert set to list */
5496 : : if (result == NULL) {
5497 : : return NULL;
5498 : : } else {
5499 : : PyObject *lst = PySequence_List(result);
5500 : : Py_DECREF(result);
5501 : : return lst;
5502 : : }
5503 : : }
5504 : :
5505 : : /*[clinic input]
5506 : : _ssl.enum_crls
5507 : : store_name: str
5508 : :
5509 : : Retrieve CRLs from Windows' cert store.
5510 : :
5511 : : store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5512 : : more cert storages, too. The function returns a list of (bytes,
5513 : : encoding_type) tuples. The encoding_type flag can be interpreted with
5514 : : X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5515 : : [clinic start generated code]*/
5516 : :
5517 : : static PyObject *
5518 : : _ssl_enum_crls_impl(PyObject *module, const char *store_name)
5519 : : /*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
5520 : : {
5521 : : HCERTSTORE hCollectionStore = NULL;
5522 : : PCCRL_CONTEXT pCrlCtx = NULL;
5523 : : PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5524 : : PyObject *result = NULL;
5525 : :
5526 : : result = PySet_New(NULL);
5527 : : if (result == NULL) {
5528 : : return NULL;
5529 : : }
5530 : : hCollectionStore = ssl_collect_certificates(store_name);
5531 : : if (hCollectionStore == NULL) {
5532 : : Py_DECREF(result);
5533 : : return PyErr_SetFromWindowsErr(GetLastError());
5534 : : }
5535 : :
5536 : : while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
5537 : : crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5538 : : pCrlCtx->cbCrlEncoded);
5539 : : if (!crl) {
5540 : : Py_CLEAR(result);
5541 : : break;
5542 : : }
5543 : : if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5544 : : Py_CLEAR(result);
5545 : : break;
5546 : : }
5547 : : if ((tup = PyTuple_New(2)) == NULL) {
5548 : : Py_CLEAR(result);
5549 : : break;
5550 : : }
5551 : : PyTuple_SET_ITEM(tup, 0, crl);
5552 : : crl = NULL;
5553 : : PyTuple_SET_ITEM(tup, 1, enc);
5554 : : enc = NULL;
5555 : :
5556 : : if (PySet_Add(result, tup) == -1) {
5557 : : Py_CLEAR(result);
5558 : : Py_CLEAR(tup);
5559 : : break;
5560 : : }
5561 : : Py_CLEAR(tup);
5562 : : }
5563 : : if (pCrlCtx) {
5564 : : /* loop ended with an error, need to clean up context manually */
5565 : : CertFreeCRLContext(pCrlCtx);
5566 : : }
5567 : :
5568 : : /* In error cases cert, enc and tup may not be NULL */
5569 : : Py_XDECREF(crl);
5570 : : Py_XDECREF(enc);
5571 : : Py_XDECREF(tup);
5572 : :
5573 : : /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5574 : : associated with the store, in this case our collection store and the
5575 : : associated system stores. */
5576 : : if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
5577 : : /* This error case might shadow another exception.*/
5578 : : Py_XDECREF(result);
5579 : : return PyErr_SetFromWindowsErr(GetLastError());
5580 : : }
5581 : : /* convert set to list */
5582 : : if (result == NULL) {
5583 : : return NULL;
5584 : : } else {
5585 : : PyObject *lst = PySequence_List(result);
5586 : : Py_DECREF(result);
5587 : : return lst;
5588 : : }
5589 : : }
5590 : :
5591 : : #endif /* _MSC_VER */
5592 : :
5593 : : /* List of functions exported by this module. */
5594 : : static PyMethodDef PySSL_methods[] = {
5595 : : _SSL__TEST_DECODE_CERT_METHODDEF
5596 : : _SSL_RAND_ADD_METHODDEF
5597 : : _SSL_RAND_BYTES_METHODDEF
5598 : : _SSL_RAND_STATUS_METHODDEF
5599 : : _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5600 : : _SSL_ENUM_CERTIFICATES_METHODDEF
5601 : : _SSL_ENUM_CRLS_METHODDEF
5602 : : _SSL_TXT2OBJ_METHODDEF
5603 : : _SSL_NID2OBJ_METHODDEF
5604 : : {NULL, NULL} /* Sentinel */
5605 : : };
5606 : :
5607 : :
5608 : : PyDoc_STRVAR(module_doc,
5609 : : "Implementation module for SSL socket operations. See the socket module\n\
5610 : : for documentation.");
5611 : :
5612 : : static int
5613 : 2 : sslmodule_init_exceptions(PyObject *module)
5614 : : {
5615 : 2 : _sslmodulestate *state = get_ssl_state(module);
5616 : 2 : PyObject *bases = NULL;
5617 : :
5618 : : #define add_exception(exc, name, doc, base) \
5619 : : do { \
5620 : : (exc) = PyErr_NewExceptionWithDoc("ssl." name, (doc), (base), NULL); \
5621 : : if ((state) == NULL) goto error; \
5622 : : if (PyModule_AddObjectRef(module, name, exc) < 0) goto error; \
5623 : : } while(0)
5624 : :
5625 : 2 : state->PySSLErrorObject = PyType_FromSpecWithBases(
5626 : : &sslerror_type_spec, PyExc_OSError);
5627 [ - + ]: 2 : if (state->PySSLErrorObject == NULL) {
5628 : 0 : goto error;
5629 : : }
5630 [ - + ]: 2 : if (PyModule_AddObjectRef(module, "SSLError", state->PySSLErrorObject) < 0) {
5631 : 0 : goto error;
5632 : : }
5633 : :
5634 : : /* ssl.CertificateError used to be a subclass of ValueError */
5635 : 2 : bases = PyTuple_Pack(2, state->PySSLErrorObject, PyExc_ValueError);
5636 [ - + ]: 2 : if (bases == NULL) {
5637 : 0 : goto error;
5638 : : }
5639 [ - + - + ]: 2 : add_exception(
5640 : : state->PySSLCertVerificationErrorObject,
5641 : : "SSLCertVerificationError",
5642 : : SSLCertVerificationError_doc,
5643 : : bases
5644 : : );
5645 [ + - ]: 2 : Py_CLEAR(bases);
5646 : :
5647 [ - + - + ]: 2 : add_exception(
5648 : : state->PySSLZeroReturnErrorObject,
5649 : : "SSLZeroReturnError",
5650 : : SSLZeroReturnError_doc,
5651 : : state->PySSLErrorObject
5652 : : );
5653 : :
5654 [ - + - + ]: 2 : add_exception(
5655 : : state->PySSLWantWriteErrorObject,
5656 : : "SSLWantWriteError",
5657 : : SSLWantWriteError_doc,
5658 : : state->PySSLErrorObject
5659 : : );
5660 : :
5661 [ - + - + ]: 2 : add_exception(
5662 : : state->PySSLWantReadErrorObject,
5663 : : "SSLWantReadError",
5664 : : SSLWantReadError_doc,
5665 : : state->PySSLErrorObject
5666 : : );
5667 : :
5668 [ - + - + ]: 2 : add_exception(
5669 : : state->PySSLSyscallErrorObject,
5670 : : "SSLSyscallError",
5671 : : SSLSyscallError_doc,
5672 : : state->PySSLErrorObject
5673 : : );
5674 : :
5675 [ - + - + ]: 2 : add_exception(
5676 : : state->PySSLEOFErrorObject,
5677 : : "SSLEOFError",
5678 : : SSLEOFError_doc,
5679 : : state->PySSLErrorObject
5680 : : );
5681 : : #undef add_exception
5682 : :
5683 : 2 : return 0;
5684 : 0 : error:
5685 : 0 : Py_XDECREF(bases);
5686 : 0 : return -1;
5687 : : }
5688 : :
5689 : : static int
5690 : 2 : sslmodule_init_socketapi(PyObject *module)
5691 : : {
5692 : 2 : _sslmodulestate *state = get_ssl_state(module);
5693 : 2 : PySocketModule_APIObject *sockmod = PySocketModule_ImportModuleAndAPI();
5694 : :
5695 [ + - - + ]: 2 : if ((sockmod == NULL) || (sockmod->Sock_Type == NULL)) {
5696 : 0 : return -1;
5697 : : }
5698 : 2 : state->Sock_Type = (PyTypeObject*)Py_NewRef(sockmod->Sock_Type);
5699 : 2 : return 0;
5700 : : }
5701 : :
5702 : : static int
5703 : 2 : sslmodule_init_constants(PyObject *m)
5704 : : {
5705 : :
5706 : 2 : PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5707 : : PY_SSL_DEFAULT_CIPHER_STRING);
5708 : :
5709 : 2 : PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5710 : : PY_SSL_ERROR_ZERO_RETURN);
5711 : 2 : PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5712 : : PY_SSL_ERROR_WANT_READ);
5713 : 2 : PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5714 : : PY_SSL_ERROR_WANT_WRITE);
5715 : 2 : PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5716 : : PY_SSL_ERROR_WANT_X509_LOOKUP);
5717 : 2 : PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5718 : : PY_SSL_ERROR_SYSCALL);
5719 : 2 : PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5720 : : PY_SSL_ERROR_SSL);
5721 : 2 : PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5722 : : PY_SSL_ERROR_WANT_CONNECT);
5723 : : /* non ssl.h errorcodes */
5724 : 2 : PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5725 : : PY_SSL_ERROR_EOF);
5726 : 2 : PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5727 : : PY_SSL_ERROR_INVALID_ERROR_CODE);
5728 : : /* cert requirements */
5729 : 2 : PyModule_AddIntConstant(m, "CERT_NONE",
5730 : : PY_SSL_CERT_NONE);
5731 : 2 : PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5732 : : PY_SSL_CERT_OPTIONAL);
5733 : 2 : PyModule_AddIntConstant(m, "CERT_REQUIRED",
5734 : : PY_SSL_CERT_REQUIRED);
5735 : : /* CRL verification for verification_flags */
5736 : 2 : PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5737 : : 0);
5738 : 2 : PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5739 : : X509_V_FLAG_CRL_CHECK);
5740 : 2 : PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5741 : : X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5742 : 2 : PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5743 : : X509_V_FLAG_X509_STRICT);
5744 : 2 : PyModule_AddIntConstant(m, "VERIFY_ALLOW_PROXY_CERTS",
5745 : : X509_V_FLAG_ALLOW_PROXY_CERTS);
5746 : 2 : PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5747 : : X509_V_FLAG_TRUSTED_FIRST);
5748 : :
5749 : : #ifdef X509_V_FLAG_PARTIAL_CHAIN
5750 : 2 : PyModule_AddIntConstant(m, "VERIFY_X509_PARTIAL_CHAIN",
5751 : : X509_V_FLAG_PARTIAL_CHAIN);
5752 : : #endif
5753 : :
5754 : : /* Alert Descriptions from ssl.h */
5755 : : /* note RESERVED constants no longer intended for use have been removed */
5756 : : /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5757 : :
5758 : : #define ADD_AD_CONSTANT(s) \
5759 : : PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5760 : : SSL_AD_##s)
5761 : :
5762 : 2 : ADD_AD_CONSTANT(CLOSE_NOTIFY);
5763 : 2 : ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5764 : 2 : ADD_AD_CONSTANT(BAD_RECORD_MAC);
5765 : 2 : ADD_AD_CONSTANT(RECORD_OVERFLOW);
5766 : 2 : ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5767 : 2 : ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5768 : 2 : ADD_AD_CONSTANT(BAD_CERTIFICATE);
5769 : 2 : ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5770 : 2 : ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5771 : 2 : ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5772 : 2 : ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5773 : 2 : ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5774 : 2 : ADD_AD_CONSTANT(UNKNOWN_CA);
5775 : 2 : ADD_AD_CONSTANT(ACCESS_DENIED);
5776 : 2 : ADD_AD_CONSTANT(DECODE_ERROR);
5777 : 2 : ADD_AD_CONSTANT(DECRYPT_ERROR);
5778 : 2 : ADD_AD_CONSTANT(PROTOCOL_VERSION);
5779 : 2 : ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5780 : 2 : ADD_AD_CONSTANT(INTERNAL_ERROR);
5781 : 2 : ADD_AD_CONSTANT(USER_CANCELLED);
5782 : 2 : ADD_AD_CONSTANT(NO_RENEGOTIATION);
5783 : : /* Not all constants are in old OpenSSL versions */
5784 : : #ifdef SSL_AD_UNSUPPORTED_EXTENSION
5785 : 2 : ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5786 : : #endif
5787 : : #ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5788 : 2 : ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5789 : : #endif
5790 : : #ifdef SSL_AD_UNRECOGNIZED_NAME
5791 : 2 : ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5792 : : #endif
5793 : : #ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5794 : 2 : ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5795 : : #endif
5796 : : #ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5797 : 2 : ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5798 : : #endif
5799 : : #ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5800 : 2 : ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5801 : : #endif
5802 : :
5803 : : #undef ADD_AD_CONSTANT
5804 : :
5805 : : /* protocol versions */
5806 : : #ifndef OPENSSL_NO_SSL3
5807 : : PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5808 : : PY_SSL_VERSION_SSL3);
5809 : : #endif
5810 : 2 : PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
5811 : : PY_SSL_VERSION_TLS);
5812 : 2 : PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5813 : : PY_SSL_VERSION_TLS);
5814 : 2 : PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5815 : : PY_SSL_VERSION_TLS_CLIENT);
5816 : 2 : PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5817 : : PY_SSL_VERSION_TLS_SERVER);
5818 : 2 : PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5819 : : PY_SSL_VERSION_TLS1);
5820 : 2 : PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5821 : : PY_SSL_VERSION_TLS1_1);
5822 : 2 : PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5823 : : PY_SSL_VERSION_TLS1_2);
5824 : :
5825 : : /* protocol options */
5826 : 2 : PyModule_AddIntConstant(m, "OP_ALL",
5827 : : SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
5828 : 2 : PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5829 : 2 : PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5830 : 2 : PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
5831 : 2 : PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5832 : 2 : PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5833 : : #ifdef SSL_OP_NO_TLSv1_3
5834 : 2 : PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5835 : : #else
5836 : : PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5837 : : #endif
5838 : 2 : PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5839 : : SSL_OP_CIPHER_SERVER_PREFERENCE);
5840 : 2 : PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
5841 : 2 : PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
5842 : 2 : PyModule_AddIntConstant(m, "OP_LEGACY_SERVER_CONNECT",
5843 : : SSL_OP_LEGACY_SERVER_CONNECT);
5844 : : #ifdef SSL_OP_SINGLE_ECDH_USE
5845 : 2 : PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
5846 : : #endif
5847 : : #ifdef SSL_OP_NO_COMPRESSION
5848 : 2 : PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5849 : : SSL_OP_NO_COMPRESSION);
5850 : : #endif
5851 : : #ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5852 : 2 : PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5853 : : SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5854 : : #endif
5855 : : #ifdef SSL_OP_NO_RENEGOTIATION
5856 : 2 : PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5857 : : SSL_OP_NO_RENEGOTIATION);
5858 : : #endif
5859 : : #ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
5860 : : PyModule_AddIntConstant(m, "OP_IGNORE_UNEXPECTED_EOF",
5861 : : SSL_OP_IGNORE_UNEXPECTED_EOF);
5862 : : #endif
5863 : : #ifdef SSL_OP_ENABLE_KTLS
5864 : : PyModule_AddIntConstant(m, "OP_ENABLE_KTLS", SSL_OP_ENABLE_KTLS);
5865 : : #endif
5866 : :
5867 : : #ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5868 : 2 : PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5869 : : X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5870 : : #endif
5871 : : #ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5872 : 2 : PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5873 : : X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5874 : : #endif
5875 : : #ifdef X509_CHECK_FLAG_NO_WILDCARDS
5876 : 2 : PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5877 : : X509_CHECK_FLAG_NO_WILDCARDS);
5878 : : #endif
5879 : : #ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5880 : 2 : PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5881 : : X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5882 : : #endif
5883 : : #ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5884 : 2 : PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5885 : : X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5886 : : #endif
5887 : : #ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5888 : 2 : PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5889 : : X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5890 : : #endif
5891 : :
5892 : : /* file types */
5893 : 2 : PyModule_AddIntConstant(m, "ENCODING_PEM", PY_SSL_ENCODING_PEM);
5894 : 2 : PyModule_AddIntConstant(m, "ENCODING_DER", PY_SSL_ENCODING_DER);
5895 : :
5896 : : /* protocol versions */
5897 : 2 : PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5898 : : PY_PROTO_MINIMUM_SUPPORTED);
5899 : 2 : PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5900 : : PY_PROTO_MAXIMUM_SUPPORTED);
5901 : 2 : PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5902 : 2 : PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5903 : 2 : PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5904 : 2 : PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5905 : 2 : PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
5906 : :
5907 : : #define addbool(m, key, value) \
5908 : : do { \
5909 : : PyObject *bool_obj = (value) ? Py_True : Py_False; \
5910 : : PyModule_AddObject((m), (key), Py_NewRef(bool_obj)); \
5911 : : } while (0)
5912 : :
5913 : 2 : addbool(m, "HAS_SNI", 1);
5914 : 2 : addbool(m, "HAS_TLS_UNIQUE", 1);
5915 : 2 : addbool(m, "HAS_ECDH", 1);
5916 : 2 : addbool(m, "HAS_NPN", 0);
5917 : 2 : addbool(m, "HAS_ALPN", 1);
5918 : :
5919 : 2 : addbool(m, "HAS_SSLv2", 0);
5920 : :
5921 : : #if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5922 : : addbool(m, "HAS_SSLv3", 1);
5923 : : #else
5924 : 2 : addbool(m, "HAS_SSLv3", 0);
5925 : : #endif
5926 : :
5927 : : #if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5928 : 2 : addbool(m, "HAS_TLSv1", 1);
5929 : : #else
5930 : : addbool(m, "HAS_TLSv1", 0);
5931 : : #endif
5932 : :
5933 : : #if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5934 : 2 : addbool(m, "HAS_TLSv1_1", 1);
5935 : : #else
5936 : : addbool(m, "HAS_TLSv1_1", 0);
5937 : : #endif
5938 : :
5939 : : #if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5940 : 2 : addbool(m, "HAS_TLSv1_2", 1);
5941 : : #else
5942 : : addbool(m, "HAS_TLSv1_2", 0);
5943 : : #endif
5944 : :
5945 : : #if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
5946 : 2 : addbool(m, "HAS_TLSv1_3", 1);
5947 : : #else
5948 : : addbool(m, "HAS_TLSv1_3", 0);
5949 : : #endif
5950 : :
5951 : 2 : return 0;
5952 : : }
5953 : :
5954 : : static int
5955 : 2 : sslmodule_init_errorcodes(PyObject *module)
5956 : : {
5957 : 2 : _sslmodulestate *state = get_ssl_state(module);
5958 : :
5959 : : struct py_ssl_error_code *errcode;
5960 : : struct py_ssl_library_code *libcode;
5961 : :
5962 : : /* Mappings for error codes */
5963 : 2 : state->err_codes_to_names = PyDict_New();
5964 [ - + ]: 2 : if (state->err_codes_to_names == NULL)
5965 : 0 : return -1;
5966 : 2 : state->err_names_to_codes = PyDict_New();
5967 [ - + ]: 2 : if (state->err_names_to_codes == NULL)
5968 : 0 : return -1;
5969 : 2 : state->lib_codes_to_names = PyDict_New();
5970 [ - + ]: 2 : if (state->lib_codes_to_names == NULL)
5971 : 0 : return -1;
5972 : :
5973 : 2 : errcode = error_codes;
5974 [ + + ]: 2554 : while (errcode->mnemonic != NULL) {
5975 : : PyObject *mnemo, *key;
5976 : 2552 : mnemo = PyUnicode_FromString(errcode->mnemonic);
5977 : 2552 : key = Py_BuildValue("ii", errcode->library, errcode->reason);
5978 [ + - - + ]: 2552 : if (mnemo == NULL || key == NULL)
5979 : 0 : return -1;
5980 [ - + ]: 2552 : if (PyDict_SetItem(state->err_codes_to_names, key, mnemo))
5981 : 0 : return -1;
5982 [ - + ]: 2552 : if (PyDict_SetItem(state->err_names_to_codes, mnemo, key))
5983 : 0 : return -1;
5984 : 2552 : Py_DECREF(key);
5985 : 2552 : Py_DECREF(mnemo);
5986 : 2552 : errcode++;
5987 : : }
5988 : :
5989 : 2 : libcode = library_codes;
5990 [ + + ]: 78 : while (libcode->library != NULL) {
5991 : : PyObject *mnemo, *key;
5992 : 76 : key = PyLong_FromLong(libcode->code);
5993 : 76 : mnemo = PyUnicode_FromString(libcode->library);
5994 [ + - - + ]: 76 : if (key == NULL || mnemo == NULL)
5995 : 0 : return -1;
5996 [ - + ]: 76 : if (PyDict_SetItem(state->lib_codes_to_names, key, mnemo))
5997 : 0 : return -1;
5998 : 76 : Py_DECREF(key);
5999 : 76 : Py_DECREF(mnemo);
6000 : 76 : libcode++;
6001 : : }
6002 : :
6003 [ - + ]: 2 : if (PyModule_AddObjectRef(module, "err_codes_to_names", state->err_codes_to_names))
6004 : 0 : return -1;
6005 [ - + ]: 2 : if (PyModule_AddObjectRef(module, "err_names_to_codes", state->err_names_to_codes))
6006 : 0 : return -1;
6007 [ - + ]: 2 : if (PyModule_AddObjectRef(module, "lib_codes_to_names", state->lib_codes_to_names))
6008 : 0 : return -1;
6009 : :
6010 : 2 : return 0;
6011 : : }
6012 : :
6013 : : static void
6014 : 4 : parse_openssl_version(unsigned long libver,
6015 : : unsigned int *major, unsigned int *minor,
6016 : : unsigned int *fix, unsigned int *patch,
6017 : : unsigned int *status)
6018 : : {
6019 : 4 : *status = libver & 0xF;
6020 : 4 : libver >>= 4;
6021 : 4 : *patch = libver & 0xFF;
6022 : 4 : libver >>= 8;
6023 : 4 : *fix = libver & 0xFF;
6024 : 4 : libver >>= 8;
6025 : 4 : *minor = libver & 0xFF;
6026 : 4 : libver >>= 8;
6027 : 4 : *major = libver & 0xFF;
6028 : 4 : }
6029 : :
6030 : : static int
6031 : 2 : sslmodule_init_versioninfo(PyObject *m)
6032 : : {
6033 : : PyObject *r;
6034 : : unsigned long libver;
6035 : : unsigned int major, minor, fix, patch, status;
6036 : :
6037 : : /* OpenSSL version */
6038 : : /* SSLeay() gives us the version of the library linked against,
6039 : : which could be different from the headers version.
6040 : : */
6041 : 2 : libver = OpenSSL_version_num();
6042 : 2 : r = PyLong_FromUnsignedLong(libver);
6043 [ + - - + ]: 2 : if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6044 : 0 : return -1;
6045 : :
6046 : 2 : parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6047 : 2 : r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6048 [ + - - + ]: 2 : if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6049 : 0 : return -1;
6050 : :
6051 : 2 : r = PyUnicode_FromString(OpenSSL_version(OPENSSL_VERSION));
6052 [ + - - + ]: 2 : if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6053 : 0 : return -1;
6054 : :
6055 : 2 : libver = OPENSSL_VERSION_NUMBER;
6056 : 2 : parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6057 : 2 : r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6058 [ + - - + ]: 2 : if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6059 : 0 : return -1;
6060 : :
6061 : 2 : return 0;
6062 : : }
6063 : :
6064 : : static int
6065 : 2 : sslmodule_init_types(PyObject *module)
6066 : : {
6067 : 2 : _sslmodulestate *state = get_ssl_state(module);
6068 : :
6069 : 2 : state->PySSLContext_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6070 : : module, &PySSLContext_spec, NULL
6071 : : );
6072 [ - + ]: 2 : if (state->PySSLContext_Type == NULL)
6073 : 0 : return -1;
6074 : :
6075 : 2 : state->PySSLSocket_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6076 : : module, &PySSLSocket_spec, NULL
6077 : : );
6078 [ - + ]: 2 : if (state->PySSLSocket_Type == NULL)
6079 : 0 : return -1;
6080 : :
6081 : 2 : state->PySSLMemoryBIO_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6082 : : module, &PySSLMemoryBIO_spec, NULL
6083 : : );
6084 [ - + ]: 2 : if (state->PySSLMemoryBIO_Type == NULL)
6085 : 0 : return -1;
6086 : :
6087 : 2 : state->PySSLSession_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6088 : : module, &PySSLSession_spec, NULL
6089 : : );
6090 [ - + ]: 2 : if (state->PySSLSession_Type == NULL)
6091 : 0 : return -1;
6092 : :
6093 : 2 : state->PySSLCertificate_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
6094 : : module, &PySSLCertificate_spec, NULL
6095 : : );
6096 [ - + ]: 2 : if (state->PySSLCertificate_Type == NULL)
6097 : 0 : return -1;
6098 : :
6099 [ - + ]: 2 : if (PyModule_AddType(module, state->PySSLContext_Type))
6100 : 0 : return -1;
6101 [ - + ]: 2 : if (PyModule_AddType(module, state->PySSLSocket_Type))
6102 : 0 : return -1;
6103 [ - + ]: 2 : if (PyModule_AddType(module, state->PySSLMemoryBIO_Type))
6104 : 0 : return -1;
6105 [ - + ]: 2 : if (PyModule_AddType(module, state->PySSLSession_Type))
6106 : 0 : return -1;
6107 [ - + ]: 2 : if (PyModule_AddType(module, state->PySSLCertificate_Type))
6108 : 0 : return -1;
6109 : 2 : return 0;
6110 : : }
6111 : :
6112 : : static int
6113 : 2 : sslmodule_init_strings(PyObject *module)
6114 : : {
6115 : 2 : _sslmodulestate *state = get_ssl_state(module);
6116 : 2 : state->str_library = PyUnicode_InternFromString("library");
6117 [ - + ]: 2 : if (state->str_library == NULL) {
6118 : 0 : return -1;
6119 : : }
6120 : 2 : state->str_reason = PyUnicode_InternFromString("reason");
6121 [ - + ]: 2 : if (state->str_reason == NULL) {
6122 : 0 : return -1;
6123 : : }
6124 : 2 : state->str_verify_message = PyUnicode_InternFromString("verify_message");
6125 [ - + ]: 2 : if (state->str_verify_message == NULL) {
6126 : 0 : return -1;
6127 : : }
6128 : 2 : state->str_verify_code = PyUnicode_InternFromString("verify_code");
6129 [ - + ]: 2 : if (state->str_verify_code == NULL) {
6130 : 0 : return -1;
6131 : : }
6132 : 2 : return 0;
6133 : : }
6134 : :
6135 : : static PyModuleDef_Slot sslmodule_slots[] = {
6136 : : {Py_mod_exec, sslmodule_init_types},
6137 : : {Py_mod_exec, sslmodule_init_exceptions},
6138 : : {Py_mod_exec, sslmodule_init_socketapi},
6139 : : {Py_mod_exec, sslmodule_init_errorcodes},
6140 : : {Py_mod_exec, sslmodule_init_constants},
6141 : : {Py_mod_exec, sslmodule_init_versioninfo},
6142 : : {Py_mod_exec, sslmodule_init_strings},
6143 : : {0, NULL}
6144 : : };
6145 : :
6146 : : static int
6147 : 18 : sslmodule_traverse(PyObject *m, visitproc visit, void *arg)
6148 : : {
6149 : 18 : _sslmodulestate *state = get_ssl_state(m);
6150 : :
6151 [ + - - + ]: 18 : Py_VISIT(state->PySSLContext_Type);
6152 [ + - - + ]: 18 : Py_VISIT(state->PySSLSocket_Type);
6153 [ + - - + ]: 18 : Py_VISIT(state->PySSLMemoryBIO_Type);
6154 [ + - - + ]: 18 : Py_VISIT(state->PySSLSession_Type);
6155 [ + - - + ]: 18 : Py_VISIT(state->PySSLCertificate_Type);
6156 [ + - - + ]: 18 : Py_VISIT(state->PySSLErrorObject);
6157 [ + - - + ]: 18 : Py_VISIT(state->PySSLCertVerificationErrorObject);
6158 [ + - - + ]: 18 : Py_VISIT(state->PySSLZeroReturnErrorObject);
6159 [ + - - + ]: 18 : Py_VISIT(state->PySSLWantReadErrorObject);
6160 [ + - - + ]: 18 : Py_VISIT(state->PySSLWantWriteErrorObject);
6161 [ + - - + ]: 18 : Py_VISIT(state->PySSLSyscallErrorObject);
6162 [ + - - + ]: 18 : Py_VISIT(state->PySSLEOFErrorObject);
6163 [ + - - + ]: 18 : Py_VISIT(state->err_codes_to_names);
6164 [ + - - + ]: 18 : Py_VISIT(state->err_names_to_codes);
6165 [ + - - + ]: 18 : Py_VISIT(state->lib_codes_to_names);
6166 [ + - - + ]: 18 : Py_VISIT(state->Sock_Type);
6167 : :
6168 : 18 : return 0;
6169 : : }
6170 : :
6171 : : static int
6172 : 4 : sslmodule_clear(PyObject *m)
6173 : : {
6174 : 4 : _sslmodulestate *state = get_ssl_state(m);
6175 : :
6176 [ + + ]: 4 : Py_CLEAR(state->PySSLContext_Type);
6177 [ + + ]: 4 : Py_CLEAR(state->PySSLSocket_Type);
6178 [ + + ]: 4 : Py_CLEAR(state->PySSLMemoryBIO_Type);
6179 [ + + ]: 4 : Py_CLEAR(state->PySSLSession_Type);
6180 [ + + ]: 4 : Py_CLEAR(state->PySSLCertificate_Type);
6181 [ + + ]: 4 : Py_CLEAR(state->PySSLErrorObject);
6182 [ + + ]: 4 : Py_CLEAR(state->PySSLCertVerificationErrorObject);
6183 [ + + ]: 4 : Py_CLEAR(state->PySSLZeroReturnErrorObject);
6184 [ + + ]: 4 : Py_CLEAR(state->PySSLWantReadErrorObject);
6185 [ + + ]: 4 : Py_CLEAR(state->PySSLWantWriteErrorObject);
6186 [ + + ]: 4 : Py_CLEAR(state->PySSLSyscallErrorObject);
6187 [ + + ]: 4 : Py_CLEAR(state->PySSLEOFErrorObject);
6188 [ + + ]: 4 : Py_CLEAR(state->err_codes_to_names);
6189 [ + + ]: 4 : Py_CLEAR(state->err_names_to_codes);
6190 [ + + ]: 4 : Py_CLEAR(state->lib_codes_to_names);
6191 [ + + ]: 4 : Py_CLEAR(state->Sock_Type);
6192 [ + + ]: 4 : Py_CLEAR(state->str_library);
6193 [ + + ]: 4 : Py_CLEAR(state->str_reason);
6194 [ + + ]: 4 : Py_CLEAR(state->str_verify_code);
6195 [ + + ]: 4 : Py_CLEAR(state->str_verify_message);
6196 : 4 : return 0;
6197 : : }
6198 : :
6199 : : static void
6200 : 2 : sslmodule_free(void *m)
6201 : : {
6202 : 2 : sslmodule_clear((PyObject *)m);
6203 : 2 : }
6204 : :
6205 : : static struct PyModuleDef _sslmodule_def = {
6206 : : PyModuleDef_HEAD_INIT,
6207 : : .m_name = "_ssl",
6208 : : .m_doc = module_doc,
6209 : : .m_size = sizeof(_sslmodulestate),
6210 : : .m_methods = PySSL_methods,
6211 : : .m_slots = sslmodule_slots,
6212 : : .m_traverse = sslmodule_traverse,
6213 : : .m_clear = sslmodule_clear,
6214 : : .m_free = sslmodule_free
6215 : : };
6216 : :
6217 : : PyMODINIT_FUNC
6218 : 2 : PyInit__ssl(void)
6219 : : {
6220 : 2 : return PyModuleDef_Init(&_sslmodule_def);
6221 : : }
|