ยปCore Development>Code coverage>Modules/_ssl.c

Python code coverage for Modules/_ssl.c

#countcontent
1n/a/* SSL socket module
2n/a
3n/a SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
4n/a Re-worked a bit by Bill Janssen to add server-side support and
5n/a certificate decoding. Chris Stawarz contributed some non-blocking
6n/a patches.
7n/a
8n/a This module is imported by ssl.py. It should *not* be used
9n/a directly.
10n/a
11n/a XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
12n/a
13n/a XXX integrate several "shutdown modes" as suggested in
14n/a http://bugs.python.org/issue8108#msg102867 ?
15n/a*/
16n/a
17n/a#define PY_SSIZE_T_CLEAN
18n/a
19n/a#include "Python.h"
20n/a
21n/a#ifdef WITH_THREAD
22n/a#include "pythread.h"
23n/a
24n/a
25n/a#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
26n/a do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
27n/a#define PySSL_END_ALLOW_THREADS_S(save) \
28n/a do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
29n/a#define PySSL_BEGIN_ALLOW_THREADS { \
30n/a PyThreadState *_save = NULL; \
31n/a PySSL_BEGIN_ALLOW_THREADS_S(_save);
32n/a#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
33n/a#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
34n/a#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
35n/a
36n/a#else /* no WITH_THREAD */
37n/a
38n/a#define PySSL_BEGIN_ALLOW_THREADS_S(save)
39n/a#define PySSL_END_ALLOW_THREADS_S(save)
40n/a#define PySSL_BEGIN_ALLOW_THREADS
41n/a#define PySSL_BLOCK_THREADS
42n/a#define PySSL_UNBLOCK_THREADS
43n/a#define PySSL_END_ALLOW_THREADS
44n/a
45n/a#endif
46n/a
47n/a/* Include symbols from _socket module */
48n/a#include "socketmodule.h"
49n/a
50n/astatic PySocketModule_APIObject PySocketModule;
51n/a
52n/a#if defined(HAVE_POLL_H)
53n/a#include <poll.h>
54n/a#elif defined(HAVE_SYS_POLL_H)
55n/a#include <sys/poll.h>
56n/a#endif
57n/a
58n/a/* Don't warn about deprecated functions */
59n/a#ifdef __GNUC__
60n/a#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
61n/a#endif
62n/a#ifdef __clang__
63n/a#pragma clang diagnostic ignored "-Wdeprecated-declarations"
64n/a#endif
65n/a
66n/a/* Include OpenSSL header files */
67n/a#include "openssl/rsa.h"
68n/a#include "openssl/crypto.h"
69n/a#include "openssl/x509.h"
70n/a#include "openssl/x509v3.h"
71n/a#include "openssl/pem.h"
72n/a#include "openssl/ssl.h"
73n/a#include "openssl/err.h"
74n/a#include "openssl/rand.h"
75n/a#include "openssl/bio.h"
76n/a
77n/a/* SSL error object */
78n/astatic PyObject *PySSLErrorObject;
79n/astatic PyObject *PySSLZeroReturnErrorObject;
80n/astatic PyObject *PySSLWantReadErrorObject;
81n/astatic PyObject *PySSLWantWriteErrorObject;
82n/astatic PyObject *PySSLSyscallErrorObject;
83n/astatic PyObject *PySSLEOFErrorObject;
84n/a
85n/a/* Error mappings */
86n/astatic PyObject *err_codes_to_names;
87n/astatic PyObject *err_names_to_codes;
88n/astatic PyObject *lib_codes_to_names;
89n/a
90n/astruct py_ssl_error_code {
91n/a const char *mnemonic;
92n/a int library, reason;
93n/a};
94n/astruct py_ssl_library_code {
95n/a const char *library;
96n/a int code;
97n/a};
98n/a
99n/a/* Include generated data (error codes) */
100n/a#include "_ssl_data.h"
101n/a
102n/a#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
103n/a# define OPENSSL_VERSION_1_1 1
104n/a#endif
105n/a
106n/a/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
107n/a http://www.openssl.org/news/changelog.html
108n/a */
109n/a#if OPENSSL_VERSION_NUMBER >= 0x10001000L
110n/a# define HAVE_TLSv1_2 1
111n/a#else
112n/a# define HAVE_TLSv1_2 0
113n/a#endif
114n/a
115n/a/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
116n/a * This includes the SSL_set_SSL_CTX() function.
117n/a */
118n/a#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
119n/a# define HAVE_SNI 1
120n/a#else
121n/a# define HAVE_SNI 0
122n/a#endif
123n/a
124n/a#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
125n/a# define HAVE_ALPN
126n/a#endif
127n/a
128n/a#ifndef INVALID_SOCKET /* MS defines this */
129n/a#define INVALID_SOCKET (-1)
130n/a#endif
131n/a
132n/a#ifdef OPENSSL_VERSION_1_1
133n/a/* OpenSSL 1.1.0+ */
134n/a#ifndef OPENSSL_NO_SSL2
135n/a#define OPENSSL_NO_SSL2
136n/a#endif
137n/a#else /* OpenSSL < 1.1.0 */
138n/a#if defined(WITH_THREAD)
139n/a#define HAVE_OPENSSL_CRYPTO_LOCK
140n/a#endif
141n/a
142n/a#define TLS_method SSLv23_method
143n/a#define TLS_client_method SSLv23_client_method
144n/a#define TLS_server_method SSLv23_server_method
145n/a
146n/astatic int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
147n/a{
148n/a return ne->set;
149n/a}
150n/a
151n/a#ifndef OPENSSL_NO_COMP
152n/a/* LCOV_EXCL_START */
153n/astatic int COMP_get_type(const COMP_METHOD *meth)
154n/a{
155n/a return meth->type;
156n/a}
157n/a/* LCOV_EXCL_STOP */
158n/a#endif
159n/a
160n/astatic pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
161n/a{
162n/a return ctx->default_passwd_callback;
163n/a}
164n/a
165n/astatic void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
166n/a{
167n/a return ctx->default_passwd_callback_userdata;
168n/a}
169n/a
170n/astatic int X509_OBJECT_get_type(X509_OBJECT *x)
171n/a{
172n/a return x->type;
173n/a}
174n/a
175n/astatic X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
176n/a{
177n/a return x->data.x509;
178n/a}
179n/a
180n/astatic int BIO_up_ref(BIO *b)
181n/a{
182n/a CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
183n/a return 1;
184n/a}
185n/a
186n/astatic STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
187n/a return store->objs;
188n/a}
189n/a
190n/astatic X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
191n/a{
192n/a return store->param;
193n/a}
194n/a
195n/astatic int
196n/aSSL_SESSION_has_ticket(const SSL_SESSION *s)
197n/a{
198n/a return (s->tlsext_ticklen > 0) ? 1 : 0;
199n/a}
200n/a
201n/astatic unsigned long
202n/aSSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
203n/a{
204n/a return s->tlsext_tick_lifetime_hint;
205n/a}
206n/a
207n/a#endif /* OpenSSL < 1.1.0 or LibreSSL */
208n/a
209n/a
210n/aenum py_ssl_error {
211n/a /* these mirror ssl.h */
212n/a PY_SSL_ERROR_NONE,
213n/a PY_SSL_ERROR_SSL,
214n/a PY_SSL_ERROR_WANT_READ,
215n/a PY_SSL_ERROR_WANT_WRITE,
216n/a PY_SSL_ERROR_WANT_X509_LOOKUP,
217n/a PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
218n/a PY_SSL_ERROR_ZERO_RETURN,
219n/a PY_SSL_ERROR_WANT_CONNECT,
220n/a /* start of non ssl.h errorcodes */
221n/a PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
222n/a PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
223n/a PY_SSL_ERROR_INVALID_ERROR_CODE
224n/a};
225n/a
226n/aenum py_ssl_server_or_client {
227n/a PY_SSL_CLIENT,
228n/a PY_SSL_SERVER
229n/a};
230n/a
231n/aenum py_ssl_cert_requirements {
232n/a PY_SSL_CERT_NONE,
233n/a PY_SSL_CERT_OPTIONAL,
234n/a PY_SSL_CERT_REQUIRED
235n/a};
236n/a
237n/aenum py_ssl_version {
238n/a PY_SSL_VERSION_SSL2,
239n/a PY_SSL_VERSION_SSL3=1,
240n/a PY_SSL_VERSION_TLS, /* SSLv23 */
241n/a#if HAVE_TLSv1_2
242n/a PY_SSL_VERSION_TLS1,
243n/a PY_SSL_VERSION_TLS1_1,
244n/a PY_SSL_VERSION_TLS1_2,
245n/a#else
246n/a PY_SSL_VERSION_TLS1,
247n/a#endif
248n/a PY_SSL_VERSION_TLS_CLIENT=0x10,
249n/a PY_SSL_VERSION_TLS_SERVER,
250n/a};
251n/a
252n/a#ifdef WITH_THREAD
253n/a
254n/a/* serves as a flag to see whether we've initialized the SSL thread support. */
255n/a/* 0 means no, greater than 0 means yes */
256n/a
257n/astatic unsigned int _ssl_locks_count = 0;
258n/a
259n/a#endif /* def WITH_THREAD */
260n/a
261n/a/* SSL socket object */
262n/a
263n/a#define X509_NAME_MAXLEN 256
264n/a
265n/a/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
266n/a * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
267n/a * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
268n/a#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
269n/a# define HAVE_SSL_CTX_CLEAR_OPTIONS
270n/a#else
271n/a# undef HAVE_SSL_CTX_CLEAR_OPTIONS
272n/a#endif
273n/a
274n/a/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
275n/a * older SSL, but let's be safe */
276n/a#define PySSL_CB_MAXLEN 128
277n/a
278n/a
279n/atypedef struct {
280n/a PyObject_HEAD
281n/a SSL_CTX *ctx;
282n/a#ifdef OPENSSL_NPN_NEGOTIATED
283n/a unsigned char *npn_protocols;
284n/a int npn_protocols_len;
285n/a#endif
286n/a#ifdef HAVE_ALPN
287n/a unsigned char *alpn_protocols;
288n/a int alpn_protocols_len;
289n/a#endif
290n/a#ifndef OPENSSL_NO_TLSEXT
291n/a PyObject *set_hostname;
292n/a#endif
293n/a int check_hostname;
294n/a} PySSLContext;
295n/a
296n/atypedef struct {
297n/a PyObject_HEAD
298n/a PyObject *Socket; /* weakref to socket on which we're layered */
299n/a SSL *ssl;
300n/a PySSLContext *ctx; /* weakref to SSL context */
301n/a X509 *peer_cert;
302n/a char shutdown_seen_zero;
303n/a char handshake_done;
304n/a enum py_ssl_server_or_client socket_type;
305n/a PyObject *owner; /* Python level "owner" passed to servername callback */
306n/a PyObject *server_hostname;
307n/a} PySSLSocket;
308n/a
309n/atypedef struct {
310n/a PyObject_HEAD
311n/a BIO *bio;
312n/a int eof_written;
313n/a} PySSLMemoryBIO;
314n/a
315n/atypedef struct {
316n/a PyObject_HEAD
317n/a SSL_SESSION *session;
318n/a PySSLContext *ctx;
319n/a} PySSLSession;
320n/a
321n/astatic PyTypeObject PySSLContext_Type;
322n/astatic PyTypeObject PySSLSocket_Type;
323n/astatic PyTypeObject PySSLMemoryBIO_Type;
324n/astatic PyTypeObject PySSLSession_Type;
325n/a
326n/a/*[clinic input]
327n/amodule _ssl
328n/aclass _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
329n/aclass _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
330n/aclass _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
331n/aclass _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
332n/a[clinic start generated code]*/
333n/a/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
334n/a
335n/a#include "clinic/_ssl.c.h"
336n/a
337n/astatic int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
338n/a
339n/a
340n/a#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
341n/a#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
342n/a#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
343n/a#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
344n/a
345n/atypedef enum {
346n/a SOCKET_IS_NONBLOCKING,
347n/a SOCKET_IS_BLOCKING,
348n/a SOCKET_HAS_TIMED_OUT,
349n/a SOCKET_HAS_BEEN_CLOSED,
350n/a SOCKET_TOO_LARGE_FOR_SELECT,
351n/a SOCKET_OPERATION_OK
352n/a} timeout_state;
353n/a
354n/a/* Wrap error strings with filename and line # */
355n/a#define ERRSTR1(x,y,z) (x ":" y ": " z)
356n/a#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
357n/a
358n/a/* Get the socket from a PySSLSocket, if it has one */
359n/a#define GET_SOCKET(obj) ((obj)->Socket ? \
360n/a (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
361n/a
362n/a/* If sock is NULL, use a timeout of 0 second */
363n/a#define GET_SOCKET_TIMEOUT(sock) \
364n/a ((sock != NULL) ? (sock)->sock_timeout : 0)
365n/a
366n/a/*
367n/a * SSL errors.
368n/a */
369n/a
370n/aPyDoc_STRVAR(SSLError_doc,
371n/a"An error occurred in the SSL implementation.");
372n/a
373n/aPyDoc_STRVAR(SSLZeroReturnError_doc,
374n/a"SSL/TLS session closed cleanly.");
375n/a
376n/aPyDoc_STRVAR(SSLWantReadError_doc,
377n/a"Non-blocking SSL socket needs to read more data\n"
378n/a"before the requested operation can be completed.");
379n/a
380n/aPyDoc_STRVAR(SSLWantWriteError_doc,
381n/a"Non-blocking SSL socket needs to write more data\n"
382n/a"before the requested operation can be completed.");
383n/a
384n/aPyDoc_STRVAR(SSLSyscallError_doc,
385n/a"System error when attempting SSL operation.");
386n/a
387n/aPyDoc_STRVAR(SSLEOFError_doc,
388n/a"SSL/TLS connection terminated abruptly.");
389n/a
390n/astatic PyObject *
391n/aSSLError_str(PyOSErrorObject *self)
392n/a{
393n/a if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
394n/a Py_INCREF(self->strerror);
395n/a return self->strerror;
396n/a }
397n/a else
398n/a return PyObject_Str(self->args);
399n/a}
400n/a
401n/astatic PyType_Slot sslerror_type_slots[] = {
402n/a {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
403n/a {Py_tp_doc, SSLError_doc},
404n/a {Py_tp_str, SSLError_str},
405n/a {0, 0},
406n/a};
407n/a
408n/astatic PyType_Spec sslerror_type_spec = {
409n/a "ssl.SSLError",
410n/a sizeof(PyOSErrorObject),
411n/a 0,
412n/a Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
413n/a sslerror_type_slots
414n/a};
415n/a
416n/astatic void
417n/afill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
418n/a int lineno, unsigned long errcode)
419n/a{
420n/a PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
421n/a PyObject *init_value, *msg, *key;
422n/a _Py_IDENTIFIER(reason);
423n/a _Py_IDENTIFIER(library);
424n/a
425n/a if (errcode != 0) {
426n/a int lib, reason;
427n/a
428n/a lib = ERR_GET_LIB(errcode);
429n/a reason = ERR_GET_REASON(errcode);
430n/a key = Py_BuildValue("ii", lib, reason);
431n/a if (key == NULL)
432n/a goto fail;
433n/a reason_obj = PyDict_GetItem(err_codes_to_names, key);
434n/a Py_DECREF(key);
435n/a if (reason_obj == NULL) {
436n/a /* XXX if reason < 100, it might reflect a library number (!!) */
437n/a PyErr_Clear();
438n/a }
439n/a key = PyLong_FromLong(lib);
440n/a if (key == NULL)
441n/a goto fail;
442n/a lib_obj = PyDict_GetItem(lib_codes_to_names, key);
443n/a Py_DECREF(key);
444n/a if (lib_obj == NULL) {
445n/a PyErr_Clear();
446n/a }
447n/a if (errstr == NULL)
448n/a errstr = ERR_reason_error_string(errcode);
449n/a }
450n/a if (errstr == NULL)
451n/a errstr = "unknown error";
452n/a
453n/a if (reason_obj && lib_obj)
454n/a msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
455n/a lib_obj, reason_obj, errstr, lineno);
456n/a else if (lib_obj)
457n/a msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
458n/a lib_obj, errstr, lineno);
459n/a else
460n/a msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
461n/a if (msg == NULL)
462n/a goto fail;
463n/a
464n/a init_value = Py_BuildValue("iN", ssl_errno, msg);
465n/a if (init_value == NULL)
466n/a goto fail;
467n/a
468n/a err_value = PyObject_CallObject(type, init_value);
469n/a Py_DECREF(init_value);
470n/a if (err_value == NULL)
471n/a goto fail;
472n/a
473n/a if (reason_obj == NULL)
474n/a reason_obj = Py_None;
475n/a if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
476n/a goto fail;
477n/a if (lib_obj == NULL)
478n/a lib_obj = Py_None;
479n/a if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
480n/a goto fail;
481n/a PyErr_SetObject(type, err_value);
482n/afail:
483n/a Py_XDECREF(err_value);
484n/a}
485n/a
486n/astatic PyObject *
487n/aPySSL_SetError(PySSLSocket *obj, int ret, const char *filename, int lineno)
488n/a{
489n/a PyObject *type = PySSLErrorObject;
490n/a char *errstr = NULL;
491n/a int err;
492n/a enum py_ssl_error p = PY_SSL_ERROR_NONE;
493n/a unsigned long e = 0;
494n/a
495n/a assert(ret <= 0);
496n/a e = ERR_peek_last_error();
497n/a
498n/a if (obj->ssl != NULL) {
499n/a err = SSL_get_error(obj->ssl, ret);
500n/a
501n/a switch (err) {
502n/a case SSL_ERROR_ZERO_RETURN:
503n/a errstr = "TLS/SSL connection has been closed (EOF)";
504n/a type = PySSLZeroReturnErrorObject;
505n/a p = PY_SSL_ERROR_ZERO_RETURN;
506n/a break;
507n/a case SSL_ERROR_WANT_READ:
508n/a errstr = "The operation did not complete (read)";
509n/a type = PySSLWantReadErrorObject;
510n/a p = PY_SSL_ERROR_WANT_READ;
511n/a break;
512n/a case SSL_ERROR_WANT_WRITE:
513n/a p = PY_SSL_ERROR_WANT_WRITE;
514n/a type = PySSLWantWriteErrorObject;
515n/a errstr = "The operation did not complete (write)";
516n/a break;
517n/a case SSL_ERROR_WANT_X509_LOOKUP:
518n/a p = PY_SSL_ERROR_WANT_X509_LOOKUP;
519n/a errstr = "The operation did not complete (X509 lookup)";
520n/a break;
521n/a case SSL_ERROR_WANT_CONNECT:
522n/a p = PY_SSL_ERROR_WANT_CONNECT;
523n/a errstr = "The operation did not complete (connect)";
524n/a break;
525n/a case SSL_ERROR_SYSCALL:
526n/a {
527n/a if (e == 0) {
528n/a PySocketSockObject *s = GET_SOCKET(obj);
529n/a if (ret == 0 || (((PyObject *)s) == Py_None)) {
530n/a p = PY_SSL_ERROR_EOF;
531n/a type = PySSLEOFErrorObject;
532n/a errstr = "EOF occurred in violation of protocol";
533n/a } else if (s && ret == -1) {
534n/a /* underlying BIO reported an I/O error */
535n/a Py_INCREF(s);
536n/a ERR_clear_error();
537n/a s->errorhandler();
538n/a Py_DECREF(s);
539n/a return NULL;
540n/a } else { /* possible? */
541n/a p = PY_SSL_ERROR_SYSCALL;
542n/a type = PySSLSyscallErrorObject;
543n/a errstr = "Some I/O error occurred";
544n/a }
545n/a } else {
546n/a p = PY_SSL_ERROR_SYSCALL;
547n/a }
548n/a break;
549n/a }
550n/a case SSL_ERROR_SSL:
551n/a {
552n/a p = PY_SSL_ERROR_SSL;
553n/a if (e == 0)
554n/a /* possible? */
555n/a errstr = "A failure in the SSL library occurred";
556n/a break;
557n/a }
558n/a default:
559n/a p = PY_SSL_ERROR_INVALID_ERROR_CODE;
560n/a errstr = "Invalid error code";
561n/a }
562n/a }
563n/a fill_and_set_sslerror(type, p, errstr, lineno, e);
564n/a ERR_clear_error();
565n/a return NULL;
566n/a}
567n/a
568n/astatic PyObject *
569n/a_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
570n/a
571n/a if (errstr == NULL)
572n/a errcode = ERR_peek_last_error();
573n/a else
574n/a errcode = 0;
575n/a fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
576n/a ERR_clear_error();
577n/a return NULL;
578n/a}
579n/a
580n/a/*
581n/a * SSL objects
582n/a */
583n/a
584n/astatic PySSLSocket *
585n/anewPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
586n/a enum py_ssl_server_or_client socket_type,
587n/a char *server_hostname,
588n/a PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
589n/a{
590n/a PySSLSocket *self;
591n/a SSL_CTX *ctx = sslctx->ctx;
592n/a long mode;
593n/a
594n/a self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
595n/a if (self == NULL)
596n/a return NULL;
597n/a
598n/a self->peer_cert = NULL;
599n/a self->ssl = NULL;
600n/a self->Socket = NULL;
601n/a self->ctx = sslctx;
602n/a self->shutdown_seen_zero = 0;
603n/a self->handshake_done = 0;
604n/a self->owner = NULL;
605n/a self->server_hostname = NULL;
606n/a if (server_hostname != NULL) {
607n/a PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
608n/a "idna", "strict");
609n/a if (hostname == NULL) {
610n/a Py_DECREF(self);
611n/a return NULL;
612n/a }
613n/a self->server_hostname = hostname;
614n/a }
615n/a
616n/a Py_INCREF(sslctx);
617n/a
618n/a /* Make sure the SSL error state is initialized */
619n/a (void) ERR_get_state();
620n/a ERR_clear_error();
621n/a
622n/a PySSL_BEGIN_ALLOW_THREADS
623n/a self->ssl = SSL_new(ctx);
624n/a PySSL_END_ALLOW_THREADS
625n/a SSL_set_app_data(self->ssl, self);
626n/a if (sock) {
627n/a SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
628n/a } else {
629n/a /* BIOs are reference counted and SSL_set_bio borrows our reference.
630n/a * To prevent a double free in memory_bio_dealloc() we need to take an
631n/a * extra reference here. */
632n/a BIO_up_ref(inbio->bio);
633n/a BIO_up_ref(outbio->bio);
634n/a SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
635n/a }
636n/a mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
637n/a#ifdef SSL_MODE_AUTO_RETRY
638n/a mode |= SSL_MODE_AUTO_RETRY;
639n/a#endif
640n/a SSL_set_mode(self->ssl, mode);
641n/a
642n/a#if HAVE_SNI
643n/a if (server_hostname != NULL)
644n/a SSL_set_tlsext_host_name(self->ssl, server_hostname);
645n/a#endif
646n/a
647n/a /* If the socket is in non-blocking mode or timeout mode, set the BIO
648n/a * to non-blocking mode (blocking is the default)
649n/a */
650n/a if (sock && sock->sock_timeout >= 0) {
651n/a BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
652n/a BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
653n/a }
654n/a
655n/a PySSL_BEGIN_ALLOW_THREADS
656n/a if (socket_type == PY_SSL_CLIENT)
657n/a SSL_set_connect_state(self->ssl);
658n/a else
659n/a SSL_set_accept_state(self->ssl);
660n/a PySSL_END_ALLOW_THREADS
661n/a
662n/a self->socket_type = socket_type;
663n/a if (sock != NULL) {
664n/a self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
665n/a if (self->Socket == NULL) {
666n/a Py_DECREF(self);
667n/a return NULL;
668n/a }
669n/a }
670n/a return self;
671n/a}
672n/a
673n/a/* SSL object methods */
674n/a
675n/a/*[clinic input]
676n/a_ssl._SSLSocket.do_handshake
677n/a[clinic start generated code]*/
678n/a
679n/astatic PyObject *
680n/a_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
681n/a/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
682n/a{
683n/a int ret;
684n/a int err;
685n/a int sockstate, nonblocking;
686n/a PySocketSockObject *sock = GET_SOCKET(self);
687n/a _PyTime_t timeout, deadline = 0;
688n/a int has_timeout;
689n/a
690n/a if (sock) {
691n/a if (((PyObject*)sock) == Py_None) {
692n/a _setSSLError("Underlying socket connection gone",
693n/a PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
694n/a return NULL;
695n/a }
696n/a Py_INCREF(sock);
697n/a
698n/a /* just in case the blocking state of the socket has been changed */
699n/a nonblocking = (sock->sock_timeout >= 0);
700n/a BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
701n/a BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
702n/a }
703n/a
704n/a timeout = GET_SOCKET_TIMEOUT(sock);
705n/a has_timeout = (timeout > 0);
706n/a if (has_timeout)
707n/a deadline = _PyTime_GetMonotonicClock() + timeout;
708n/a
709n/a /* Actually negotiate SSL connection */
710n/a /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
711n/a do {
712n/a PySSL_BEGIN_ALLOW_THREADS
713n/a ret = SSL_do_handshake(self->ssl);
714n/a err = SSL_get_error(self->ssl, ret);
715n/a PySSL_END_ALLOW_THREADS
716n/a
717n/a if (PyErr_CheckSignals())
718n/a goto error;
719n/a
720n/a if (has_timeout)
721n/a timeout = deadline - _PyTime_GetMonotonicClock();
722n/a
723n/a if (err == SSL_ERROR_WANT_READ) {
724n/a sockstate = PySSL_select(sock, 0, timeout);
725n/a } else if (err == SSL_ERROR_WANT_WRITE) {
726n/a sockstate = PySSL_select(sock, 1, timeout);
727n/a } else {
728n/a sockstate = SOCKET_OPERATION_OK;
729n/a }
730n/a
731n/a if (sockstate == SOCKET_HAS_TIMED_OUT) {
732n/a PyErr_SetString(PySocketModule.timeout_error,
733n/a ERRSTR("The handshake operation timed out"));
734n/a goto error;
735n/a } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
736n/a PyErr_SetString(PySSLErrorObject,
737n/a ERRSTR("Underlying socket has been closed."));
738n/a goto error;
739n/a } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
740n/a PyErr_SetString(PySSLErrorObject,
741n/a ERRSTR("Underlying socket too large for select()."));
742n/a goto error;
743n/a } else if (sockstate == SOCKET_IS_NONBLOCKING) {
744n/a break;
745n/a }
746n/a } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
747n/a Py_XDECREF(sock);
748n/a if (ret < 1)
749n/a return PySSL_SetError(self, ret, __FILE__, __LINE__);
750n/a
751n/a if (self->peer_cert)
752n/a X509_free (self->peer_cert);
753n/a PySSL_BEGIN_ALLOW_THREADS
754n/a self->peer_cert = SSL_get_peer_certificate(self->ssl);
755n/a PySSL_END_ALLOW_THREADS
756n/a self->handshake_done = 1;
757n/a
758n/a Py_RETURN_NONE;
759n/a
760n/aerror:
761n/a Py_XDECREF(sock);
762n/a return NULL;
763n/a}
764n/a
765n/astatic PyObject *
766n/a_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
767n/a
768n/a char namebuf[X509_NAME_MAXLEN];
769n/a int buflen;
770n/a PyObject *name_obj;
771n/a PyObject *value_obj;
772n/a PyObject *attr;
773n/a unsigned char *valuebuf = NULL;
774n/a
775n/a buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
776n/a if (buflen < 0) {
777n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
778n/a goto fail;
779n/a }
780n/a name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
781n/a if (name_obj == NULL)
782n/a goto fail;
783n/a
784n/a buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
785n/a if (buflen < 0) {
786n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
787n/a Py_DECREF(name_obj);
788n/a goto fail;
789n/a }
790n/a value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
791n/a buflen, "strict");
792n/a OPENSSL_free(valuebuf);
793n/a if (value_obj == NULL) {
794n/a Py_DECREF(name_obj);
795n/a goto fail;
796n/a }
797n/a attr = PyTuple_New(2);
798n/a if (attr == NULL) {
799n/a Py_DECREF(name_obj);
800n/a Py_DECREF(value_obj);
801n/a goto fail;
802n/a }
803n/a PyTuple_SET_ITEM(attr, 0, name_obj);
804n/a PyTuple_SET_ITEM(attr, 1, value_obj);
805n/a return attr;
806n/a
807n/a fail:
808n/a return NULL;
809n/a}
810n/a
811n/astatic PyObject *
812n/a_create_tuple_for_X509_NAME (X509_NAME *xname)
813n/a{
814n/a PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
815n/a PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
816n/a PyObject *rdnt;
817n/a PyObject *attr = NULL; /* tuple to hold an attribute */
818n/a int entry_count = X509_NAME_entry_count(xname);
819n/a X509_NAME_ENTRY *entry;
820n/a ASN1_OBJECT *name;
821n/a ASN1_STRING *value;
822n/a int index_counter;
823n/a int rdn_level = -1;
824n/a int retcode;
825n/a
826n/a dn = PyList_New(0);
827n/a if (dn == NULL)
828n/a return NULL;
829n/a /* now create another tuple to hold the top-level RDN */
830n/a rdn = PyList_New(0);
831n/a if (rdn == NULL)
832n/a goto fail0;
833n/a
834n/a for (index_counter = 0;
835n/a index_counter < entry_count;
836n/a index_counter++)
837n/a {
838n/a entry = X509_NAME_get_entry(xname, index_counter);
839n/a
840n/a /* check to see if we've gotten to a new RDN */
841n/a if (rdn_level >= 0) {
842n/a if (rdn_level != X509_NAME_ENTRY_set(entry)) {
843n/a /* yes, new RDN */
844n/a /* add old RDN to DN */
845n/a rdnt = PyList_AsTuple(rdn);
846n/a Py_DECREF(rdn);
847n/a if (rdnt == NULL)
848n/a goto fail0;
849n/a retcode = PyList_Append(dn, rdnt);
850n/a Py_DECREF(rdnt);
851n/a if (retcode < 0)
852n/a goto fail0;
853n/a /* create new RDN */
854n/a rdn = PyList_New(0);
855n/a if (rdn == NULL)
856n/a goto fail0;
857n/a }
858n/a }
859n/a rdn_level = X509_NAME_ENTRY_set(entry);
860n/a
861n/a /* now add this attribute to the current RDN */
862n/a name = X509_NAME_ENTRY_get_object(entry);
863n/a value = X509_NAME_ENTRY_get_data(entry);
864n/a attr = _create_tuple_for_attribute(name, value);
865n/a /*
866n/a fprintf(stderr, "RDN level %d, attribute %s: %s\n",
867n/a entry->set,
868n/a PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
869n/a PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
870n/a */
871n/a if (attr == NULL)
872n/a goto fail1;
873n/a retcode = PyList_Append(rdn, attr);
874n/a Py_DECREF(attr);
875n/a if (retcode < 0)
876n/a goto fail1;
877n/a }
878n/a /* now, there's typically a dangling RDN */
879n/a if (rdn != NULL) {
880n/a if (PyList_GET_SIZE(rdn) > 0) {
881n/a rdnt = PyList_AsTuple(rdn);
882n/a Py_DECREF(rdn);
883n/a if (rdnt == NULL)
884n/a goto fail0;
885n/a retcode = PyList_Append(dn, rdnt);
886n/a Py_DECREF(rdnt);
887n/a if (retcode < 0)
888n/a goto fail0;
889n/a }
890n/a else {
891n/a Py_DECREF(rdn);
892n/a }
893n/a }
894n/a
895n/a /* convert list to tuple */
896n/a rdnt = PyList_AsTuple(dn);
897n/a Py_DECREF(dn);
898n/a if (rdnt == NULL)
899n/a return NULL;
900n/a return rdnt;
901n/a
902n/a fail1:
903n/a Py_XDECREF(rdn);
904n/a
905n/a fail0:
906n/a Py_XDECREF(dn);
907n/a return NULL;
908n/a}
909n/a
910n/astatic PyObject *
911n/a_get_peer_alt_names (X509 *certificate) {
912n/a
913n/a /* this code follows the procedure outlined in
914n/a OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
915n/a function to extract the STACK_OF(GENERAL_NAME),
916n/a then iterates through the stack to add the
917n/a names. */
918n/a
919n/a int i, j;
920n/a PyObject *peer_alt_names = Py_None;
921n/a PyObject *v = NULL, *t;
922n/a X509_EXTENSION *ext = NULL;
923n/a GENERAL_NAMES *names = NULL;
924n/a GENERAL_NAME *name;
925n/a const X509V3_EXT_METHOD *method;
926n/a BIO *biobuf = NULL;
927n/a char buf[2048];
928n/a char *vptr;
929n/a int len;
930n/a const unsigned char *p;
931n/a
932n/a if (certificate == NULL)
933n/a return peer_alt_names;
934n/a
935n/a /* get a memory buffer */
936n/a biobuf = BIO_new(BIO_s_mem());
937n/a
938n/a i = -1;
939n/a while ((i = X509_get_ext_by_NID(
940n/a certificate, NID_subject_alt_name, i)) >= 0) {
941n/a
942n/a if (peer_alt_names == Py_None) {
943n/a peer_alt_names = PyList_New(0);
944n/a if (peer_alt_names == NULL)
945n/a goto fail;
946n/a }
947n/a
948n/a /* now decode the altName */
949n/a ext = X509_get_ext(certificate, i);
950n/a if(!(method = X509V3_EXT_get(ext))) {
951n/a PyErr_SetString
952n/a (PySSLErrorObject,
953n/a ERRSTR("No method for internalizing subjectAltName!"));
954n/a goto fail;
955n/a }
956n/a
957n/a p = X509_EXTENSION_get_data(ext)->data;
958n/a if (method->it)
959n/a names = (GENERAL_NAMES*)
960n/a (ASN1_item_d2i(NULL,
961n/a &p,
962n/a X509_EXTENSION_get_data(ext)->length,
963n/a ASN1_ITEM_ptr(method->it)));
964n/a else
965n/a names = (GENERAL_NAMES*)
966n/a (method->d2i(NULL,
967n/a &p,
968n/a X509_EXTENSION_get_data(ext)->length));
969n/a
970n/a for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
971n/a /* get a rendering of each name in the set of names */
972n/a int gntype;
973n/a ASN1_STRING *as = NULL;
974n/a
975n/a name = sk_GENERAL_NAME_value(names, j);
976n/a gntype = name->type;
977n/a switch (gntype) {
978n/a case GEN_DIRNAME:
979n/a /* we special-case DirName as a tuple of
980n/a tuples of attributes */
981n/a
982n/a t = PyTuple_New(2);
983n/a if (t == NULL) {
984n/a goto fail;
985n/a }
986n/a
987n/a v = PyUnicode_FromString("DirName");
988n/a if (v == NULL) {
989n/a Py_DECREF(t);
990n/a goto fail;
991n/a }
992n/a PyTuple_SET_ITEM(t, 0, v);
993n/a
994n/a v = _create_tuple_for_X509_NAME (name->d.dirn);
995n/a if (v == NULL) {
996n/a Py_DECREF(t);
997n/a goto fail;
998n/a }
999n/a PyTuple_SET_ITEM(t, 1, v);
1000n/a break;
1001n/a
1002n/a case GEN_EMAIL:
1003n/a case GEN_DNS:
1004n/a case GEN_URI:
1005n/a /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1006n/a correctly, CVE-2013-4238 */
1007n/a t = PyTuple_New(2);
1008n/a if (t == NULL)
1009n/a goto fail;
1010n/a switch (gntype) {
1011n/a case GEN_EMAIL:
1012n/a v = PyUnicode_FromString("email");
1013n/a as = name->d.rfc822Name;
1014n/a break;
1015n/a case GEN_DNS:
1016n/a v = PyUnicode_FromString("DNS");
1017n/a as = name->d.dNSName;
1018n/a break;
1019n/a case GEN_URI:
1020n/a v = PyUnicode_FromString("URI");
1021n/a as = name->d.uniformResourceIdentifier;
1022n/a break;
1023n/a }
1024n/a if (v == NULL) {
1025n/a Py_DECREF(t);
1026n/a goto fail;
1027n/a }
1028n/a PyTuple_SET_ITEM(t, 0, v);
1029n/a v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1030n/a ASN1_STRING_length(as));
1031n/a if (v == NULL) {
1032n/a Py_DECREF(t);
1033n/a goto fail;
1034n/a }
1035n/a PyTuple_SET_ITEM(t, 1, v);
1036n/a break;
1037n/a
1038n/a case GEN_RID:
1039n/a t = PyTuple_New(2);
1040n/a if (t == NULL)
1041n/a goto fail;
1042n/a
1043n/a v = PyUnicode_FromString("Registered ID");
1044n/a if (v == NULL) {
1045n/a Py_DECREF(t);
1046n/a goto fail;
1047n/a }
1048n/a PyTuple_SET_ITEM(t, 0, v);
1049n/a
1050n/a len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1051n/a if (len < 0) {
1052n/a Py_DECREF(t);
1053n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
1054n/a goto fail;
1055n/a } else if (len >= (int)sizeof(buf)) {
1056n/a v = PyUnicode_FromString("<INVALID>");
1057n/a } else {
1058n/a v = PyUnicode_FromStringAndSize(buf, len);
1059n/a }
1060n/a if (v == NULL) {
1061n/a Py_DECREF(t);
1062n/a goto fail;
1063n/a }
1064n/a PyTuple_SET_ITEM(t, 1, v);
1065n/a break;
1066n/a
1067n/a default:
1068n/a /* for everything else, we use the OpenSSL print form */
1069n/a switch (gntype) {
1070n/a /* check for new general name type */
1071n/a case GEN_OTHERNAME:
1072n/a case GEN_X400:
1073n/a case GEN_EDIPARTY:
1074n/a case GEN_IPADD:
1075n/a case GEN_RID:
1076n/a break;
1077n/a default:
1078n/a if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1079n/a "Unknown general name type %d",
1080n/a gntype) == -1) {
1081n/a goto fail;
1082n/a }
1083n/a break;
1084n/a }
1085n/a (void) BIO_reset(biobuf);
1086n/a GENERAL_NAME_print(biobuf, name);
1087n/a len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1088n/a if (len < 0) {
1089n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
1090n/a goto fail;
1091n/a }
1092n/a vptr = strchr(buf, ':');
1093n/a if (vptr == NULL) {
1094n/a PyErr_Format(PyExc_ValueError,
1095n/a "Invalid value %.200s",
1096n/a buf);
1097n/a goto fail;
1098n/a }
1099n/a t = PyTuple_New(2);
1100n/a if (t == NULL)
1101n/a goto fail;
1102n/a v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1103n/a if (v == NULL) {
1104n/a Py_DECREF(t);
1105n/a goto fail;
1106n/a }
1107n/a PyTuple_SET_ITEM(t, 0, v);
1108n/a v = PyUnicode_FromStringAndSize((vptr + 1),
1109n/a (len - (vptr - buf + 1)));
1110n/a if (v == NULL) {
1111n/a Py_DECREF(t);
1112n/a goto fail;
1113n/a }
1114n/a PyTuple_SET_ITEM(t, 1, v);
1115n/a break;
1116n/a }
1117n/a
1118n/a /* and add that rendering to the list */
1119n/a
1120n/a if (PyList_Append(peer_alt_names, t) < 0) {
1121n/a Py_DECREF(t);
1122n/a goto fail;
1123n/a }
1124n/a Py_DECREF(t);
1125n/a }
1126n/a sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
1127n/a }
1128n/a BIO_free(biobuf);
1129n/a if (peer_alt_names != Py_None) {
1130n/a v = PyList_AsTuple(peer_alt_names);
1131n/a Py_DECREF(peer_alt_names);
1132n/a return v;
1133n/a } else {
1134n/a return peer_alt_names;
1135n/a }
1136n/a
1137n/a
1138n/a fail:
1139n/a if (biobuf != NULL)
1140n/a BIO_free(biobuf);
1141n/a
1142n/a if (peer_alt_names != Py_None) {
1143n/a Py_XDECREF(peer_alt_names);
1144n/a }
1145n/a
1146n/a return NULL;
1147n/a}
1148n/a
1149n/astatic PyObject *
1150n/a_get_aia_uri(X509 *certificate, int nid) {
1151n/a PyObject *lst = NULL, *ostr = NULL;
1152n/a int i, result;
1153n/a AUTHORITY_INFO_ACCESS *info;
1154n/a
1155n/a info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
1156n/a if (info == NULL)
1157n/a return Py_None;
1158n/a if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1159n/a AUTHORITY_INFO_ACCESS_free(info);
1160n/a return Py_None;
1161n/a }
1162n/a
1163n/a if ((lst = PyList_New(0)) == NULL) {
1164n/a goto fail;
1165n/a }
1166n/a
1167n/a for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1168n/a ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1169n/a ASN1_IA5STRING *uri;
1170n/a
1171n/a if ((OBJ_obj2nid(ad->method) != nid) ||
1172n/a (ad->location->type != GEN_URI)) {
1173n/a continue;
1174n/a }
1175n/a uri = ad->location->d.uniformResourceIdentifier;
1176n/a ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1177n/a uri->length);
1178n/a if (ostr == NULL) {
1179n/a goto fail;
1180n/a }
1181n/a result = PyList_Append(lst, ostr);
1182n/a Py_DECREF(ostr);
1183n/a if (result < 0) {
1184n/a goto fail;
1185n/a }
1186n/a }
1187n/a AUTHORITY_INFO_ACCESS_free(info);
1188n/a
1189n/a /* convert to tuple or None */
1190n/a if (PyList_Size(lst) == 0) {
1191n/a Py_DECREF(lst);
1192n/a return Py_None;
1193n/a } else {
1194n/a PyObject *tup;
1195n/a tup = PyList_AsTuple(lst);
1196n/a Py_DECREF(lst);
1197n/a return tup;
1198n/a }
1199n/a
1200n/a fail:
1201n/a AUTHORITY_INFO_ACCESS_free(info);
1202n/a Py_XDECREF(lst);
1203n/a return NULL;
1204n/a}
1205n/a
1206n/astatic PyObject *
1207n/a_get_crl_dp(X509 *certificate) {
1208n/a STACK_OF(DIST_POINT) *dps;
1209n/a int i, j;
1210n/a PyObject *lst, *res = NULL;
1211n/a
1212n/a#if OPENSSL_VERSION_NUMBER >= 0x10001000L
1213n/a /* Calls x509v3_cache_extensions and sets up crldp */
1214n/a X509_check_ca(certificate);
1215n/a#endif
1216n/a dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
1217n/a
1218n/a if (dps == NULL)
1219n/a return Py_None;
1220n/a
1221n/a lst = PyList_New(0);
1222n/a if (lst == NULL)
1223n/a goto done;
1224n/a
1225n/a for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1226n/a DIST_POINT *dp;
1227n/a STACK_OF(GENERAL_NAME) *gns;
1228n/a
1229n/a dp = sk_DIST_POINT_value(dps, i);
1230n/a gns = dp->distpoint->name.fullname;
1231n/a
1232n/a for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1233n/a GENERAL_NAME *gn;
1234n/a ASN1_IA5STRING *uri;
1235n/a PyObject *ouri;
1236n/a int err;
1237n/a
1238n/a gn = sk_GENERAL_NAME_value(gns, j);
1239n/a if (gn->type != GEN_URI) {
1240n/a continue;
1241n/a }
1242n/a uri = gn->d.uniformResourceIdentifier;
1243n/a ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1244n/a uri->length);
1245n/a if (ouri == NULL)
1246n/a goto done;
1247n/a
1248n/a err = PyList_Append(lst, ouri);
1249n/a Py_DECREF(ouri);
1250n/a if (err < 0)
1251n/a goto done;
1252n/a }
1253n/a }
1254n/a
1255n/a /* Convert to tuple. */
1256n/a res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1257n/a
1258n/a done:
1259n/a Py_XDECREF(lst);
1260n/a#if OPENSSL_VERSION_NUMBER < 0x10001000L
1261n/a sk_DIST_POINT_free(dps);
1262n/a#endif
1263n/a return res;
1264n/a}
1265n/a
1266n/astatic PyObject *
1267n/a_decode_certificate(X509 *certificate) {
1268n/a
1269n/a PyObject *retval = NULL;
1270n/a BIO *biobuf = NULL;
1271n/a PyObject *peer;
1272n/a PyObject *peer_alt_names = NULL;
1273n/a PyObject *issuer;
1274n/a PyObject *version;
1275n/a PyObject *sn_obj;
1276n/a PyObject *obj;
1277n/a ASN1_INTEGER *serialNumber;
1278n/a char buf[2048];
1279n/a int len, result;
1280n/a ASN1_TIME *notBefore, *notAfter;
1281n/a PyObject *pnotBefore, *pnotAfter;
1282n/a
1283n/a retval = PyDict_New();
1284n/a if (retval == NULL)
1285n/a return NULL;
1286n/a
1287n/a peer = _create_tuple_for_X509_NAME(
1288n/a X509_get_subject_name(certificate));
1289n/a if (peer == NULL)
1290n/a goto fail0;
1291n/a if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1292n/a Py_DECREF(peer);
1293n/a goto fail0;
1294n/a }
1295n/a Py_DECREF(peer);
1296n/a
1297n/a issuer = _create_tuple_for_X509_NAME(
1298n/a X509_get_issuer_name(certificate));
1299n/a if (issuer == NULL)
1300n/a goto fail0;
1301n/a if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
1302n/a Py_DECREF(issuer);
1303n/a goto fail0;
1304n/a }
1305n/a Py_DECREF(issuer);
1306n/a
1307n/a version = PyLong_FromLong(X509_get_version(certificate) + 1);
1308n/a if (version == NULL)
1309n/a goto fail0;
1310n/a if (PyDict_SetItemString(retval, "version", version) < 0) {
1311n/a Py_DECREF(version);
1312n/a goto fail0;
1313n/a }
1314n/a Py_DECREF(version);
1315n/a
1316n/a /* get a memory buffer */
1317n/a biobuf = BIO_new(BIO_s_mem());
1318n/a
1319n/a (void) BIO_reset(biobuf);
1320n/a serialNumber = X509_get_serialNumber(certificate);
1321n/a /* should not exceed 20 octets, 160 bits, so buf is big enough */
1322n/a i2a_ASN1_INTEGER(biobuf, serialNumber);
1323n/a len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1324n/a if (len < 0) {
1325n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
1326n/a goto fail1;
1327n/a }
1328n/a sn_obj = PyUnicode_FromStringAndSize(buf, len);
1329n/a if (sn_obj == NULL)
1330n/a goto fail1;
1331n/a if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1332n/a Py_DECREF(sn_obj);
1333n/a goto fail1;
1334n/a }
1335n/a Py_DECREF(sn_obj);
1336n/a
1337n/a (void) BIO_reset(biobuf);
1338n/a notBefore = X509_get_notBefore(certificate);
1339n/a ASN1_TIME_print(biobuf, notBefore);
1340n/a len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1341n/a if (len < 0) {
1342n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
1343n/a goto fail1;
1344n/a }
1345n/a pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1346n/a if (pnotBefore == NULL)
1347n/a goto fail1;
1348n/a if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1349n/a Py_DECREF(pnotBefore);
1350n/a goto fail1;
1351n/a }
1352n/a Py_DECREF(pnotBefore);
1353n/a
1354n/a (void) BIO_reset(biobuf);
1355n/a notAfter = X509_get_notAfter(certificate);
1356n/a ASN1_TIME_print(biobuf, notAfter);
1357n/a len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1358n/a if (len < 0) {
1359n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
1360n/a goto fail1;
1361n/a }
1362n/a pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1363n/a if (pnotAfter == NULL)
1364n/a goto fail1;
1365n/a if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1366n/a Py_DECREF(pnotAfter);
1367n/a goto fail1;
1368n/a }
1369n/a Py_DECREF(pnotAfter);
1370n/a
1371n/a /* Now look for subjectAltName */
1372n/a
1373n/a peer_alt_names = _get_peer_alt_names(certificate);
1374n/a if (peer_alt_names == NULL)
1375n/a goto fail1;
1376n/a else if (peer_alt_names != Py_None) {
1377n/a if (PyDict_SetItemString(retval, "subjectAltName",
1378n/a peer_alt_names) < 0) {
1379n/a Py_DECREF(peer_alt_names);
1380n/a goto fail1;
1381n/a }
1382n/a Py_DECREF(peer_alt_names);
1383n/a }
1384n/a
1385n/a /* Authority Information Access: OCSP URIs */
1386n/a obj = _get_aia_uri(certificate, NID_ad_OCSP);
1387n/a if (obj == NULL) {
1388n/a goto fail1;
1389n/a } else if (obj != Py_None) {
1390n/a result = PyDict_SetItemString(retval, "OCSP", obj);
1391n/a Py_DECREF(obj);
1392n/a if (result < 0) {
1393n/a goto fail1;
1394n/a }
1395n/a }
1396n/a
1397n/a obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1398n/a if (obj == NULL) {
1399n/a goto fail1;
1400n/a } else if (obj != Py_None) {
1401n/a result = PyDict_SetItemString(retval, "caIssuers", obj);
1402n/a Py_DECREF(obj);
1403n/a if (result < 0) {
1404n/a goto fail1;
1405n/a }
1406n/a }
1407n/a
1408n/a /* CDP (CRL distribution points) */
1409n/a obj = _get_crl_dp(certificate);
1410n/a if (obj == NULL) {
1411n/a goto fail1;
1412n/a } else if (obj != Py_None) {
1413n/a result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1414n/a Py_DECREF(obj);
1415n/a if (result < 0) {
1416n/a goto fail1;
1417n/a }
1418n/a }
1419n/a
1420n/a BIO_free(biobuf);
1421n/a return retval;
1422n/a
1423n/a fail1:
1424n/a if (biobuf != NULL)
1425n/a BIO_free(biobuf);
1426n/a fail0:
1427n/a Py_XDECREF(retval);
1428n/a return NULL;
1429n/a}
1430n/a
1431n/astatic PyObject *
1432n/a_certificate_to_der(X509 *certificate)
1433n/a{
1434n/a unsigned char *bytes_buf = NULL;
1435n/a int len;
1436n/a PyObject *retval;
1437n/a
1438n/a bytes_buf = NULL;
1439n/a len = i2d_X509(certificate, &bytes_buf);
1440n/a if (len < 0) {
1441n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
1442n/a return NULL;
1443n/a }
1444n/a /* this is actually an immutable bytes sequence */
1445n/a retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1446n/a OPENSSL_free(bytes_buf);
1447n/a return retval;
1448n/a}
1449n/a
1450n/a/*[clinic input]
1451n/a_ssl._test_decode_cert
1452n/a path: object(converter="PyUnicode_FSConverter")
1453n/a /
1454n/a
1455n/a[clinic start generated code]*/
1456n/a
1457n/astatic PyObject *
1458n/a_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1459n/a/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
1460n/a{
1461n/a PyObject *retval = NULL;
1462n/a X509 *x=NULL;
1463n/a BIO *cert;
1464n/a
1465n/a if ((cert=BIO_new(BIO_s_file())) == NULL) {
1466n/a PyErr_SetString(PySSLErrorObject,
1467n/a "Can't malloc memory to read file");
1468n/a goto fail0;
1469n/a }
1470n/a
1471n/a if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
1472n/a PyErr_SetString(PySSLErrorObject,
1473n/a "Can't open file");
1474n/a goto fail0;
1475n/a }
1476n/a
1477n/a x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1478n/a if (x == NULL) {
1479n/a PyErr_SetString(PySSLErrorObject,
1480n/a "Error decoding PEM-encoded file");
1481n/a goto fail0;
1482n/a }
1483n/a
1484n/a retval = _decode_certificate(x);
1485n/a X509_free(x);
1486n/a
1487n/a fail0:
1488n/a Py_DECREF(path);
1489n/a if (cert != NULL) BIO_free(cert);
1490n/a return retval;
1491n/a}
1492n/a
1493n/a
1494n/a/*[clinic input]
1495n/a_ssl._SSLSocket.peer_certificate
1496n/a der as binary_mode: bool = False
1497n/a /
1498n/a
1499n/aReturns the certificate for the peer.
1500n/a
1501n/aIf no certificate was provided, returns None. If a certificate was
1502n/aprovided, but not validated, returns an empty dictionary. Otherwise
1503n/areturns a dict containing information about the peer certificate.
1504n/a
1505n/aIf the optional argument is True, returns a DER-encoded copy of the
1506n/apeer certificate, or None if no certificate was provided. This will
1507n/areturn the certificate even if it wasn't validated.
1508n/a[clinic start generated code]*/
1509n/a
1510n/astatic PyObject *
1511n/a_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1512n/a/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
1513n/a{
1514n/a int verification;
1515n/a
1516n/a if (!self->handshake_done) {
1517n/a PyErr_SetString(PyExc_ValueError,
1518n/a "handshake not done yet");
1519n/a return NULL;
1520n/a }
1521n/a if (!self->peer_cert)
1522n/a Py_RETURN_NONE;
1523n/a
1524n/a if (binary_mode) {
1525n/a /* return cert in DER-encoded format */
1526n/a return _certificate_to_der(self->peer_cert);
1527n/a } else {
1528n/a verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
1529n/a if ((verification & SSL_VERIFY_PEER) == 0)
1530n/a return PyDict_New();
1531n/a else
1532n/a return _decode_certificate(self->peer_cert);
1533n/a }
1534n/a}
1535n/a
1536n/astatic PyObject *
1537n/acipher_to_tuple(const SSL_CIPHER *cipher)
1538n/a{
1539n/a const char *cipher_name, *cipher_protocol;
1540n/a PyObject *v, *retval = PyTuple_New(3);
1541n/a if (retval == NULL)
1542n/a return NULL;
1543n/a
1544n/a cipher_name = SSL_CIPHER_get_name(cipher);
1545n/a if (cipher_name == NULL) {
1546n/a Py_INCREF(Py_None);
1547n/a PyTuple_SET_ITEM(retval, 0, Py_None);
1548n/a } else {
1549n/a v = PyUnicode_FromString(cipher_name);
1550n/a if (v == NULL)
1551n/a goto fail;
1552n/a PyTuple_SET_ITEM(retval, 0, v);
1553n/a }
1554n/a
1555n/a cipher_protocol = SSL_CIPHER_get_version(cipher);
1556n/a if (cipher_protocol == NULL) {
1557n/a Py_INCREF(Py_None);
1558n/a PyTuple_SET_ITEM(retval, 1, Py_None);
1559n/a } else {
1560n/a v = PyUnicode_FromString(cipher_protocol);
1561n/a if (v == NULL)
1562n/a goto fail;
1563n/a PyTuple_SET_ITEM(retval, 1, v);
1564n/a }
1565n/a
1566n/a v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
1567n/a if (v == NULL)
1568n/a goto fail;
1569n/a PyTuple_SET_ITEM(retval, 2, v);
1570n/a
1571n/a return retval;
1572n/a
1573n/a fail:
1574n/a Py_DECREF(retval);
1575n/a return NULL;
1576n/a}
1577n/a
1578n/a#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1579n/astatic PyObject *
1580n/acipher_to_dict(const SSL_CIPHER *cipher)
1581n/a{
1582n/a const char *cipher_name, *cipher_protocol;
1583n/a
1584n/a unsigned long cipher_id;
1585n/a int alg_bits, strength_bits, len;
1586n/a char buf[512] = {0};
1587n/a#if OPENSSL_VERSION_1_1
1588n/a int aead, nid;
1589n/a const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1590n/a#endif
1591n/a
1592n/a /* can be NULL */
1593n/a cipher_name = SSL_CIPHER_get_name(cipher);
1594n/a cipher_protocol = SSL_CIPHER_get_version(cipher);
1595n/a cipher_id = SSL_CIPHER_get_id(cipher);
1596n/a SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1597n/a len = strlen(buf);
1598n/a if (len > 1 && buf[len-1] == '\n')
1599n/a buf[len-1] = '\0';
1600n/a strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1601n/a
1602n/a#if OPENSSL_VERSION_1_1
1603n/a aead = SSL_CIPHER_is_aead(cipher);
1604n/a nid = SSL_CIPHER_get_cipher_nid(cipher);
1605n/a skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1606n/a nid = SSL_CIPHER_get_digest_nid(cipher);
1607n/a digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1608n/a nid = SSL_CIPHER_get_kx_nid(cipher);
1609n/a kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1610n/a nid = SSL_CIPHER_get_auth_nid(cipher);
1611n/a auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1612n/a#endif
1613n/a
1614n/a return Py_BuildValue(
1615n/a "{sksssssssisi"
1616n/a#if OPENSSL_VERSION_1_1
1617n/a "sOssssssss"
1618n/a#endif
1619n/a "}",
1620n/a "id", cipher_id,
1621n/a "name", cipher_name,
1622n/a "protocol", cipher_protocol,
1623n/a "description", buf,
1624n/a "strength_bits", strength_bits,
1625n/a "alg_bits", alg_bits
1626n/a#if OPENSSL_VERSION_1_1
1627n/a ,"aead", aead ? Py_True : Py_False,
1628n/a "symmetric", skcipher,
1629n/a "digest", digest,
1630n/a "kea", kx,
1631n/a "auth", auth
1632n/a#endif
1633n/a );
1634n/a}
1635n/a#endif
1636n/a
1637n/a/*[clinic input]
1638n/a_ssl._SSLSocket.shared_ciphers
1639n/a[clinic start generated code]*/
1640n/a
1641n/astatic PyObject *
1642n/a_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1643n/a/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
1644n/a{
1645n/a STACK_OF(SSL_CIPHER) *ciphers;
1646n/a int i;
1647n/a PyObject *res;
1648n/a
1649n/a ciphers = SSL_get_ciphers(self->ssl);
1650n/a if (!ciphers)
1651n/a Py_RETURN_NONE;
1652n/a res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1653n/a if (!res)
1654n/a return NULL;
1655n/a for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1656n/a PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1657n/a if (!tup) {
1658n/a Py_DECREF(res);
1659n/a return NULL;
1660n/a }
1661n/a PyList_SET_ITEM(res, i, tup);
1662n/a }
1663n/a return res;
1664n/a}
1665n/a
1666n/a/*[clinic input]
1667n/a_ssl._SSLSocket.cipher
1668n/a[clinic start generated code]*/
1669n/a
1670n/astatic PyObject *
1671n/a_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1672n/a/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
1673n/a{
1674n/a const SSL_CIPHER *current;
1675n/a
1676n/a if (self->ssl == NULL)
1677n/a Py_RETURN_NONE;
1678n/a current = SSL_get_current_cipher(self->ssl);
1679n/a if (current == NULL)
1680n/a Py_RETURN_NONE;
1681n/a return cipher_to_tuple(current);
1682n/a}
1683n/a
1684n/a/*[clinic input]
1685n/a_ssl._SSLSocket.version
1686n/a[clinic start generated code]*/
1687n/a
1688n/astatic PyObject *
1689n/a_ssl__SSLSocket_version_impl(PySSLSocket *self)
1690n/a/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
1691n/a{
1692n/a const char *version;
1693n/a
1694n/a if (self->ssl == NULL)
1695n/a Py_RETURN_NONE;
1696n/a version = SSL_get_version(self->ssl);
1697n/a if (!strcmp(version, "unknown"))
1698n/a Py_RETURN_NONE;
1699n/a return PyUnicode_FromString(version);
1700n/a}
1701n/a
1702n/a#ifdef OPENSSL_NPN_NEGOTIATED
1703n/a/*[clinic input]
1704n/a_ssl._SSLSocket.selected_npn_protocol
1705n/a[clinic start generated code]*/
1706n/a
1707n/astatic PyObject *
1708n/a_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1709n/a/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1710n/a{
1711n/a const unsigned char *out;
1712n/a unsigned int outlen;
1713n/a
1714n/a SSL_get0_next_proto_negotiated(self->ssl,
1715n/a &out, &outlen);
1716n/a
1717n/a if (out == NULL)
1718n/a Py_RETURN_NONE;
1719n/a return PyUnicode_FromStringAndSize((char *)out, outlen);
1720n/a}
1721n/a#endif
1722n/a
1723n/a#ifdef HAVE_ALPN
1724n/a/*[clinic input]
1725n/a_ssl._SSLSocket.selected_alpn_protocol
1726n/a[clinic start generated code]*/
1727n/a
1728n/astatic PyObject *
1729n/a_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1730n/a/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1731n/a{
1732n/a const unsigned char *out;
1733n/a unsigned int outlen;
1734n/a
1735n/a SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1736n/a
1737n/a if (out == NULL)
1738n/a Py_RETURN_NONE;
1739n/a return PyUnicode_FromStringAndSize((char *)out, outlen);
1740n/a}
1741n/a#endif
1742n/a
1743n/a/*[clinic input]
1744n/a_ssl._SSLSocket.compression
1745n/a[clinic start generated code]*/
1746n/a
1747n/astatic PyObject *
1748n/a_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1749n/a/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1750n/a{
1751n/a#ifdef OPENSSL_NO_COMP
1752n/a Py_RETURN_NONE;
1753n/a#else
1754n/a const COMP_METHOD *comp_method;
1755n/a const char *short_name;
1756n/a
1757n/a if (self->ssl == NULL)
1758n/a Py_RETURN_NONE;
1759n/a comp_method = SSL_get_current_compression(self->ssl);
1760n/a if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
1761n/a Py_RETURN_NONE;
1762n/a short_name = OBJ_nid2sn(COMP_get_type(comp_method));
1763n/a if (short_name == NULL)
1764n/a Py_RETURN_NONE;
1765n/a return PyUnicode_DecodeFSDefault(short_name);
1766n/a#endif
1767n/a}
1768n/a
1769n/astatic PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1770n/a Py_INCREF(self->ctx);
1771n/a return self->ctx;
1772n/a}
1773n/a
1774n/astatic int PySSL_set_context(PySSLSocket *self, PyObject *value,
1775n/a void *closure) {
1776n/a
1777n/a if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1778n/a#if !HAVE_SNI
1779n/a PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1780n/a "context is not supported by your OpenSSL library");
1781n/a return -1;
1782n/a#else
1783n/a Py_INCREF(value);
1784n/a Py_SETREF(self->ctx, (PySSLContext *)value);
1785n/a SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1786n/a#endif
1787n/a } else {
1788n/a PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1789n/a return -1;
1790n/a }
1791n/a
1792n/a return 0;
1793n/a}
1794n/a
1795n/aPyDoc_STRVAR(PySSL_set_context_doc,
1796n/a"_setter_context(ctx)\n\
1797n/a\
1798n/aThis changes the context associated with the SSLSocket. This is typically\n\
1799n/aused from within a callback function set by the set_servername_callback\n\
1800n/aon the SSLContext to change the certificate information associated with the\n\
1801n/aSSLSocket before the cryptographic exchange handshake messages\n");
1802n/a
1803n/a
1804n/astatic PyObject *
1805n/aPySSL_get_server_side(PySSLSocket *self, void *c)
1806n/a{
1807n/a return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1808n/a}
1809n/a
1810n/aPyDoc_STRVAR(PySSL_get_server_side_doc,
1811n/a"Whether this is a server-side socket.");
1812n/a
1813n/astatic PyObject *
1814n/aPySSL_get_server_hostname(PySSLSocket *self, void *c)
1815n/a{
1816n/a if (self->server_hostname == NULL)
1817n/a Py_RETURN_NONE;
1818n/a Py_INCREF(self->server_hostname);
1819n/a return self->server_hostname;
1820n/a}
1821n/a
1822n/aPyDoc_STRVAR(PySSL_get_server_hostname_doc,
1823n/a"The currently set server hostname (for SNI).");
1824n/a
1825n/astatic PyObject *
1826n/aPySSL_get_owner(PySSLSocket *self, void *c)
1827n/a{
1828n/a PyObject *owner;
1829n/a
1830n/a if (self->owner == NULL)
1831n/a Py_RETURN_NONE;
1832n/a
1833n/a owner = PyWeakref_GetObject(self->owner);
1834n/a Py_INCREF(owner);
1835n/a return owner;
1836n/a}
1837n/a
1838n/astatic int
1839n/aPySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1840n/a{
1841n/a Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
1842n/a if (self->owner == NULL)
1843n/a return -1;
1844n/a return 0;
1845n/a}
1846n/a
1847n/aPyDoc_STRVAR(PySSL_get_owner_doc,
1848n/a"The Python-level owner of this object.\
1849n/aPassed as \"self\" in servername callback.");
1850n/a
1851n/a
1852n/astatic void PySSL_dealloc(PySSLSocket *self)
1853n/a{
1854n/a if (self->peer_cert) /* Possible not to have one? */
1855n/a X509_free (self->peer_cert);
1856n/a if (self->ssl)
1857n/a SSL_free(self->ssl);
1858n/a Py_XDECREF(self->Socket);
1859n/a Py_XDECREF(self->ctx);
1860n/a Py_XDECREF(self->server_hostname);
1861n/a Py_XDECREF(self->owner);
1862n/a PyObject_Del(self);
1863n/a}
1864n/a
1865n/a/* If the socket has a timeout, do a select()/poll() on the socket.
1866n/a The argument writing indicates the direction.
1867n/a Returns one of the possibilities in the timeout_state enum (above).
1868n/a */
1869n/a
1870n/astatic int
1871n/aPySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
1872n/a{
1873n/a int rc;
1874n/a#ifdef HAVE_POLL
1875n/a struct pollfd pollfd;
1876n/a _PyTime_t ms;
1877n/a#else
1878n/a int nfds;
1879n/a fd_set fds;
1880n/a struct timeval tv;
1881n/a#endif
1882n/a
1883n/a /* Nothing to do unless we're in timeout mode (not non-blocking) */
1884n/a if ((s == NULL) || (timeout == 0))
1885n/a return SOCKET_IS_NONBLOCKING;
1886n/a else if (timeout < 0) {
1887n/a if (s->sock_timeout > 0)
1888n/a return SOCKET_HAS_TIMED_OUT;
1889n/a else
1890n/a return SOCKET_IS_BLOCKING;
1891n/a }
1892n/a
1893n/a /* Guard against closed socket */
1894n/a if (s->sock_fd == INVALID_SOCKET)
1895n/a return SOCKET_HAS_BEEN_CLOSED;
1896n/a
1897n/a /* Prefer poll, if available, since you can poll() any fd
1898n/a * which can't be done with select(). */
1899n/a#ifdef HAVE_POLL
1900n/a pollfd.fd = s->sock_fd;
1901n/a pollfd.events = writing ? POLLOUT : POLLIN;
1902n/a
1903n/a /* timeout is in seconds, poll() uses milliseconds */
1904n/a ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
1905n/a assert(ms <= INT_MAX);
1906n/a
1907n/a PySSL_BEGIN_ALLOW_THREADS
1908n/a rc = poll(&pollfd, 1, (int)ms);
1909n/a PySSL_END_ALLOW_THREADS
1910n/a#else
1911n/a /* Guard against socket too large for select*/
1912n/a if (!_PyIsSelectable_fd(s->sock_fd))
1913n/a return SOCKET_TOO_LARGE_FOR_SELECT;
1914n/a
1915n/a _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
1916n/a
1917n/a FD_ZERO(&fds);
1918n/a FD_SET(s->sock_fd, &fds);
1919n/a
1920n/a /* Wait until the socket becomes ready */
1921n/a PySSL_BEGIN_ALLOW_THREADS
1922n/a nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
1923n/a if (writing)
1924n/a rc = select(nfds, NULL, &fds, NULL, &tv);
1925n/a else
1926n/a rc = select(nfds, &fds, NULL, NULL, &tv);
1927n/a PySSL_END_ALLOW_THREADS
1928n/a#endif
1929n/a
1930n/a /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1931n/a (when we are able to write or when there's something to read) */
1932n/a return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
1933n/a}
1934n/a
1935n/a/*[clinic input]
1936n/a_ssl._SSLSocket.write
1937n/a b: Py_buffer
1938n/a /
1939n/a
1940n/aWrites the bytes-like object b into the SSL object.
1941n/a
1942n/aReturns the number of bytes written.
1943n/a[clinic start generated code]*/
1944n/a
1945n/astatic PyObject *
1946n/a_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1947n/a/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
1948n/a{
1949n/a int len;
1950n/a int sockstate;
1951n/a int err;
1952n/a int nonblocking;
1953n/a PySocketSockObject *sock = GET_SOCKET(self);
1954n/a _PyTime_t timeout, deadline = 0;
1955n/a int has_timeout;
1956n/a
1957n/a if (sock != NULL) {
1958n/a if (((PyObject*)sock) == Py_None) {
1959n/a _setSSLError("Underlying socket connection gone",
1960n/a PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1961n/a return NULL;
1962n/a }
1963n/a Py_INCREF(sock);
1964n/a }
1965n/a
1966n/a if (b->len > INT_MAX) {
1967n/a PyErr_Format(PyExc_OverflowError,
1968n/a "string longer than %d bytes", INT_MAX);
1969n/a goto error;
1970n/a }
1971n/a
1972n/a if (sock != NULL) {
1973n/a /* just in case the blocking state of the socket has been changed */
1974n/a nonblocking = (sock->sock_timeout >= 0);
1975n/a BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1976n/a BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1977n/a }
1978n/a
1979n/a timeout = GET_SOCKET_TIMEOUT(sock);
1980n/a has_timeout = (timeout > 0);
1981n/a if (has_timeout)
1982n/a deadline = _PyTime_GetMonotonicClock() + timeout;
1983n/a
1984n/a sockstate = PySSL_select(sock, 1, timeout);
1985n/a if (sockstate == SOCKET_HAS_TIMED_OUT) {
1986n/a PyErr_SetString(PySocketModule.timeout_error,
1987n/a "The write operation timed out");
1988n/a goto error;
1989n/a } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1990n/a PyErr_SetString(PySSLErrorObject,
1991n/a "Underlying socket has been closed.");
1992n/a goto error;
1993n/a } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1994n/a PyErr_SetString(PySSLErrorObject,
1995n/a "Underlying socket too large for select().");
1996n/a goto error;
1997n/a }
1998n/a
1999n/a do {
2000n/a PySSL_BEGIN_ALLOW_THREADS
2001n/a len = SSL_write(self->ssl, b->buf, (int)b->len);
2002n/a err = SSL_get_error(self->ssl, len);
2003n/a PySSL_END_ALLOW_THREADS
2004n/a
2005n/a if (PyErr_CheckSignals())
2006n/a goto error;
2007n/a
2008n/a if (has_timeout)
2009n/a timeout = deadline - _PyTime_GetMonotonicClock();
2010n/a
2011n/a if (err == SSL_ERROR_WANT_READ) {
2012n/a sockstate = PySSL_select(sock, 0, timeout);
2013n/a } else if (err == SSL_ERROR_WANT_WRITE) {
2014n/a sockstate = PySSL_select(sock, 1, timeout);
2015n/a } else {
2016n/a sockstate = SOCKET_OPERATION_OK;
2017n/a }
2018n/a
2019n/a if (sockstate == SOCKET_HAS_TIMED_OUT) {
2020n/a PyErr_SetString(PySocketModule.timeout_error,
2021n/a "The write operation timed out");
2022n/a goto error;
2023n/a } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2024n/a PyErr_SetString(PySSLErrorObject,
2025n/a "Underlying socket has been closed.");
2026n/a goto error;
2027n/a } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2028n/a break;
2029n/a }
2030n/a } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
2031n/a
2032n/a Py_XDECREF(sock);
2033n/a if (len > 0)
2034n/a return PyLong_FromLong(len);
2035n/a else
2036n/a return PySSL_SetError(self, len, __FILE__, __LINE__);
2037n/a
2038n/aerror:
2039n/a Py_XDECREF(sock);
2040n/a return NULL;
2041n/a}
2042n/a
2043n/a/*[clinic input]
2044n/a_ssl._SSLSocket.pending
2045n/a
2046n/aReturns the number of already decrypted bytes available for read, pending on the connection.
2047n/a[clinic start generated code]*/
2048n/a
2049n/astatic PyObject *
2050n/a_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2051n/a/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
2052n/a{
2053n/a int count = 0;
2054n/a
2055n/a PySSL_BEGIN_ALLOW_THREADS
2056n/a count = SSL_pending(self->ssl);
2057n/a PySSL_END_ALLOW_THREADS
2058n/a if (count < 0)
2059n/a return PySSL_SetError(self, count, __FILE__, __LINE__);
2060n/a else
2061n/a return PyLong_FromLong(count);
2062n/a}
2063n/a
2064n/a/*[clinic input]
2065n/a_ssl._SSLSocket.read
2066n/a size as len: int
2067n/a [
2068n/a buffer: Py_buffer(accept={rwbuffer})
2069n/a ]
2070n/a /
2071n/a
2072n/aRead up to size bytes from the SSL socket.
2073n/a[clinic start generated code]*/
2074n/a
2075n/astatic PyObject *
2076n/a_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2077n/a Py_buffer *buffer)
2078n/a/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
2079n/a{
2080n/a PyObject *dest = NULL;
2081n/a char *mem;
2082n/a int count;
2083n/a int sockstate;
2084n/a int err;
2085n/a int nonblocking;
2086n/a PySocketSockObject *sock = GET_SOCKET(self);
2087n/a _PyTime_t timeout, deadline = 0;
2088n/a int has_timeout;
2089n/a
2090n/a if (!group_right_1 && len < 0) {
2091n/a PyErr_SetString(PyExc_ValueError, "size should not be negative");
2092n/a return NULL;
2093n/a }
2094n/a
2095n/a if (sock != NULL) {
2096n/a if (((PyObject*)sock) == Py_None) {
2097n/a _setSSLError("Underlying socket connection gone",
2098n/a PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2099n/a return NULL;
2100n/a }
2101n/a Py_INCREF(sock);
2102n/a }
2103n/a
2104n/a if (!group_right_1) {
2105n/a dest = PyBytes_FromStringAndSize(NULL, len);
2106n/a if (dest == NULL)
2107n/a goto error;
2108n/a if (len == 0) {
2109n/a Py_XDECREF(sock);
2110n/a return dest;
2111n/a }
2112n/a mem = PyBytes_AS_STRING(dest);
2113n/a }
2114n/a else {
2115n/a mem = buffer->buf;
2116n/a if (len <= 0 || len > buffer->len) {
2117n/a len = (int) buffer->len;
2118n/a if (buffer->len != len) {
2119n/a PyErr_SetString(PyExc_OverflowError,
2120n/a "maximum length can't fit in a C 'int'");
2121n/a goto error;
2122n/a }
2123n/a if (len == 0) {
2124n/a count = 0;
2125n/a goto done;
2126n/a }
2127n/a }
2128n/a }
2129n/a
2130n/a if (sock != NULL) {
2131n/a /* just in case the blocking state of the socket has been changed */
2132n/a nonblocking = (sock->sock_timeout >= 0);
2133n/a BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2134n/a BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2135n/a }
2136n/a
2137n/a timeout = GET_SOCKET_TIMEOUT(sock);
2138n/a has_timeout = (timeout > 0);
2139n/a if (has_timeout)
2140n/a deadline = _PyTime_GetMonotonicClock() + timeout;
2141n/a
2142n/a do {
2143n/a PySSL_BEGIN_ALLOW_THREADS
2144n/a count = SSL_read(self->ssl, mem, len);
2145n/a err = SSL_get_error(self->ssl, count);
2146n/a PySSL_END_ALLOW_THREADS
2147n/a
2148n/a if (PyErr_CheckSignals())
2149n/a goto error;
2150n/a
2151n/a if (has_timeout)
2152n/a timeout = deadline - _PyTime_GetMonotonicClock();
2153n/a
2154n/a if (err == SSL_ERROR_WANT_READ) {
2155n/a sockstate = PySSL_select(sock, 0, timeout);
2156n/a } else if (err == SSL_ERROR_WANT_WRITE) {
2157n/a sockstate = PySSL_select(sock, 1, timeout);
2158n/a } else if (err == SSL_ERROR_ZERO_RETURN &&
2159n/a SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
2160n/a {
2161n/a count = 0;
2162n/a goto done;
2163n/a }
2164n/a else
2165n/a sockstate = SOCKET_OPERATION_OK;
2166n/a
2167n/a if (sockstate == SOCKET_HAS_TIMED_OUT) {
2168n/a PyErr_SetString(PySocketModule.timeout_error,
2169n/a "The read operation timed out");
2170n/a goto error;
2171n/a } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2172n/a break;
2173n/a }
2174n/a } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
2175n/a
2176n/a if (count <= 0) {
2177n/a PySSL_SetError(self, count, __FILE__, __LINE__);
2178n/a goto error;
2179n/a }
2180n/a
2181n/adone:
2182n/a Py_XDECREF(sock);
2183n/a if (!group_right_1) {
2184n/a _PyBytes_Resize(&dest, count);
2185n/a return dest;
2186n/a }
2187n/a else {
2188n/a return PyLong_FromLong(count);
2189n/a }
2190n/a
2191n/aerror:
2192n/a Py_XDECREF(sock);
2193n/a if (!group_right_1)
2194n/a Py_XDECREF(dest);
2195n/a return NULL;
2196n/a}
2197n/a
2198n/a/*[clinic input]
2199n/a_ssl._SSLSocket.shutdown
2200n/a
2201n/aDoes the SSL shutdown handshake with the remote end.
2202n/a
2203n/aReturns the underlying socket object.
2204n/a[clinic start generated code]*/
2205n/a
2206n/astatic PyObject *
2207n/a_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2208n/a/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
2209n/a{
2210n/a int err, ssl_err, sockstate, nonblocking;
2211n/a int zeros = 0;
2212n/a PySocketSockObject *sock = GET_SOCKET(self);
2213n/a _PyTime_t timeout, deadline = 0;
2214n/a int has_timeout;
2215n/a
2216n/a if (sock != NULL) {
2217n/a /* Guard against closed socket */
2218n/a if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
2219n/a _setSSLError("Underlying socket connection gone",
2220n/a PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2221n/a return NULL;
2222n/a }
2223n/a Py_INCREF(sock);
2224n/a
2225n/a /* Just in case the blocking state of the socket has been changed */
2226n/a nonblocking = (sock->sock_timeout >= 0);
2227n/a BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2228n/a BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2229n/a }
2230n/a
2231n/a timeout = GET_SOCKET_TIMEOUT(sock);
2232n/a has_timeout = (timeout > 0);
2233n/a if (has_timeout)
2234n/a deadline = _PyTime_GetMonotonicClock() + timeout;
2235n/a
2236n/a while (1) {
2237n/a PySSL_BEGIN_ALLOW_THREADS
2238n/a /* Disable read-ahead so that unwrap can work correctly.
2239n/a * Otherwise OpenSSL might read in too much data,
2240n/a * eating clear text data that happens to be
2241n/a * transmitted after the SSL shutdown.
2242n/a * Should be safe to call repeatedly every time this
2243n/a * function is used and the shutdown_seen_zero != 0
2244n/a * condition is met.
2245n/a */
2246n/a if (self->shutdown_seen_zero)
2247n/a SSL_set_read_ahead(self->ssl, 0);
2248n/a err = SSL_shutdown(self->ssl);
2249n/a PySSL_END_ALLOW_THREADS
2250n/a
2251n/a /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2252n/a if (err > 0)
2253n/a break;
2254n/a if (err == 0) {
2255n/a /* Don't loop endlessly; instead preserve legacy
2256n/a behaviour of trying SSL_shutdown() only twice.
2257n/a This looks necessary for OpenSSL < 0.9.8m */
2258n/a if (++zeros > 1)
2259n/a break;
2260n/a /* Shutdown was sent, now try receiving */
2261n/a self->shutdown_seen_zero = 1;
2262n/a continue;
2263n/a }
2264n/a
2265n/a if (has_timeout)
2266n/a timeout = deadline - _PyTime_GetMonotonicClock();
2267n/a
2268n/a /* Possibly retry shutdown until timeout or failure */
2269n/a ssl_err = SSL_get_error(self->ssl, err);
2270n/a if (ssl_err == SSL_ERROR_WANT_READ)
2271n/a sockstate = PySSL_select(sock, 0, timeout);
2272n/a else if (ssl_err == SSL_ERROR_WANT_WRITE)
2273n/a sockstate = PySSL_select(sock, 1, timeout);
2274n/a else
2275n/a break;
2276n/a
2277n/a if (sockstate == SOCKET_HAS_TIMED_OUT) {
2278n/a if (ssl_err == SSL_ERROR_WANT_READ)
2279n/a PyErr_SetString(PySocketModule.timeout_error,
2280n/a "The read operation timed out");
2281n/a else
2282n/a PyErr_SetString(PySocketModule.timeout_error,
2283n/a "The write operation timed out");
2284n/a goto error;
2285n/a }
2286n/a else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2287n/a PyErr_SetString(PySSLErrorObject,
2288n/a "Underlying socket too large for select().");
2289n/a goto error;
2290n/a }
2291n/a else if (sockstate != SOCKET_OPERATION_OK)
2292n/a /* Retain the SSL error code */
2293n/a break;
2294n/a }
2295n/a
2296n/a if (err < 0) {
2297n/a Py_XDECREF(sock);
2298n/a return PySSL_SetError(self, err, __FILE__, __LINE__);
2299n/a }
2300n/a if (sock)
2301n/a /* It's already INCREF'ed */
2302n/a return (PyObject *) sock;
2303n/a else
2304n/a Py_RETURN_NONE;
2305n/a
2306n/aerror:
2307n/a Py_XDECREF(sock);
2308n/a return NULL;
2309n/a}
2310n/a
2311n/a/*[clinic input]
2312n/a_ssl._SSLSocket.tls_unique_cb
2313n/a
2314n/aReturns the 'tls-unique' channel binding data, as defined by RFC 5929.
2315n/a
2316n/aIf the TLS handshake is not yet complete, None is returned.
2317n/a[clinic start generated code]*/
2318n/a
2319n/astatic PyObject *
2320n/a_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2321n/a/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
2322n/a{
2323n/a PyObject *retval = NULL;
2324n/a char buf[PySSL_CB_MAXLEN];
2325n/a size_t len;
2326n/a
2327n/a if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2328n/a /* if session is resumed XOR we are the client */
2329n/a len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2330n/a }
2331n/a else {
2332n/a /* if a new session XOR we are the server */
2333n/a len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2334n/a }
2335n/a
2336n/a /* It cannot be negative in current OpenSSL version as of July 2011 */
2337n/a if (len == 0)
2338n/a Py_RETURN_NONE;
2339n/a
2340n/a retval = PyBytes_FromStringAndSize(buf, len);
2341n/a
2342n/a return retval;
2343n/a}
2344n/a
2345n/a#ifdef OPENSSL_VERSION_1_1
2346n/a
2347n/astatic SSL_SESSION*
2348n/a_ssl_session_dup(SSL_SESSION *session) {
2349n/a SSL_SESSION *newsession = NULL;
2350n/a int slen;
2351n/a unsigned char *senc = NULL, *p;
2352n/a const unsigned char *const_p;
2353n/a
2354n/a if (session == NULL) {
2355n/a PyErr_SetString(PyExc_ValueError, "Invalid session");
2356n/a goto error;
2357n/a }
2358n/a
2359n/a /* get length */
2360n/a slen = i2d_SSL_SESSION(session, NULL);
2361n/a if (slen == 0 || slen > 0xFF00) {
2362n/a PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2363n/a goto error;
2364n/a }
2365n/a if ((senc = PyMem_Malloc(slen)) == NULL) {
2366n/a PyErr_NoMemory();
2367n/a goto error;
2368n/a }
2369n/a p = senc;
2370n/a if (!i2d_SSL_SESSION(session, &p)) {
2371n/a PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2372n/a goto error;
2373n/a }
2374n/a const_p = senc;
2375n/a newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2376n/a if (session == NULL) {
2377n/a goto error;
2378n/a }
2379n/a PyMem_Free(senc);
2380n/a return newsession;
2381n/a error:
2382n/a if (senc != NULL) {
2383n/a PyMem_Free(senc);
2384n/a }
2385n/a return NULL;
2386n/a}
2387n/a#endif
2388n/a
2389n/astatic PyObject *
2390n/aPySSL_get_session(PySSLSocket *self, void *closure) {
2391n/a /* get_session can return sessions from a server-side connection,
2392n/a * it does not check for handshake done or client socket. */
2393n/a PySSLSession *pysess;
2394n/a SSL_SESSION *session;
2395n/a
2396n/a#ifdef OPENSSL_VERSION_1_1
2397n/a /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2398n/a * https://github.com/openssl/openssl/issues/1550 */
2399n/a session = SSL_get0_session(self->ssl); /* borrowed reference */
2400n/a if (session == NULL) {
2401n/a Py_RETURN_NONE;
2402n/a }
2403n/a if ((session = _ssl_session_dup(session)) == NULL) {
2404n/a return NULL;
2405n/a }
2406n/a#else
2407n/a session = SSL_get1_session(self->ssl);
2408n/a if (session == NULL) {
2409n/a Py_RETURN_NONE;
2410n/a }
2411n/a#endif
2412n/a pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
2413n/a if (pysess == NULL) {
2414n/a SSL_SESSION_free(session);
2415n/a return NULL;
2416n/a }
2417n/a
2418n/a assert(self->ctx);
2419n/a pysess->ctx = self->ctx;
2420n/a Py_INCREF(pysess->ctx);
2421n/a pysess->session = session;
2422n/a PyObject_GC_Track(pysess);
2423n/a return (PyObject *)pysess;
2424n/a}
2425n/a
2426n/astatic int PySSL_set_session(PySSLSocket *self, PyObject *value,
2427n/a void *closure)
2428n/a {
2429n/a PySSLSession *pysess;
2430n/a#ifdef OPENSSL_VERSION_1_1
2431n/a SSL_SESSION *session;
2432n/a#endif
2433n/a int result;
2434n/a
2435n/a if (!PySSLSession_Check(value)) {
2436n/a PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2437n/a return -1;
2438n/a }
2439n/a pysess = (PySSLSession *)value;
2440n/a
2441n/a if (self->ctx->ctx != pysess->ctx->ctx) {
2442n/a PyErr_SetString(PyExc_ValueError,
2443n/a "Session refers to a different SSLContext.");
2444n/a return -1;
2445n/a }
2446n/a if (self->socket_type != PY_SSL_CLIENT) {
2447n/a PyErr_SetString(PyExc_ValueError,
2448n/a "Cannot set session for server-side SSLSocket.");
2449n/a return -1;
2450n/a }
2451n/a if (self->handshake_done) {
2452n/a PyErr_SetString(PyExc_ValueError,
2453n/a "Cannot set session after handshake.");
2454n/a return -1;
2455n/a }
2456n/a#ifdef OPENSSL_VERSION_1_1
2457n/a /* duplicate session */
2458n/a if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2459n/a return -1;
2460n/a }
2461n/a result = SSL_set_session(self->ssl, session);
2462n/a /* free duplicate, SSL_set_session() bumps ref count */
2463n/a SSL_SESSION_free(session);
2464n/a#else
2465n/a result = SSL_set_session(self->ssl, pysess->session);
2466n/a#endif
2467n/a if (result == 0) {
2468n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
2469n/a return -1;
2470n/a }
2471n/a return 0;
2472n/a}
2473n/a
2474n/aPyDoc_STRVAR(PySSL_set_session_doc,
2475n/a"_setter_session(session)\n\
2476n/a\
2477n/aGet / set SSLSession.");
2478n/a
2479n/astatic PyObject *
2480n/aPySSL_get_session_reused(PySSLSocket *self, void *closure) {
2481n/a if (SSL_session_reused(self->ssl)) {
2482n/a Py_RETURN_TRUE;
2483n/a } else {
2484n/a Py_RETURN_FALSE;
2485n/a }
2486n/a}
2487n/a
2488n/aPyDoc_STRVAR(PySSL_get_session_reused_doc,
2489n/a"Was the client session reused during handshake?");
2490n/a
2491n/astatic PyGetSetDef ssl_getsetlist[] = {
2492n/a {"context", (getter) PySSL_get_context,
2493n/a (setter) PySSL_set_context, PySSL_set_context_doc},
2494n/a {"server_side", (getter) PySSL_get_server_side, NULL,
2495n/a PySSL_get_server_side_doc},
2496n/a {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2497n/a PySSL_get_server_hostname_doc},
2498n/a {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2499n/a PySSL_get_owner_doc},
2500n/a {"session", (getter) PySSL_get_session,
2501n/a (setter) PySSL_set_session, PySSL_set_session_doc},
2502n/a {"session_reused", (getter) PySSL_get_session_reused, NULL,
2503n/a PySSL_get_session_reused_doc},
2504n/a {NULL}, /* sentinel */
2505n/a};
2506n/a
2507n/astatic PyMethodDef PySSLMethods[] = {
2508n/a _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2509n/a _SSL__SSLSOCKET_WRITE_METHODDEF
2510n/a _SSL__SSLSOCKET_READ_METHODDEF
2511n/a _SSL__SSLSOCKET_PENDING_METHODDEF
2512n/a _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2513n/a _SSL__SSLSOCKET_CIPHER_METHODDEF
2514n/a _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2515n/a _SSL__SSLSOCKET_VERSION_METHODDEF
2516n/a _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2517n/a _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2518n/a _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2519n/a _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2520n/a _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
2521n/a {NULL, NULL}
2522n/a};
2523n/a
2524n/astatic PyTypeObject PySSLSocket_Type = {
2525n/a PyVarObject_HEAD_INIT(NULL, 0)
2526n/a "_ssl._SSLSocket", /*tp_name*/
2527n/a sizeof(PySSLSocket), /*tp_basicsize*/
2528n/a 0, /*tp_itemsize*/
2529n/a /* methods */
2530n/a (destructor)PySSL_dealloc, /*tp_dealloc*/
2531n/a 0, /*tp_print*/
2532n/a 0, /*tp_getattr*/
2533n/a 0, /*tp_setattr*/
2534n/a 0, /*tp_reserved*/
2535n/a 0, /*tp_repr*/
2536n/a 0, /*tp_as_number*/
2537n/a 0, /*tp_as_sequence*/
2538n/a 0, /*tp_as_mapping*/
2539n/a 0, /*tp_hash*/
2540n/a 0, /*tp_call*/
2541n/a 0, /*tp_str*/
2542n/a 0, /*tp_getattro*/
2543n/a 0, /*tp_setattro*/
2544n/a 0, /*tp_as_buffer*/
2545n/a Py_TPFLAGS_DEFAULT, /*tp_flags*/
2546n/a 0, /*tp_doc*/
2547n/a 0, /*tp_traverse*/
2548n/a 0, /*tp_clear*/
2549n/a 0, /*tp_richcompare*/
2550n/a 0, /*tp_weaklistoffset*/
2551n/a 0, /*tp_iter*/
2552n/a 0, /*tp_iternext*/
2553n/a PySSLMethods, /*tp_methods*/
2554n/a 0, /*tp_members*/
2555n/a ssl_getsetlist, /*tp_getset*/
2556n/a};
2557n/a
2558n/a
2559n/a/*
2560n/a * _SSLContext objects
2561n/a */
2562n/a
2563n/astatic int
2564n/a_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2565n/a{
2566n/a int mode;
2567n/a int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2568n/a
2569n/a switch(n) {
2570n/a case PY_SSL_CERT_NONE:
2571n/a mode = SSL_VERIFY_NONE;
2572n/a break;
2573n/a case PY_SSL_CERT_OPTIONAL:
2574n/a mode = SSL_VERIFY_PEER;
2575n/a break;
2576n/a case PY_SSL_CERT_REQUIRED:
2577n/a mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2578n/a break;
2579n/a default:
2580n/a PyErr_SetString(PyExc_ValueError,
2581n/a "invalid value for verify_mode");
2582n/a return -1;
2583n/a }
2584n/a /* keep current verify cb */
2585n/a verify_cb = SSL_CTX_get_verify_callback(ctx);
2586n/a SSL_CTX_set_verify(ctx, mode, verify_cb);
2587n/a return 0;
2588n/a}
2589n/a
2590n/a/*[clinic input]
2591n/a@classmethod
2592n/a_ssl._SSLContext.__new__
2593n/a protocol as proto_version: int
2594n/a /
2595n/a[clinic start generated code]*/
2596n/a
2597n/astatic PyObject *
2598n/a_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2599n/a/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
2600n/a{
2601n/a PySSLContext *self;
2602n/a long options;
2603n/a SSL_CTX *ctx = NULL;
2604n/a int result;
2605n/a#if defined(SSL_MODE_RELEASE_BUFFERS)
2606n/a unsigned long libver;
2607n/a#endif
2608n/a
2609n/a PySSL_BEGIN_ALLOW_THREADS
2610n/a if (proto_version == PY_SSL_VERSION_TLS1)
2611n/a ctx = SSL_CTX_new(TLSv1_method());
2612n/a#if HAVE_TLSv1_2
2613n/a else if (proto_version == PY_SSL_VERSION_TLS1_1)
2614n/a ctx = SSL_CTX_new(TLSv1_1_method());
2615n/a else if (proto_version == PY_SSL_VERSION_TLS1_2)
2616n/a ctx = SSL_CTX_new(TLSv1_2_method());
2617n/a#endif
2618n/a#ifndef OPENSSL_NO_SSL3
2619n/a else if (proto_version == PY_SSL_VERSION_SSL3)
2620n/a ctx = SSL_CTX_new(SSLv3_method());
2621n/a#endif
2622n/a#ifndef OPENSSL_NO_SSL2
2623n/a else if (proto_version == PY_SSL_VERSION_SSL2)
2624n/a ctx = SSL_CTX_new(SSLv2_method());
2625n/a#endif
2626n/a else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
2627n/a ctx = SSL_CTX_new(TLS_method());
2628n/a else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2629n/a ctx = SSL_CTX_new(TLS_client_method());
2630n/a else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2631n/a ctx = SSL_CTX_new(TLS_server_method());
2632n/a else
2633n/a proto_version = -1;
2634n/a PySSL_END_ALLOW_THREADS
2635n/a
2636n/a if (proto_version == -1) {
2637n/a PyErr_SetString(PyExc_ValueError,
2638n/a "invalid protocol version");
2639n/a return NULL;
2640n/a }
2641n/a if (ctx == NULL) {
2642n/a PyErr_SetString(PySSLErrorObject,
2643n/a "failed to allocate SSL context");
2644n/a return NULL;
2645n/a }
2646n/a
2647n/a assert(type != NULL && type->tp_alloc != NULL);
2648n/a self = (PySSLContext *) type->tp_alloc(type, 0);
2649n/a if (self == NULL) {
2650n/a SSL_CTX_free(ctx);
2651n/a return NULL;
2652n/a }
2653n/a self->ctx = ctx;
2654n/a#ifdef OPENSSL_NPN_NEGOTIATED
2655n/a self->npn_protocols = NULL;
2656n/a#endif
2657n/a#ifdef HAVE_ALPN
2658n/a self->alpn_protocols = NULL;
2659n/a#endif
2660n/a#ifndef OPENSSL_NO_TLSEXT
2661n/a self->set_hostname = NULL;
2662n/a#endif
2663n/a /* Don't check host name by default */
2664n/a if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2665n/a self->check_hostname = 1;
2666n/a if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2667n/a Py_DECREF(self);
2668n/a return NULL;
2669n/a }
2670n/a } else {
2671n/a self->check_hostname = 0;
2672n/a if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2673n/a Py_DECREF(self);
2674n/a return NULL;
2675n/a }
2676n/a }
2677n/a /* Defaults */
2678n/a options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2679n/a if (proto_version != PY_SSL_VERSION_SSL2)
2680n/a options |= SSL_OP_NO_SSLv2;
2681n/a if (proto_version != PY_SSL_VERSION_SSL3)
2682n/a options |= SSL_OP_NO_SSLv3;
2683n/a /* Minimal security flags for server and client side context.
2684n/a * Client sockets ignore server-side parameters. */
2685n/a#ifdef SSL_OP_NO_COMPRESSION
2686n/a options |= SSL_OP_NO_COMPRESSION;
2687n/a#endif
2688n/a#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2689n/a options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2690n/a#endif
2691n/a#ifdef SSL_OP_SINGLE_DH_USE
2692n/a options |= SSL_OP_SINGLE_DH_USE;
2693n/a#endif
2694n/a#ifdef SSL_OP_SINGLE_ECDH_USE
2695n/a options |= SSL_OP_SINGLE_ECDH_USE;
2696n/a#endif
2697n/a SSL_CTX_set_options(self->ctx, options);
2698n/a
2699n/a /* A bare minimum cipher list without completly broken cipher suites.
2700n/a * It's far from perfect but gives users a better head start. */
2701n/a if (proto_version != PY_SSL_VERSION_SSL2) {
2702n/a result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2703n/a } else {
2704n/a /* SSLv2 needs MD5 */
2705n/a result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2706n/a }
2707n/a if (result == 0) {
2708n/a Py_DECREF(self);
2709n/a ERR_clear_error();
2710n/a PyErr_SetString(PySSLErrorObject,
2711n/a "No cipher can be selected.");
2712n/a return NULL;
2713n/a }
2714n/a
2715n/a#if defined(SSL_MODE_RELEASE_BUFFERS)
2716n/a /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2717n/a usage for no cost at all. However, don't do this for OpenSSL versions
2718n/a between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2719n/a 2014-0198. I can't find exactly which beta fixed this CVE, so be
2720n/a conservative and assume it wasn't fixed until release. We do this check
2721n/a at runtime to avoid problems from the dynamic linker.
2722n/a See #25672 for more on this. */
2723n/a libver = SSLeay();
2724n/a if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2725n/a !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2726n/a SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2727n/a }
2728n/a#endif
2729n/a
2730n/a
2731n/a#ifndef OPENSSL_NO_ECDH
2732n/a /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2733n/a prime256v1 by default. This is Apache mod_ssl's initialization
2734n/a policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2735n/a */
2736n/a#if defined(SSL_CTX_set_ecdh_auto) && !defined(OPENSSL_VERSION_1_1)
2737n/a SSL_CTX_set_ecdh_auto(self->ctx, 1);
2738n/a#else
2739n/a {
2740n/a EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2741n/a SSL_CTX_set_tmp_ecdh(self->ctx, key);
2742n/a EC_KEY_free(key);
2743n/a }
2744n/a#endif
2745n/a#endif
2746n/a
2747n/a#define SID_CTX "Python"
2748n/a SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2749n/a sizeof(SID_CTX));
2750n/a#undef SID_CTX
2751n/a
2752n/a#ifdef X509_V_FLAG_TRUSTED_FIRST
2753n/a {
2754n/a /* Improve trust chain building when cross-signed intermediate
2755n/a certificates are present. See https://bugs.python.org/issue23476. */
2756n/a X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2757n/a X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2758n/a }
2759n/a#endif
2760n/a
2761n/a return (PyObject *)self;
2762n/a}
2763n/a
2764n/astatic int
2765n/acontext_traverse(PySSLContext *self, visitproc visit, void *arg)
2766n/a{
2767n/a#ifndef OPENSSL_NO_TLSEXT
2768n/a Py_VISIT(self->set_hostname);
2769n/a#endif
2770n/a return 0;
2771n/a}
2772n/a
2773n/astatic int
2774n/acontext_clear(PySSLContext *self)
2775n/a{
2776n/a#ifndef OPENSSL_NO_TLSEXT
2777n/a Py_CLEAR(self->set_hostname);
2778n/a#endif
2779n/a return 0;
2780n/a}
2781n/a
2782n/astatic void
2783n/acontext_dealloc(PySSLContext *self)
2784n/a{
2785n/a context_clear(self);
2786n/a SSL_CTX_free(self->ctx);
2787n/a#ifdef OPENSSL_NPN_NEGOTIATED
2788n/a PyMem_FREE(self->npn_protocols);
2789n/a#endif
2790n/a#ifdef HAVE_ALPN
2791n/a PyMem_FREE(self->alpn_protocols);
2792n/a#endif
2793n/a Py_TYPE(self)->tp_free(self);
2794n/a}
2795n/a
2796n/a/*[clinic input]
2797n/a_ssl._SSLContext.set_ciphers
2798n/a cipherlist: str
2799n/a /
2800n/a[clinic start generated code]*/
2801n/a
2802n/astatic PyObject *
2803n/a_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2804n/a/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2805n/a{
2806n/a int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2807n/a if (ret == 0) {
2808n/a /* Clearing the error queue is necessary on some OpenSSL versions,
2809n/a otherwise the error will be reported again when another SSL call
2810n/a is done. */
2811n/a ERR_clear_error();
2812n/a PyErr_SetString(PySSLErrorObject,
2813n/a "No cipher can be selected.");
2814n/a return NULL;
2815n/a }
2816n/a Py_RETURN_NONE;
2817n/a}
2818n/a
2819n/a#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2820n/a/*[clinic input]
2821n/a_ssl._SSLContext.get_ciphers
2822n/a[clinic start generated code]*/
2823n/a
2824n/astatic PyObject *
2825n/a_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2826n/a/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2827n/a{
2828n/a SSL *ssl = NULL;
2829n/a STACK_OF(SSL_CIPHER) *sk = NULL;
2830n/a const SSL_CIPHER *cipher;
2831n/a int i=0;
2832n/a PyObject *result = NULL, *dct;
2833n/a
2834n/a ssl = SSL_new(self->ctx);
2835n/a if (ssl == NULL) {
2836n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
2837n/a goto exit;
2838n/a }
2839n/a sk = SSL_get_ciphers(ssl);
2840n/a
2841n/a result = PyList_New(sk_SSL_CIPHER_num(sk));
2842n/a if (result == NULL) {
2843n/a goto exit;
2844n/a }
2845n/a
2846n/a for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2847n/a cipher = sk_SSL_CIPHER_value(sk, i);
2848n/a dct = cipher_to_dict(cipher);
2849n/a if (dct == NULL) {
2850n/a Py_CLEAR(result);
2851n/a goto exit;
2852n/a }
2853n/a PyList_SET_ITEM(result, i, dct);
2854n/a }
2855n/a
2856n/a exit:
2857n/a if (ssl != NULL)
2858n/a SSL_free(ssl);
2859n/a return result;
2860n/a
2861n/a}
2862n/a#endif
2863n/a
2864n/a
2865n/a#ifdef OPENSSL_NPN_NEGOTIATED
2866n/astatic int
2867n/ado_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2868n/a const unsigned char *server_protocols, unsigned int server_protocols_len,
2869n/a const unsigned char *client_protocols, unsigned int client_protocols_len)
2870n/a{
2871n/a int ret;
2872n/a if (client_protocols == NULL) {
2873n/a client_protocols = (unsigned char *)"";
2874n/a client_protocols_len = 0;
2875n/a }
2876n/a if (server_protocols == NULL) {
2877n/a server_protocols = (unsigned char *)"";
2878n/a server_protocols_len = 0;
2879n/a }
2880n/a
2881n/a ret = SSL_select_next_proto(out, outlen,
2882n/a server_protocols, server_protocols_len,
2883n/a client_protocols, client_protocols_len);
2884n/a if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2885n/a return SSL_TLSEXT_ERR_NOACK;
2886n/a
2887n/a return SSL_TLSEXT_ERR_OK;
2888n/a}
2889n/a
2890n/a/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2891n/astatic int
2892n/a_advertiseNPN_cb(SSL *s,
2893n/a const unsigned char **data, unsigned int *len,
2894n/a void *args)
2895n/a{
2896n/a PySSLContext *ssl_ctx = (PySSLContext *) args;
2897n/a
2898n/a if (ssl_ctx->npn_protocols == NULL) {
2899n/a *data = (unsigned char *)"";
2900n/a *len = 0;
2901n/a } else {
2902n/a *data = ssl_ctx->npn_protocols;
2903n/a *len = ssl_ctx->npn_protocols_len;
2904n/a }
2905n/a
2906n/a return SSL_TLSEXT_ERR_OK;
2907n/a}
2908n/a/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2909n/astatic int
2910n/a_selectNPN_cb(SSL *s,
2911n/a unsigned char **out, unsigned char *outlen,
2912n/a const unsigned char *server, unsigned int server_len,
2913n/a void *args)
2914n/a{
2915n/a PySSLContext *ctx = (PySSLContext *)args;
2916n/a return do_protocol_selection(0, out, outlen, server, server_len,
2917n/a ctx->npn_protocols, ctx->npn_protocols_len);
2918n/a}
2919n/a#endif
2920n/a
2921n/a/*[clinic input]
2922n/a_ssl._SSLContext._set_npn_protocols
2923n/a protos: Py_buffer
2924n/a /
2925n/a[clinic start generated code]*/
2926n/a
2927n/astatic PyObject *
2928n/a_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2929n/a Py_buffer *protos)
2930n/a/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
2931n/a{
2932n/a#ifdef OPENSSL_NPN_NEGOTIATED
2933n/a PyMem_Free(self->npn_protocols);
2934n/a self->npn_protocols = PyMem_Malloc(protos->len);
2935n/a if (self->npn_protocols == NULL)
2936n/a return PyErr_NoMemory();
2937n/a memcpy(self->npn_protocols, protos->buf, protos->len);
2938n/a self->npn_protocols_len = (int) protos->len;
2939n/a
2940n/a /* set both server and client callbacks, because the context can
2941n/a * be used to create both types of sockets */
2942n/a SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2943n/a _advertiseNPN_cb,
2944n/a self);
2945n/a SSL_CTX_set_next_proto_select_cb(self->ctx,
2946n/a _selectNPN_cb,
2947n/a self);
2948n/a
2949n/a Py_RETURN_NONE;
2950n/a#else
2951n/a PyErr_SetString(PyExc_NotImplementedError,
2952n/a "The NPN extension requires OpenSSL 1.0.1 or later.");
2953n/a return NULL;
2954n/a#endif
2955n/a}
2956n/a
2957n/a#ifdef HAVE_ALPN
2958n/astatic int
2959n/a_selectALPN_cb(SSL *s,
2960n/a const unsigned char **out, unsigned char *outlen,
2961n/a const unsigned char *client_protocols, unsigned int client_protocols_len,
2962n/a void *args)
2963n/a{
2964n/a PySSLContext *ctx = (PySSLContext *)args;
2965n/a return do_protocol_selection(1, (unsigned char **)out, outlen,
2966n/a ctx->alpn_protocols, ctx->alpn_protocols_len,
2967n/a client_protocols, client_protocols_len);
2968n/a}
2969n/a#endif
2970n/a
2971n/a/*[clinic input]
2972n/a_ssl._SSLContext._set_alpn_protocols
2973n/a protos: Py_buffer
2974n/a /
2975n/a[clinic start generated code]*/
2976n/a
2977n/astatic PyObject *
2978n/a_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2979n/a Py_buffer *protos)
2980n/a/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
2981n/a{
2982n/a#ifdef HAVE_ALPN
2983n/a PyMem_FREE(self->alpn_protocols);
2984n/a self->alpn_protocols = PyMem_Malloc(protos->len);
2985n/a if (!self->alpn_protocols)
2986n/a return PyErr_NoMemory();
2987n/a memcpy(self->alpn_protocols, protos->buf, protos->len);
2988n/a self->alpn_protocols_len = protos->len;
2989n/a
2990n/a if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2991n/a return PyErr_NoMemory();
2992n/a SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2993n/a
2994n/a Py_RETURN_NONE;
2995n/a#else
2996n/a PyErr_SetString(PyExc_NotImplementedError,
2997n/a "The ALPN extension requires OpenSSL 1.0.2 or later.");
2998n/a return NULL;
2999n/a#endif
3000n/a}
3001n/a
3002n/astatic PyObject *
3003n/aget_verify_mode(PySSLContext *self, void *c)
3004n/a{
3005n/a switch (SSL_CTX_get_verify_mode(self->ctx)) {
3006n/a case SSL_VERIFY_NONE:
3007n/a return PyLong_FromLong(PY_SSL_CERT_NONE);
3008n/a case SSL_VERIFY_PEER:
3009n/a return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3010n/a case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3011n/a return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3012n/a }
3013n/a PyErr_SetString(PySSLErrorObject,
3014n/a "invalid return value from SSL_CTX_get_verify_mode");
3015n/a return NULL;
3016n/a}
3017n/a
3018n/astatic int
3019n/aset_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3020n/a{
3021n/a int n;
3022n/a if (!PyArg_Parse(arg, "i", &n))
3023n/a return -1;
3024n/a if (n == PY_SSL_CERT_NONE && self->check_hostname) {
3025n/a PyErr_SetString(PyExc_ValueError,
3026n/a "Cannot set verify_mode to CERT_NONE when "
3027n/a "check_hostname is enabled.");
3028n/a return -1;
3029n/a }
3030n/a return _set_verify_mode(self->ctx, n);
3031n/a}
3032n/a
3033n/astatic PyObject *
3034n/aget_verify_flags(PySSLContext *self, void *c)
3035n/a{
3036n/a X509_STORE *store;
3037n/a X509_VERIFY_PARAM *param;
3038n/a unsigned long flags;
3039n/a
3040n/a store = SSL_CTX_get_cert_store(self->ctx);
3041n/a param = X509_STORE_get0_param(store);
3042n/a flags = X509_VERIFY_PARAM_get_flags(param);
3043n/a return PyLong_FromUnsignedLong(flags);
3044n/a}
3045n/a
3046n/astatic int
3047n/aset_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3048n/a{
3049n/a X509_STORE *store;
3050n/a X509_VERIFY_PARAM *param;
3051n/a unsigned long new_flags, flags, set, clear;
3052n/a
3053n/a if (!PyArg_Parse(arg, "k", &new_flags))
3054n/a return -1;
3055n/a store = SSL_CTX_get_cert_store(self->ctx);
3056n/a param = X509_STORE_get0_param(store);
3057n/a flags = X509_VERIFY_PARAM_get_flags(param);
3058n/a clear = flags & ~new_flags;
3059n/a set = ~flags & new_flags;
3060n/a if (clear) {
3061n/a if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
3062n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
3063n/a return -1;
3064n/a }
3065n/a }
3066n/a if (set) {
3067n/a if (!X509_VERIFY_PARAM_set_flags(param, set)) {
3068n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
3069n/a return -1;
3070n/a }
3071n/a }
3072n/a return 0;
3073n/a}
3074n/a
3075n/astatic PyObject *
3076n/aget_options(PySSLContext *self, void *c)
3077n/a{
3078n/a return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3079n/a}
3080n/a
3081n/astatic int
3082n/aset_options(PySSLContext *self, PyObject *arg, void *c)
3083n/a{
3084n/a long new_opts, opts, set, clear;
3085n/a if (!PyArg_Parse(arg, "l", &new_opts))
3086n/a return -1;
3087n/a opts = SSL_CTX_get_options(self->ctx);
3088n/a clear = opts & ~new_opts;
3089n/a set = ~opts & new_opts;
3090n/a if (clear) {
3091n/a#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3092n/a SSL_CTX_clear_options(self->ctx, clear);
3093n/a#else
3094n/a PyErr_SetString(PyExc_ValueError,
3095n/a "can't clear options before OpenSSL 0.9.8m");
3096n/a return -1;
3097n/a#endif
3098n/a }
3099n/a if (set)
3100n/a SSL_CTX_set_options(self->ctx, set);
3101n/a return 0;
3102n/a}
3103n/a
3104n/astatic PyObject *
3105n/aget_check_hostname(PySSLContext *self, void *c)
3106n/a{
3107n/a return PyBool_FromLong(self->check_hostname);
3108n/a}
3109n/a
3110n/astatic int
3111n/aset_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3112n/a{
3113n/a int check_hostname;
3114n/a if (!PyArg_Parse(arg, "p", &check_hostname))
3115n/a return -1;
3116n/a if (check_hostname &&
3117n/a SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3118n/a PyErr_SetString(PyExc_ValueError,
3119n/a "check_hostname needs a SSL context with either "
3120n/a "CERT_OPTIONAL or CERT_REQUIRED");
3121n/a return -1;
3122n/a }
3123n/a self->check_hostname = check_hostname;
3124n/a return 0;
3125n/a}
3126n/a
3127n/a
3128n/atypedef struct {
3129n/a PyThreadState *thread_state;
3130n/a PyObject *callable;
3131n/a char *password;
3132n/a int size;
3133n/a int error;
3134n/a} _PySSLPasswordInfo;
3135n/a
3136n/astatic int
3137n/a_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3138n/a const char *bad_type_error)
3139n/a{
3140n/a /* Set the password and size fields of a _PySSLPasswordInfo struct
3141n/a from a unicode, bytes, or byte array object.
3142n/a The password field will be dynamically allocated and must be freed
3143n/a by the caller */
3144n/a PyObject *password_bytes = NULL;
3145n/a const char *data = NULL;
3146n/a Py_ssize_t size;
3147n/a
3148n/a if (PyUnicode_Check(password)) {
3149n/a password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3150n/a if (!password_bytes) {
3151n/a goto error;
3152n/a }
3153n/a data = PyBytes_AS_STRING(password_bytes);
3154n/a size = PyBytes_GET_SIZE(password_bytes);
3155n/a } else if (PyBytes_Check(password)) {
3156n/a data = PyBytes_AS_STRING(password);
3157n/a size = PyBytes_GET_SIZE(password);
3158n/a } else if (PyByteArray_Check(password)) {
3159n/a data = PyByteArray_AS_STRING(password);
3160n/a size = PyByteArray_GET_SIZE(password);
3161n/a } else {
3162n/a PyErr_SetString(PyExc_TypeError, bad_type_error);
3163n/a goto error;
3164n/a }
3165n/a
3166n/a if (size > (Py_ssize_t)INT_MAX) {
3167n/a PyErr_Format(PyExc_ValueError,
3168n/a "password cannot be longer than %d bytes", INT_MAX);
3169n/a goto error;
3170n/a }
3171n/a
3172n/a PyMem_Free(pw_info->password);
3173n/a pw_info->password = PyMem_Malloc(size);
3174n/a if (!pw_info->password) {
3175n/a PyErr_SetString(PyExc_MemoryError,
3176n/a "unable to allocate password buffer");
3177n/a goto error;
3178n/a }
3179n/a memcpy(pw_info->password, data, size);
3180n/a pw_info->size = (int)size;
3181n/a
3182n/a Py_XDECREF(password_bytes);
3183n/a return 1;
3184n/a
3185n/aerror:
3186n/a Py_XDECREF(password_bytes);
3187n/a return 0;
3188n/a}
3189n/a
3190n/astatic int
3191n/a_password_callback(char *buf, int size, int rwflag, void *userdata)
3192n/a{
3193n/a _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3194n/a PyObject *fn_ret = NULL;
3195n/a
3196n/a PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3197n/a
3198n/a if (pw_info->callable) {
3199n/a fn_ret = _PyObject_CallNoArg(pw_info->callable);
3200n/a if (!fn_ret) {
3201n/a /* TODO: It would be nice to move _ctypes_add_traceback() into the
3202n/a core python API, so we could use it to add a frame here */
3203n/a goto error;
3204n/a }
3205n/a
3206n/a if (!_pwinfo_set(pw_info, fn_ret,
3207n/a "password callback must return a string")) {
3208n/a goto error;
3209n/a }
3210n/a Py_CLEAR(fn_ret);
3211n/a }
3212n/a
3213n/a if (pw_info->size > size) {
3214n/a PyErr_Format(PyExc_ValueError,
3215n/a "password cannot be longer than %d bytes", size);
3216n/a goto error;
3217n/a }
3218n/a
3219n/a PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3220n/a memcpy(buf, pw_info->password, pw_info->size);
3221n/a return pw_info->size;
3222n/a
3223n/aerror:
3224n/a Py_XDECREF(fn_ret);
3225n/a PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3226n/a pw_info->error = 1;
3227n/a return -1;
3228n/a}
3229n/a
3230n/a/*[clinic input]
3231n/a_ssl._SSLContext.load_cert_chain
3232n/a certfile: object
3233n/a keyfile: object = NULL
3234n/a password: object = NULL
3235n/a
3236n/a[clinic start generated code]*/
3237n/a
3238n/astatic PyObject *
3239n/a_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3240n/a PyObject *keyfile, PyObject *password)
3241n/a/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
3242n/a{
3243n/a PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
3244n/a pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3245n/a void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
3246n/a _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
3247n/a int r;
3248n/a
3249n/a errno = 0;
3250n/a ERR_clear_error();
3251n/a if (keyfile == Py_None)
3252n/a keyfile = NULL;
3253n/a if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3254n/a PyErr_SetString(PyExc_TypeError,
3255n/a "certfile should be a valid filesystem path");
3256n/a return NULL;
3257n/a }
3258n/a if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3259n/a PyErr_SetString(PyExc_TypeError,
3260n/a "keyfile should be a valid filesystem path");
3261n/a goto error;
3262n/a }
3263n/a if (password && password != Py_None) {
3264n/a if (PyCallable_Check(password)) {
3265n/a pw_info.callable = password;
3266n/a } else if (!_pwinfo_set(&pw_info, password,
3267n/a "password should be a string or callable")) {
3268n/a goto error;
3269n/a }
3270n/a SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3271n/a SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3272n/a }
3273n/a PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
3274n/a r = SSL_CTX_use_certificate_chain_file(self->ctx,
3275n/a PyBytes_AS_STRING(certfile_bytes));
3276n/a PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3277n/a if (r != 1) {
3278n/a if (pw_info.error) {
3279n/a ERR_clear_error();
3280n/a /* the password callback has already set the error information */
3281n/a }
3282n/a else if (errno != 0) {
3283n/a ERR_clear_error();
3284n/a PyErr_SetFromErrno(PyExc_IOError);
3285n/a }
3286n/a else {
3287n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
3288n/a }
3289n/a goto error;
3290n/a }
3291n/a PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
3292n/a r = SSL_CTX_use_PrivateKey_file(self->ctx,
3293n/a PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3294n/a SSL_FILETYPE_PEM);
3295n/a PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3296n/a Py_CLEAR(keyfile_bytes);
3297n/a Py_CLEAR(certfile_bytes);
3298n/a if (r != 1) {
3299n/a if (pw_info.error) {
3300n/a ERR_clear_error();
3301n/a /* the password callback has already set the error information */
3302n/a }
3303n/a else if (errno != 0) {
3304n/a ERR_clear_error();
3305n/a PyErr_SetFromErrno(PyExc_IOError);
3306n/a }
3307n/a else {
3308n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
3309n/a }
3310n/a goto error;
3311n/a }
3312n/a PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
3313n/a r = SSL_CTX_check_private_key(self->ctx);
3314n/a PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3315n/a if (r != 1) {
3316n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
3317n/a goto error;
3318n/a }
3319n/a SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3320n/a SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
3321n/a PyMem_Free(pw_info.password);
3322n/a Py_RETURN_NONE;
3323n/a
3324n/aerror:
3325n/a SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3326n/a SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
3327n/a PyMem_Free(pw_info.password);
3328n/a Py_XDECREF(keyfile_bytes);
3329n/a Py_XDECREF(certfile_bytes);
3330n/a return NULL;
3331n/a}
3332n/a
3333n/a/* internal helper function, returns -1 on error
3334n/a */
3335n/astatic int
3336n/a_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3337n/a int filetype)
3338n/a{
3339n/a BIO *biobuf = NULL;
3340n/a X509_STORE *store;
3341n/a int retval = 0, err, loaded = 0;
3342n/a
3343n/a assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3344n/a
3345n/a if (len <= 0) {
3346n/a PyErr_SetString(PyExc_ValueError,
3347n/a "Empty certificate data");
3348n/a return -1;
3349n/a } else if (len > INT_MAX) {
3350n/a PyErr_SetString(PyExc_OverflowError,
3351n/a "Certificate data is too long.");
3352n/a return -1;
3353n/a }
3354n/a
3355n/a biobuf = BIO_new_mem_buf(data, (int)len);
3356n/a if (biobuf == NULL) {
3357n/a _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3358n/a return -1;
3359n/a }
3360n/a
3361n/a store = SSL_CTX_get_cert_store(self->ctx);
3362n/a assert(store != NULL);
3363n/a
3364n/a while (1) {
3365n/a X509 *cert = NULL;
3366n/a int r;
3367n/a
3368n/a if (filetype == SSL_FILETYPE_ASN1) {
3369n/a cert = d2i_X509_bio(biobuf, NULL);
3370n/a } else {
3371n/a cert = PEM_read_bio_X509(biobuf, NULL,
3372n/a SSL_CTX_get_default_passwd_cb(self->ctx),
3373n/a SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3374n/a );
3375n/a }
3376n/a if (cert == NULL) {
3377n/a break;
3378n/a }
3379n/a r = X509_STORE_add_cert(store, cert);
3380n/a X509_free(cert);
3381n/a if (!r) {
3382n/a err = ERR_peek_last_error();
3383n/a if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3384n/a (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3385n/a /* cert already in hash table, not an error */
3386n/a ERR_clear_error();
3387n/a } else {
3388n/a break;
3389n/a }
3390n/a }
3391n/a loaded++;
3392n/a }
3393n/a
3394n/a err = ERR_peek_last_error();
3395n/a if ((filetype == SSL_FILETYPE_ASN1) &&
3396n/a (loaded > 0) &&
3397n/a (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3398n/a (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3399n/a /* EOF ASN1 file, not an error */
3400n/a ERR_clear_error();
3401n/a retval = 0;
3402n/a } else if ((filetype == SSL_FILETYPE_PEM) &&
3403n/a (loaded > 0) &&
3404n/a (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3405n/a (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3406n/a /* EOF PEM file, not an error */
3407n/a ERR_clear_error();
3408n/a retval = 0;
3409n/a } else {
3410n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
3411n/a retval = -1;
3412n/a }
3413n/a
3414n/a BIO_free(biobuf);
3415n/a return retval;
3416n/a}
3417n/a
3418n/a
3419n/a/*[clinic input]
3420n/a_ssl._SSLContext.load_verify_locations
3421n/a cafile: object = NULL
3422n/a capath: object = NULL
3423n/a cadata: object = NULL
3424n/a
3425n/a[clinic start generated code]*/
3426n/a
3427n/astatic PyObject *
3428n/a_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3429n/a PyObject *cafile,
3430n/a PyObject *capath,
3431n/a PyObject *cadata)
3432n/a/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
3433n/a{
3434n/a PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3435n/a const char *cafile_buf = NULL, *capath_buf = NULL;
3436n/a int r = 0, ok = 1;
3437n/a
3438n/a errno = 0;
3439n/a if (cafile == Py_None)
3440n/a cafile = NULL;
3441n/a if (capath == Py_None)
3442n/a capath = NULL;
3443n/a if (cadata == Py_None)
3444n/a cadata = NULL;
3445n/a
3446n/a if (cafile == NULL && capath == NULL && cadata == NULL) {
3447n/a PyErr_SetString(PyExc_TypeError,
3448n/a "cafile, capath and cadata cannot be all omitted");
3449n/a goto error;
3450n/a }
3451n/a if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3452n/a PyErr_SetString(PyExc_TypeError,
3453n/a "cafile should be a valid filesystem path");
3454n/a goto error;
3455n/a }
3456n/a if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
3457n/a PyErr_SetString(PyExc_TypeError,
3458n/a "capath should be a valid filesystem path");
3459n/a goto error;
3460n/a }
3461n/a
3462n/a /* validata cadata type and load cadata */
3463n/a if (cadata) {
3464n/a Py_buffer buf;
3465n/a PyObject *cadata_ascii = NULL;
3466n/a
3467n/a if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3468n/a if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3469n/a PyBuffer_Release(&buf);
3470n/a PyErr_SetString(PyExc_TypeError,
3471n/a "cadata should be a contiguous buffer with "
3472n/a "a single dimension");
3473n/a goto error;
3474n/a }
3475n/a r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3476n/a PyBuffer_Release(&buf);
3477n/a if (r == -1) {
3478n/a goto error;
3479n/a }
3480n/a } else {
3481n/a PyErr_Clear();
3482n/a cadata_ascii = PyUnicode_AsASCIIString(cadata);
3483n/a if (cadata_ascii == NULL) {
3484n/a PyErr_SetString(PyExc_TypeError,
3485n/a "cadata should be an ASCII string or a "
3486n/a "bytes-like object");
3487n/a goto error;
3488n/a }
3489n/a r = _add_ca_certs(self,
3490n/a PyBytes_AS_STRING(cadata_ascii),
3491n/a PyBytes_GET_SIZE(cadata_ascii),
3492n/a SSL_FILETYPE_PEM);
3493n/a Py_DECREF(cadata_ascii);
3494n/a if (r == -1) {
3495n/a goto error;
3496n/a }
3497n/a }
3498n/a }
3499n/a
3500n/a /* load cafile or capath */
3501n/a if (cafile || capath) {
3502n/a if (cafile)
3503n/a cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3504n/a if (capath)
3505n/a capath_buf = PyBytes_AS_STRING(capath_bytes);
3506n/a PySSL_BEGIN_ALLOW_THREADS
3507n/a r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3508n/a PySSL_END_ALLOW_THREADS
3509n/a if (r != 1) {
3510n/a ok = 0;
3511n/a if (errno != 0) {
3512n/a ERR_clear_error();
3513n/a PyErr_SetFromErrno(PyExc_IOError);
3514n/a }
3515n/a else {
3516n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
3517n/a }
3518n/a goto error;
3519n/a }
3520n/a }
3521n/a goto end;
3522n/a
3523n/a error:
3524n/a ok = 0;
3525n/a end:
3526n/a Py_XDECREF(cafile_bytes);
3527n/a Py_XDECREF(capath_bytes);
3528n/a if (ok) {
3529n/a Py_RETURN_NONE;
3530n/a } else {
3531n/a return NULL;
3532n/a }
3533n/a}
3534n/a
3535n/a/*[clinic input]
3536n/a_ssl._SSLContext.load_dh_params
3537n/a path as filepath: object
3538n/a /
3539n/a
3540n/a[clinic start generated code]*/
3541n/a
3542n/astatic PyObject *
3543n/a_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3544n/a/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
3545n/a{
3546n/a FILE *f;
3547n/a DH *dh;
3548n/a
3549n/a f = _Py_fopen_obj(filepath, "rb");
3550n/a if (f == NULL)
3551n/a return NULL;
3552n/a
3553n/a errno = 0;
3554n/a PySSL_BEGIN_ALLOW_THREADS
3555n/a dh = PEM_read_DHparams(f, NULL, NULL, NULL);
3556n/a fclose(f);
3557n/a PySSL_END_ALLOW_THREADS
3558n/a if (dh == NULL) {
3559n/a if (errno != 0) {
3560n/a ERR_clear_error();
3561n/a PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3562n/a }
3563n/a else {
3564n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
3565n/a }
3566n/a return NULL;
3567n/a }
3568n/a if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3569n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
3570n/a DH_free(dh);
3571n/a Py_RETURN_NONE;
3572n/a}
3573n/a
3574n/a/*[clinic input]
3575n/a_ssl._SSLContext._wrap_socket
3576n/a sock: object(subclass_of="PySocketModule.Sock_Type")
3577n/a server_side: int
3578n/a server_hostname as hostname_obj: object = None
3579n/a
3580n/a[clinic start generated code]*/
3581n/a
3582n/astatic PyObject *
3583n/a_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3584n/a int server_side, PyObject *hostname_obj)
3585n/a/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
3586n/a{
3587n/a char *hostname = NULL;
3588n/a PyObject *res;
3589n/a
3590n/a /* server_hostname is either None (or absent), or to be encoded
3591n/a using the idna encoding. */
3592n/a if (hostname_obj != Py_None) {
3593n/a if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3594n/a return NULL;
3595n/a }
3596n/a
3597n/a res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3598n/a server_side, hostname,
3599n/a NULL, NULL);
3600n/a if (hostname != NULL)
3601n/a PyMem_Free(hostname);
3602n/a return res;
3603n/a}
3604n/a
3605n/a/*[clinic input]
3606n/a_ssl._SSLContext._wrap_bio
3607n/a incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3608n/a outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3609n/a server_side: int
3610n/a server_hostname as hostname_obj: object = None
3611n/a
3612n/a[clinic start generated code]*/
3613n/a
3614n/astatic PyObject *
3615n/a_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3616n/a PySSLMemoryBIO *outgoing, int server_side,
3617n/a PyObject *hostname_obj)
3618n/a/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
3619n/a{
3620n/a char *hostname = NULL;
3621n/a PyObject *res;
3622n/a
3623n/a /* server_hostname is either None (or absent), or to be encoded
3624n/a using the idna encoding. */
3625n/a if (hostname_obj != Py_None) {
3626n/a if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3627n/a return NULL;
3628n/a }
3629n/a
3630n/a res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3631n/a incoming, outgoing);
3632n/a
3633n/a PyMem_Free(hostname);
3634n/a return res;
3635n/a}
3636n/a
3637n/a/*[clinic input]
3638n/a_ssl._SSLContext.session_stats
3639n/a[clinic start generated code]*/
3640n/a
3641n/astatic PyObject *
3642n/a_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3643n/a/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
3644n/a{
3645n/a int r;
3646n/a PyObject *value, *stats = PyDict_New();
3647n/a if (!stats)
3648n/a return NULL;
3649n/a
3650n/a#define ADD_STATS(SSL_NAME, KEY_NAME) \
3651n/a value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3652n/a if (value == NULL) \
3653n/a goto error; \
3654n/a r = PyDict_SetItemString(stats, KEY_NAME, value); \
3655n/a Py_DECREF(value); \
3656n/a if (r < 0) \
3657n/a goto error;
3658n/a
3659n/a ADD_STATS(number, "number");
3660n/a ADD_STATS(connect, "connect");
3661n/a ADD_STATS(connect_good, "connect_good");
3662n/a ADD_STATS(connect_renegotiate, "connect_renegotiate");
3663n/a ADD_STATS(accept, "accept");
3664n/a ADD_STATS(accept_good, "accept_good");
3665n/a ADD_STATS(accept_renegotiate, "accept_renegotiate");
3666n/a ADD_STATS(accept, "accept");
3667n/a ADD_STATS(hits, "hits");
3668n/a ADD_STATS(misses, "misses");
3669n/a ADD_STATS(timeouts, "timeouts");
3670n/a ADD_STATS(cache_full, "cache_full");
3671n/a
3672n/a#undef ADD_STATS
3673n/a
3674n/a return stats;
3675n/a
3676n/aerror:
3677n/a Py_DECREF(stats);
3678n/a return NULL;
3679n/a}
3680n/a
3681n/a/*[clinic input]
3682n/a_ssl._SSLContext.set_default_verify_paths
3683n/a[clinic start generated code]*/
3684n/a
3685n/astatic PyObject *
3686n/a_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3687n/a/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
3688n/a{
3689n/a if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3690n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
3691n/a return NULL;
3692n/a }
3693n/a Py_RETURN_NONE;
3694n/a}
3695n/a
3696n/a#ifndef OPENSSL_NO_ECDH
3697n/a/*[clinic input]
3698n/a_ssl._SSLContext.set_ecdh_curve
3699n/a name: object
3700n/a /
3701n/a
3702n/a[clinic start generated code]*/
3703n/a
3704n/astatic PyObject *
3705n/a_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3706n/a/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
3707n/a{
3708n/a PyObject *name_bytes;
3709n/a int nid;
3710n/a EC_KEY *key;
3711n/a
3712n/a if (!PyUnicode_FSConverter(name, &name_bytes))
3713n/a return NULL;
3714n/a assert(PyBytes_Check(name_bytes));
3715n/a nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3716n/a Py_DECREF(name_bytes);
3717n/a if (nid == 0) {
3718n/a PyErr_Format(PyExc_ValueError,
3719n/a "unknown elliptic curve name %R", name);
3720n/a return NULL;
3721n/a }
3722n/a key = EC_KEY_new_by_curve_name(nid);
3723n/a if (key == NULL) {
3724n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
3725n/a return NULL;
3726n/a }
3727n/a SSL_CTX_set_tmp_ecdh(self->ctx, key);
3728n/a EC_KEY_free(key);
3729n/a Py_RETURN_NONE;
3730n/a}
3731n/a#endif
3732n/a
3733n/a#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3734n/astatic int
3735n/a_servername_callback(SSL *s, int *al, void *args)
3736n/a{
3737n/a int ret;
3738n/a PySSLContext *ssl_ctx = (PySSLContext *) args;
3739n/a PySSLSocket *ssl;
3740n/a PyObject *servername_o;
3741n/a PyObject *servername_idna;
3742n/a PyObject *result;
3743n/a /* The high-level ssl.SSLSocket object */
3744n/a PyObject *ssl_socket;
3745n/a const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
3746n/a#ifdef WITH_THREAD
3747n/a PyGILState_STATE gstate = PyGILState_Ensure();
3748n/a#endif
3749n/a
3750n/a if (ssl_ctx->set_hostname == NULL) {
3751n/a /* remove race condition in this the call back while if removing the
3752n/a * callback is in progress */
3753n/a#ifdef WITH_THREAD
3754n/a PyGILState_Release(gstate);
3755n/a#endif
3756n/a return SSL_TLSEXT_ERR_OK;
3757n/a }
3758n/a
3759n/a ssl = SSL_get_app_data(s);
3760n/a assert(PySSLSocket_Check(ssl));
3761n/a
3762n/a /* The servername callback expects an argument that represents the current
3763n/a * SSL connection and that has a .context attribute that can be changed to
3764n/a * identify the requested hostname. Since the official API is the Python
3765n/a * level API we want to pass the callback a Python level object rather than
3766n/a * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3767n/a * SSLObject) that will be passed. Otherwise if there's a socket then that
3768n/a * will be passed. If both do not exist only then the C-level object is
3769n/a * passed. */
3770n/a if (ssl->owner)
3771n/a ssl_socket = PyWeakref_GetObject(ssl->owner);
3772n/a else if (ssl->Socket)
3773n/a ssl_socket = PyWeakref_GetObject(ssl->Socket);
3774n/a else
3775n/a ssl_socket = (PyObject *) ssl;
3776n/a
3777n/a Py_INCREF(ssl_socket);
3778n/a if (ssl_socket == Py_None)
3779n/a goto error;
3780n/a
3781n/a if (servername == NULL) {
3782n/a result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3783n/a Py_None, ssl_ctx, NULL);
3784n/a }
3785n/a else {
3786n/a servername_o = PyBytes_FromString(servername);
3787n/a if (servername_o == NULL) {
3788n/a PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3789n/a goto error;
3790n/a }
3791n/a servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3792n/a if (servername_idna == NULL) {
3793n/a PyErr_WriteUnraisable(servername_o);
3794n/a Py_DECREF(servername_o);
3795n/a goto error;
3796n/a }
3797n/a Py_DECREF(servername_o);
3798n/a result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3799n/a servername_idna, ssl_ctx, NULL);
3800n/a Py_DECREF(servername_idna);
3801n/a }
3802n/a Py_DECREF(ssl_socket);
3803n/a
3804n/a if (result == NULL) {
3805n/a PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3806n/a *al = SSL_AD_HANDSHAKE_FAILURE;
3807n/a ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3808n/a }
3809n/a else {
3810n/a if (result != Py_None) {
3811n/a *al = (int) PyLong_AsLong(result);
3812n/a if (PyErr_Occurred()) {
3813n/a PyErr_WriteUnraisable(result);
3814n/a *al = SSL_AD_INTERNAL_ERROR;
3815n/a }
3816n/a ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3817n/a }
3818n/a else {
3819n/a ret = SSL_TLSEXT_ERR_OK;
3820n/a }
3821n/a Py_DECREF(result);
3822n/a }
3823n/a
3824n/a#ifdef WITH_THREAD
3825n/a PyGILState_Release(gstate);
3826n/a#endif
3827n/a return ret;
3828n/a
3829n/aerror:
3830n/a Py_DECREF(ssl_socket);
3831n/a *al = SSL_AD_INTERNAL_ERROR;
3832n/a ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3833n/a#ifdef WITH_THREAD
3834n/a PyGILState_Release(gstate);
3835n/a#endif
3836n/a return ret;
3837n/a}
3838n/a#endif
3839n/a
3840n/a/*[clinic input]
3841n/a_ssl._SSLContext.set_servername_callback
3842n/a method as cb: object
3843n/a /
3844n/a
3845n/aSet a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3846n/a
3847n/aIf the argument is None then the callback is disabled. The method is called
3848n/awith the SSLSocket, the server name as a string, and the SSLContext object.
3849n/aSee RFC 6066 for details of the SNI extension.
3850n/a[clinic start generated code]*/
3851n/a
3852n/astatic PyObject *
3853n/a_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3854n/a/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
3855n/a{
3856n/a#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
3857n/a Py_CLEAR(self->set_hostname);
3858n/a if (cb == Py_None) {
3859n/a SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3860n/a }
3861n/a else {
3862n/a if (!PyCallable_Check(cb)) {
3863n/a SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3864n/a PyErr_SetString(PyExc_TypeError,
3865n/a "not a callable object");
3866n/a return NULL;
3867n/a }
3868n/a Py_INCREF(cb);
3869n/a self->set_hostname = cb;
3870n/a SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3871n/a SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3872n/a }
3873n/a Py_RETURN_NONE;
3874n/a#else
3875n/a PyErr_SetString(PyExc_NotImplementedError,
3876n/a "The TLS extension servername callback, "
3877n/a "SSL_CTX_set_tlsext_servername_callback, "
3878n/a "is not in the current OpenSSL library.");
3879n/a return NULL;
3880n/a#endif
3881n/a}
3882n/a
3883n/a/*[clinic input]
3884n/a_ssl._SSLContext.cert_store_stats
3885n/a
3886n/aReturns quantities of loaded X.509 certificates.
3887n/a
3888n/aX.509 certificates with a CA extension and certificate revocation lists
3889n/ainside the context's cert store.
3890n/a
3891n/aNOTE: Certificates in a capath directory aren't loaded unless they have
3892n/abeen used at least once.
3893n/a[clinic start generated code]*/
3894n/a
3895n/astatic PyObject *
3896n/a_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3897n/a/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
3898n/a{
3899n/a X509_STORE *store;
3900n/a STACK_OF(X509_OBJECT) *objs;
3901n/a X509_OBJECT *obj;
3902n/a int x509 = 0, crl = 0, ca = 0, i;
3903n/a
3904n/a store = SSL_CTX_get_cert_store(self->ctx);
3905n/a objs = X509_STORE_get0_objects(store);
3906n/a for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3907n/a obj = sk_X509_OBJECT_value(objs, i);
3908n/a switch (X509_OBJECT_get_type(obj)) {
3909n/a case X509_LU_X509:
3910n/a x509++;
3911n/a if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
3912n/a ca++;
3913n/a }
3914n/a break;
3915n/a case X509_LU_CRL:
3916n/a crl++;
3917n/a break;
3918n/a default:
3919n/a /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3920n/a * As far as I can tell they are internal states and never
3921n/a * stored in a cert store */
3922n/a break;
3923n/a }
3924n/a }
3925n/a return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3926n/a "x509_ca", ca);
3927n/a}
3928n/a
3929n/a/*[clinic input]
3930n/a_ssl._SSLContext.get_ca_certs
3931n/a binary_form: bool = False
3932n/a
3933n/aReturns a list of dicts with information of loaded CA certs.
3934n/a
3935n/aIf the optional argument is True, returns a DER-encoded copy of the CA
3936n/acertificate.
3937n/a
3938n/aNOTE: Certificates in a capath directory aren't loaded unless they have
3939n/abeen used at least once.
3940n/a[clinic start generated code]*/
3941n/a
3942n/astatic PyObject *
3943n/a_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3944n/a/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
3945n/a{
3946n/a X509_STORE *store;
3947n/a STACK_OF(X509_OBJECT) *objs;
3948n/a PyObject *ci = NULL, *rlist = NULL;
3949n/a int i;
3950n/a
3951n/a if ((rlist = PyList_New(0)) == NULL) {
3952n/a return NULL;
3953n/a }
3954n/a
3955n/a store = SSL_CTX_get_cert_store(self->ctx);
3956n/a objs = X509_STORE_get0_objects(store);
3957n/a for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3958n/a X509_OBJECT *obj;
3959n/a X509 *cert;
3960n/a
3961n/a obj = sk_X509_OBJECT_value(objs, i);
3962n/a if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
3963n/a /* not a x509 cert */
3964n/a continue;
3965n/a }
3966n/a /* CA for any purpose */
3967n/a cert = X509_OBJECT_get0_X509(obj);
3968n/a if (!X509_check_ca(cert)) {
3969n/a continue;
3970n/a }
3971n/a if (binary_form) {
3972n/a ci = _certificate_to_der(cert);
3973n/a } else {
3974n/a ci = _decode_certificate(cert);
3975n/a }
3976n/a if (ci == NULL) {
3977n/a goto error;
3978n/a }
3979n/a if (PyList_Append(rlist, ci) == -1) {
3980n/a goto error;
3981n/a }
3982n/a Py_CLEAR(ci);
3983n/a }
3984n/a return rlist;
3985n/a
3986n/a error:
3987n/a Py_XDECREF(ci);
3988n/a Py_XDECREF(rlist);
3989n/a return NULL;
3990n/a}
3991n/a
3992n/a
3993n/astatic PyGetSetDef context_getsetlist[] = {
3994n/a {"check_hostname", (getter) get_check_hostname,
3995n/a (setter) set_check_hostname, NULL},
3996n/a {"options", (getter) get_options,
3997n/a (setter) set_options, NULL},
3998n/a {"verify_flags", (getter) get_verify_flags,
3999n/a (setter) set_verify_flags, NULL},
4000n/a {"verify_mode", (getter) get_verify_mode,
4001n/a (setter) set_verify_mode, NULL},
4002n/a {NULL}, /* sentinel */
4003n/a};
4004n/a
4005n/astatic struct PyMethodDef context_methods[] = {
4006n/a _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4007n/a _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4008n/a _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4009n/a _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4010n/a _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4011n/a _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4012n/a _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4013n/a _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4014n/a _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4015n/a _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4016n/a _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4017n/a _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4018n/a _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4019n/a _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
4020n/a _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
4021n/a {NULL, NULL} /* sentinel */
4022n/a};
4023n/a
4024n/astatic PyTypeObject PySSLContext_Type = {
4025n/a PyVarObject_HEAD_INIT(NULL, 0)
4026n/a "_ssl._SSLContext", /*tp_name*/
4027n/a sizeof(PySSLContext), /*tp_basicsize*/
4028n/a 0, /*tp_itemsize*/
4029n/a (destructor)context_dealloc, /*tp_dealloc*/
4030n/a 0, /*tp_print*/
4031n/a 0, /*tp_getattr*/
4032n/a 0, /*tp_setattr*/
4033n/a 0, /*tp_reserved*/
4034n/a 0, /*tp_repr*/
4035n/a 0, /*tp_as_number*/
4036n/a 0, /*tp_as_sequence*/
4037n/a 0, /*tp_as_mapping*/
4038n/a 0, /*tp_hash*/
4039n/a 0, /*tp_call*/
4040n/a 0, /*tp_str*/
4041n/a 0, /*tp_getattro*/
4042n/a 0, /*tp_setattro*/
4043n/a 0, /*tp_as_buffer*/
4044n/a Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
4045n/a 0, /*tp_doc*/
4046n/a (traverseproc) context_traverse, /*tp_traverse*/
4047n/a (inquiry) context_clear, /*tp_clear*/
4048n/a 0, /*tp_richcompare*/
4049n/a 0, /*tp_weaklistoffset*/
4050n/a 0, /*tp_iter*/
4051n/a 0, /*tp_iternext*/
4052n/a context_methods, /*tp_methods*/
4053n/a 0, /*tp_members*/
4054n/a context_getsetlist, /*tp_getset*/
4055n/a 0, /*tp_base*/
4056n/a 0, /*tp_dict*/
4057n/a 0, /*tp_descr_get*/
4058n/a 0, /*tp_descr_set*/
4059n/a 0, /*tp_dictoffset*/
4060n/a 0, /*tp_init*/
4061n/a 0, /*tp_alloc*/
4062n/a _ssl__SSLContext, /*tp_new*/
4063n/a};
4064n/a
4065n/a
4066n/a/*
4067n/a * MemoryBIO objects
4068n/a */
4069n/a
4070n/a/*[clinic input]
4071n/a@classmethod
4072n/a_ssl.MemoryBIO.__new__
4073n/a
4074n/a[clinic start generated code]*/
4075n/a
4076n/astatic PyObject *
4077n/a_ssl_MemoryBIO_impl(PyTypeObject *type)
4078n/a/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
4079n/a{
4080n/a BIO *bio;
4081n/a PySSLMemoryBIO *self;
4082n/a
4083n/a bio = BIO_new(BIO_s_mem());
4084n/a if (bio == NULL) {
4085n/a PyErr_SetString(PySSLErrorObject,
4086n/a "failed to allocate BIO");
4087n/a return NULL;
4088n/a }
4089n/a /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4090n/a * just that no data is currently available. The SSL routines should retry
4091n/a * the read, which we can achieve by calling BIO_set_retry_read(). */
4092n/a BIO_set_retry_read(bio);
4093n/a BIO_set_mem_eof_return(bio, -1);
4094n/a
4095n/a assert(type != NULL && type->tp_alloc != NULL);
4096n/a self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4097n/a if (self == NULL) {
4098n/a BIO_free(bio);
4099n/a return NULL;
4100n/a }
4101n/a self->bio = bio;
4102n/a self->eof_written = 0;
4103n/a
4104n/a return (PyObject *) self;
4105n/a}
4106n/a
4107n/astatic void
4108n/amemory_bio_dealloc(PySSLMemoryBIO *self)
4109n/a{
4110n/a BIO_free(self->bio);
4111n/a Py_TYPE(self)->tp_free(self);
4112n/a}
4113n/a
4114n/astatic PyObject *
4115n/amemory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4116n/a{
4117n/a return PyLong_FromLong(BIO_ctrl_pending(self->bio));
4118n/a}
4119n/a
4120n/aPyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4121n/a"The number of bytes pending in the memory BIO.");
4122n/a
4123n/astatic PyObject *
4124n/amemory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4125n/a{
4126n/a return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4127n/a && self->eof_written);
4128n/a}
4129n/a
4130n/aPyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4131n/a"Whether the memory BIO is at EOF.");
4132n/a
4133n/a/*[clinic input]
4134n/a_ssl.MemoryBIO.read
4135n/a size as len: int = -1
4136n/a /
4137n/a
4138n/aRead up to size bytes from the memory BIO.
4139n/a
4140n/aIf size is not specified, read the entire buffer.
4141n/aIf the return value is an empty bytes instance, this means either
4142n/aEOF or that no data is available. Use the "eof" property to
4143n/adistinguish between the two.
4144n/a[clinic start generated code]*/
4145n/a
4146n/astatic PyObject *
4147n/a_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4148n/a/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4149n/a{
4150n/a int avail, nbytes;
4151n/a PyObject *result;
4152n/a
4153n/a avail = BIO_ctrl_pending(self->bio);
4154n/a if ((len < 0) || (len > avail))
4155n/a len = avail;
4156n/a
4157n/a result = PyBytes_FromStringAndSize(NULL, len);
4158n/a if ((result == NULL) || (len == 0))
4159n/a return result;
4160n/a
4161n/a nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4162n/a /* There should never be any short reads but check anyway. */
4163n/a if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4164n/a Py_DECREF(result);
4165n/a return NULL;
4166n/a }
4167n/a
4168n/a return result;
4169n/a}
4170n/a
4171n/a/*[clinic input]
4172n/a_ssl.MemoryBIO.write
4173n/a b: Py_buffer
4174n/a /
4175n/a
4176n/aWrites the bytes b into the memory BIO.
4177n/a
4178n/aReturns the number of bytes written.
4179n/a[clinic start generated code]*/
4180n/a
4181n/astatic PyObject *
4182n/a_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4183n/a/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
4184n/a{
4185n/a int nbytes;
4186n/a
4187n/a if (b->len > INT_MAX) {
4188n/a PyErr_Format(PyExc_OverflowError,
4189n/a "string longer than %d bytes", INT_MAX);
4190n/a return NULL;
4191n/a }
4192n/a
4193n/a if (self->eof_written) {
4194n/a PyErr_SetString(PySSLErrorObject,
4195n/a "cannot write() after write_eof()");
4196n/a return NULL;
4197n/a }
4198n/a
4199n/a nbytes = BIO_write(self->bio, b->buf, b->len);
4200n/a if (nbytes < 0) {
4201n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
4202n/a return NULL;
4203n/a }
4204n/a
4205n/a return PyLong_FromLong(nbytes);
4206n/a}
4207n/a
4208n/a/*[clinic input]
4209n/a_ssl.MemoryBIO.write_eof
4210n/a
4211n/aWrite an EOF marker to the memory BIO.
4212n/a
4213n/aWhen all data has been read, the "eof" property will be True.
4214n/a[clinic start generated code]*/
4215n/a
4216n/astatic PyObject *
4217n/a_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4218n/a/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
4219n/a{
4220n/a self->eof_written = 1;
4221n/a /* After an EOF is written, a zero return from read() should be a real EOF
4222n/a * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4223n/a BIO_clear_retry_flags(self->bio);
4224n/a BIO_set_mem_eof_return(self->bio, 0);
4225n/a
4226n/a Py_RETURN_NONE;
4227n/a}
4228n/a
4229n/astatic PyGetSetDef memory_bio_getsetlist[] = {
4230n/a {"pending", (getter) memory_bio_get_pending, NULL,
4231n/a PySSL_memory_bio_pending_doc},
4232n/a {"eof", (getter) memory_bio_get_eof, NULL,
4233n/a PySSL_memory_bio_eof_doc},
4234n/a {NULL}, /* sentinel */
4235n/a};
4236n/a
4237n/astatic struct PyMethodDef memory_bio_methods[] = {
4238n/a _SSL_MEMORYBIO_READ_METHODDEF
4239n/a _SSL_MEMORYBIO_WRITE_METHODDEF
4240n/a _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
4241n/a {NULL, NULL} /* sentinel */
4242n/a};
4243n/a
4244n/astatic PyTypeObject PySSLMemoryBIO_Type = {
4245n/a PyVarObject_HEAD_INIT(NULL, 0)
4246n/a "_ssl.MemoryBIO", /*tp_name*/
4247n/a sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4248n/a 0, /*tp_itemsize*/
4249n/a (destructor)memory_bio_dealloc, /*tp_dealloc*/
4250n/a 0, /*tp_print*/
4251n/a 0, /*tp_getattr*/
4252n/a 0, /*tp_setattr*/
4253n/a 0, /*tp_reserved*/
4254n/a 0, /*tp_repr*/
4255n/a 0, /*tp_as_number*/
4256n/a 0, /*tp_as_sequence*/
4257n/a 0, /*tp_as_mapping*/
4258n/a 0, /*tp_hash*/
4259n/a 0, /*tp_call*/
4260n/a 0, /*tp_str*/
4261n/a 0, /*tp_getattro*/
4262n/a 0, /*tp_setattro*/
4263n/a 0, /*tp_as_buffer*/
4264n/a Py_TPFLAGS_DEFAULT, /*tp_flags*/
4265n/a 0, /*tp_doc*/
4266n/a 0, /*tp_traverse*/
4267n/a 0, /*tp_clear*/
4268n/a 0, /*tp_richcompare*/
4269n/a 0, /*tp_weaklistoffset*/
4270n/a 0, /*tp_iter*/
4271n/a 0, /*tp_iternext*/
4272n/a memory_bio_methods, /*tp_methods*/
4273n/a 0, /*tp_members*/
4274n/a memory_bio_getsetlist, /*tp_getset*/
4275n/a 0, /*tp_base*/
4276n/a 0, /*tp_dict*/
4277n/a 0, /*tp_descr_get*/
4278n/a 0, /*tp_descr_set*/
4279n/a 0, /*tp_dictoffset*/
4280n/a 0, /*tp_init*/
4281n/a 0, /*tp_alloc*/
4282n/a _ssl_MemoryBIO, /*tp_new*/
4283n/a};
4284n/a
4285n/a
4286n/a/*
4287n/a * SSL Session object
4288n/a */
4289n/a
4290n/astatic void
4291n/aPySSLSession_dealloc(PySSLSession *self)
4292n/a{
4293n/a PyObject_GC_UnTrack(self);
4294n/a Py_XDECREF(self->ctx);
4295n/a if (self->session != NULL) {
4296n/a SSL_SESSION_free(self->session);
4297n/a }
4298n/a PyObject_GC_Del(self);
4299n/a}
4300n/a
4301n/astatic PyObject *
4302n/aPySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4303n/a{
4304n/a int result;
4305n/a
4306n/a if (left == NULL || right == NULL) {
4307n/a PyErr_BadInternalCall();
4308n/a return NULL;
4309n/a }
4310n/a
4311n/a if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4312n/a Py_RETURN_NOTIMPLEMENTED;
4313n/a }
4314n/a
4315n/a if (left == right) {
4316n/a result = 0;
4317n/a } else {
4318n/a const unsigned char *left_id, *right_id;
4319n/a unsigned int left_len, right_len;
4320n/a left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4321n/a &left_len);
4322n/a right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4323n/a &right_len);
4324n/a if (left_len == right_len) {
4325n/a result = memcmp(left_id, right_id, left_len);
4326n/a } else {
4327n/a result = 1;
4328n/a }
4329n/a }
4330n/a
4331n/a switch (op) {
4332n/a case Py_EQ:
4333n/a if (result == 0) {
4334n/a Py_RETURN_TRUE;
4335n/a } else {
4336n/a Py_RETURN_FALSE;
4337n/a }
4338n/a break;
4339n/a case Py_NE:
4340n/a if (result != 0) {
4341n/a Py_RETURN_TRUE;
4342n/a } else {
4343n/a Py_RETURN_FALSE;
4344n/a }
4345n/a break;
4346n/a case Py_LT:
4347n/a case Py_LE:
4348n/a case Py_GT:
4349n/a case Py_GE:
4350n/a Py_RETURN_NOTIMPLEMENTED;
4351n/a break;
4352n/a default:
4353n/a PyErr_BadArgument();
4354n/a return NULL;
4355n/a }
4356n/a}
4357n/a
4358n/astatic int
4359n/aPySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4360n/a{
4361n/a Py_VISIT(self->ctx);
4362n/a return 0;
4363n/a}
4364n/a
4365n/astatic int
4366n/aPySSLSession_clear(PySSLSession *self)
4367n/a{
4368n/a Py_CLEAR(self->ctx);
4369n/a return 0;
4370n/a}
4371n/a
4372n/a
4373n/astatic PyObject *
4374n/aPySSLSession_get_time(PySSLSession *self, void *closure) {
4375n/a return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4376n/a}
4377n/a
4378n/aPyDoc_STRVAR(PySSLSession_get_time_doc,
4379n/a"Session creation time (seconds since epoch).");
4380n/a
4381n/a
4382n/astatic PyObject *
4383n/aPySSLSession_get_timeout(PySSLSession *self, void *closure) {
4384n/a return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4385n/a}
4386n/a
4387n/aPyDoc_STRVAR(PySSLSession_get_timeout_doc,
4388n/a"Session timeout (delta in seconds).");
4389n/a
4390n/a
4391n/astatic PyObject *
4392n/aPySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4393n/a unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4394n/a return PyLong_FromUnsignedLong(hint);
4395n/a}
4396n/a
4397n/aPyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4398n/a"Ticket life time hint.");
4399n/a
4400n/a
4401n/astatic PyObject *
4402n/aPySSLSession_get_session_id(PySSLSession *self, void *closure) {
4403n/a const unsigned char *id;
4404n/a unsigned int len;
4405n/a id = SSL_SESSION_get_id(self->session, &len);
4406n/a return PyBytes_FromStringAndSize((const char *)id, len);
4407n/a}
4408n/a
4409n/aPyDoc_STRVAR(PySSLSession_get_session_id_doc,
4410n/a"Session id");
4411n/a
4412n/a
4413n/astatic PyObject *
4414n/aPySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4415n/a if (SSL_SESSION_has_ticket(self->session)) {
4416n/a Py_RETURN_TRUE;
4417n/a } else {
4418n/a Py_RETURN_FALSE;
4419n/a }
4420n/a}
4421n/a
4422n/aPyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4423n/a"Does the session contain a ticket?");
4424n/a
4425n/a
4426n/astatic PyGetSetDef PySSLSession_getsetlist[] = {
4427n/a {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4428n/a PySSLSession_get_has_ticket_doc},
4429n/a {"id", (getter) PySSLSession_get_session_id, NULL,
4430n/a PySSLSession_get_session_id_doc},
4431n/a {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4432n/a NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4433n/a {"time", (getter) PySSLSession_get_time, NULL,
4434n/a PySSLSession_get_time_doc},
4435n/a {"timeout", (getter) PySSLSession_get_timeout, NULL,
4436n/a PySSLSession_get_timeout_doc},
4437n/a {NULL}, /* sentinel */
4438n/a};
4439n/a
4440n/astatic PyTypeObject PySSLSession_Type = {
4441n/a PyVarObject_HEAD_INIT(NULL, 0)
4442n/a "_ssl.Session", /*tp_name*/
4443n/a sizeof(PySSLSession), /*tp_basicsize*/
4444n/a 0, /*tp_itemsize*/
4445n/a (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4446n/a 0, /*tp_print*/
4447n/a 0, /*tp_getattr*/
4448n/a 0, /*tp_setattr*/
4449n/a 0, /*tp_reserved*/
4450n/a 0, /*tp_repr*/
4451n/a 0, /*tp_as_number*/
4452n/a 0, /*tp_as_sequence*/
4453n/a 0, /*tp_as_mapping*/
4454n/a 0, /*tp_hash*/
4455n/a 0, /*tp_call*/
4456n/a 0, /*tp_str*/
4457n/a 0, /*tp_getattro*/
4458n/a 0, /*tp_setattro*/
4459n/a 0, /*tp_as_buffer*/
4460n/a Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
4461n/a 0, /*tp_doc*/
4462n/a (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4463n/a (inquiry)PySSLSession_clear, /*tp_clear*/
4464n/a PySSLSession_richcompare, /*tp_richcompare*/
4465n/a 0, /*tp_weaklistoffset*/
4466n/a 0, /*tp_iter*/
4467n/a 0, /*tp_iternext*/
4468n/a 0, /*tp_methods*/
4469n/a 0, /*tp_members*/
4470n/a PySSLSession_getsetlist, /*tp_getset*/
4471n/a};
4472n/a
4473n/a
4474n/a/* helper routines for seeding the SSL PRNG */
4475n/a/*[clinic input]
4476n/a_ssl.RAND_add
4477n/a string as view: Py_buffer(accept={str, buffer})
4478n/a entropy: double
4479n/a /
4480n/a
4481n/aMix string into the OpenSSL PRNG state.
4482n/a
4483n/aentropy (a float) is a lower bound on the entropy contained in
4484n/astring. See RFC 1750.
4485n/a[clinic start generated code]*/
4486n/a
4487n/astatic PyObject *
4488n/a_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
4489n/a/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
4490n/a{
4491n/a const char *buf;
4492n/a Py_ssize_t len, written;
4493n/a
4494n/a buf = (const char *)view->buf;
4495n/a len = view->len;
4496n/a do {
4497n/a written = Py_MIN(len, INT_MAX);
4498n/a RAND_add(buf, (int)written, entropy);
4499n/a buf += written;
4500n/a len -= written;
4501n/a } while (len);
4502n/a Py_RETURN_NONE;
4503n/a}
4504n/a
4505n/astatic PyObject *
4506n/aPySSL_RAND(int len, int pseudo)
4507n/a{
4508n/a int ok;
4509n/a PyObject *bytes;
4510n/a unsigned long err;
4511n/a const char *errstr;
4512n/a PyObject *v;
4513n/a
4514n/a if (len < 0) {
4515n/a PyErr_SetString(PyExc_ValueError, "num must be positive");
4516n/a return NULL;
4517n/a }
4518n/a
4519n/a bytes = PyBytes_FromStringAndSize(NULL, len);
4520n/a if (bytes == NULL)
4521n/a return NULL;
4522n/a if (pseudo) {
4523n/a ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4524n/a if (ok == 0 || ok == 1)
4525n/a return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4526n/a }
4527n/a else {
4528n/a ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4529n/a if (ok == 1)
4530n/a return bytes;
4531n/a }
4532n/a Py_DECREF(bytes);
4533n/a
4534n/a err = ERR_get_error();
4535n/a errstr = ERR_reason_error_string(err);
4536n/a v = Py_BuildValue("(ks)", err, errstr);
4537n/a if (v != NULL) {
4538n/a PyErr_SetObject(PySSLErrorObject, v);
4539n/a Py_DECREF(v);
4540n/a }
4541n/a return NULL;
4542n/a}
4543n/a
4544n/a/*[clinic input]
4545n/a_ssl.RAND_bytes
4546n/a n: int
4547n/a /
4548n/a
4549n/aGenerate n cryptographically strong pseudo-random bytes.
4550n/a[clinic start generated code]*/
4551n/a
4552n/astatic PyObject *
4553n/a_ssl_RAND_bytes_impl(PyObject *module, int n)
4554n/a/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
4555n/a{
4556n/a return PySSL_RAND(n, 0);
4557n/a}
4558n/a
4559n/a/*[clinic input]
4560n/a_ssl.RAND_pseudo_bytes
4561n/a n: int
4562n/a /
4563n/a
4564n/aGenerate n pseudo-random bytes.
4565n/a
4566n/aReturn a pair (bytes, is_cryptographic). is_cryptographic is True
4567n/aif the bytes generated are cryptographically strong.
4568n/a[clinic start generated code]*/
4569n/a
4570n/astatic PyObject *
4571n/a_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4572n/a/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
4573n/a{
4574n/a return PySSL_RAND(n, 1);
4575n/a}
4576n/a
4577n/a/*[clinic input]
4578n/a_ssl.RAND_status
4579n/a
4580n/aReturns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4581n/a
4582n/aIt is necessary to seed the PRNG with RAND_add() on some platforms before
4583n/ausing the ssl() function.
4584n/a[clinic start generated code]*/
4585n/a
4586n/astatic PyObject *
4587n/a_ssl_RAND_status_impl(PyObject *module)
4588n/a/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
4589n/a{
4590n/a return PyLong_FromLong(RAND_status());
4591n/a}
4592n/a
4593n/a#ifndef OPENSSL_NO_EGD
4594n/a/* LCOV_EXCL_START */
4595n/a/*[clinic input]
4596n/a_ssl.RAND_egd
4597n/a path: object(converter="PyUnicode_FSConverter")
4598n/a /
4599n/a
4600n/aQueries the entropy gather daemon (EGD) on the socket named by 'path'.
4601n/a
4602n/aReturns number of bytes read. Raises SSLError if connection to EGD
4603n/afails or if it does not provide enough data to seed PRNG.
4604n/a[clinic start generated code]*/
4605n/a
4606n/astatic PyObject *
4607n/a_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4608n/a/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
4609n/a{
4610n/a int bytes = RAND_egd(PyBytes_AsString(path));
4611n/a Py_DECREF(path);
4612n/a if (bytes == -1) {
4613n/a PyErr_SetString(PySSLErrorObject,
4614n/a "EGD connection failed or EGD did not return "
4615n/a "enough data to seed the PRNG");
4616n/a return NULL;
4617n/a }
4618n/a return PyLong_FromLong(bytes);
4619n/a}
4620n/a/* LCOV_EXCL_STOP */
4621n/a#endif /* OPENSSL_NO_EGD */
4622n/a
4623n/a
4624n/a
4625n/a/*[clinic input]
4626n/a_ssl.get_default_verify_paths
4627n/a
4628n/aReturn search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4629n/a
4630n/aThe values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4631n/a[clinic start generated code]*/
4632n/a
4633n/astatic PyObject *
4634n/a_ssl_get_default_verify_paths_impl(PyObject *module)
4635n/a/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
4636n/a{
4637n/a PyObject *ofile_env = NULL;
4638n/a PyObject *ofile = NULL;
4639n/a PyObject *odir_env = NULL;
4640n/a PyObject *odir = NULL;
4641n/a
4642n/a#define CONVERT(info, target) { \
4643n/a const char *tmp = (info); \
4644n/a target = NULL; \
4645n/a if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4646n/a else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4647n/a target = PyBytes_FromString(tmp); } \
4648n/a if (!target) goto error; \
4649n/a }
4650n/a
4651n/a CONVERT(X509_get_default_cert_file_env(), ofile_env);
4652n/a CONVERT(X509_get_default_cert_file(), ofile);
4653n/a CONVERT(X509_get_default_cert_dir_env(), odir_env);
4654n/a CONVERT(X509_get_default_cert_dir(), odir);
4655n/a#undef CONVERT
4656n/a
4657n/a return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
4658n/a
4659n/a error:
4660n/a Py_XDECREF(ofile_env);
4661n/a Py_XDECREF(ofile);
4662n/a Py_XDECREF(odir_env);
4663n/a Py_XDECREF(odir);
4664n/a return NULL;
4665n/a}
4666n/a
4667n/astatic PyObject*
4668n/aasn1obj2py(ASN1_OBJECT *obj)
4669n/a{
4670n/a int nid;
4671n/a const char *ln, *sn;
4672n/a char buf[100];
4673n/a Py_ssize_t buflen;
4674n/a
4675n/a nid = OBJ_obj2nid(obj);
4676n/a if (nid == NID_undef) {
4677n/a PyErr_Format(PyExc_ValueError, "Unknown object");
4678n/a return NULL;
4679n/a }
4680n/a sn = OBJ_nid2sn(nid);
4681n/a ln = OBJ_nid2ln(nid);
4682n/a buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4683n/a if (buflen < 0) {
4684n/a _setSSLError(NULL, 0, __FILE__, __LINE__);
4685n/a return NULL;
4686n/a }
4687n/a if (buflen) {
4688n/a return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4689n/a } else {
4690n/a return Py_BuildValue("issO", nid, sn, ln, Py_None);
4691n/a }
4692n/a}
4693n/a
4694n/a/*[clinic input]
4695n/a_ssl.txt2obj
4696n/a txt: str
4697n/a name: bool = False
4698n/a
4699n/aLookup NID, short name, long name and OID of an ASN1_OBJECT.
4700n/a
4701n/aBy default objects are looked up by OID. With name=True short and
4702n/along name are also matched.
4703n/a[clinic start generated code]*/
4704n/a
4705n/astatic PyObject *
4706n/a_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4707n/a/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
4708n/a{
4709n/a PyObject *result = NULL;
4710n/a ASN1_OBJECT *obj;
4711n/a
4712n/a obj = OBJ_txt2obj(txt, name ? 0 : 1);
4713n/a if (obj == NULL) {
4714n/a PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
4715n/a return NULL;
4716n/a }
4717n/a result = asn1obj2py(obj);
4718n/a ASN1_OBJECT_free(obj);
4719n/a return result;
4720n/a}
4721n/a
4722n/a/*[clinic input]
4723n/a_ssl.nid2obj
4724n/a nid: int
4725n/a /
4726n/a
4727n/aLookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4728n/a[clinic start generated code]*/
4729n/a
4730n/astatic PyObject *
4731n/a_ssl_nid2obj_impl(PyObject *module, int nid)
4732n/a/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
4733n/a{
4734n/a PyObject *result = NULL;
4735n/a ASN1_OBJECT *obj;
4736n/a
4737n/a if (nid < NID_undef) {
4738n/a PyErr_SetString(PyExc_ValueError, "NID must be positive.");
4739n/a return NULL;
4740n/a }
4741n/a obj = OBJ_nid2obj(nid);
4742n/a if (obj == NULL) {
4743n/a PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
4744n/a return NULL;
4745n/a }
4746n/a result = asn1obj2py(obj);
4747n/a ASN1_OBJECT_free(obj);
4748n/a return result;
4749n/a}
4750n/a
4751n/a#ifdef _MSC_VER
4752n/a
4753n/astatic PyObject*
4754n/acertEncodingType(DWORD encodingType)
4755n/a{
4756n/a static PyObject *x509_asn = NULL;
4757n/a static PyObject *pkcs_7_asn = NULL;
4758n/a
4759n/a if (x509_asn == NULL) {
4760n/a x509_asn = PyUnicode_InternFromString("x509_asn");
4761n/a if (x509_asn == NULL)
4762n/a return NULL;
4763n/a }
4764n/a if (pkcs_7_asn == NULL) {
4765n/a pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4766n/a if (pkcs_7_asn == NULL)
4767n/a return NULL;
4768n/a }
4769n/a switch(encodingType) {
4770n/a case X509_ASN_ENCODING:
4771n/a Py_INCREF(x509_asn);
4772n/a return x509_asn;
4773n/a case PKCS_7_ASN_ENCODING:
4774n/a Py_INCREF(pkcs_7_asn);
4775n/a return pkcs_7_asn;
4776n/a default:
4777n/a return PyLong_FromLong(encodingType);
4778n/a }
4779n/a}
4780n/a
4781n/astatic PyObject*
4782n/aparseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4783n/a{
4784n/a CERT_ENHKEY_USAGE *usage;
4785n/a DWORD size, error, i;
4786n/a PyObject *retval;
4787n/a
4788n/a if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4789n/a error = GetLastError();
4790n/a if (error == CRYPT_E_NOT_FOUND) {
4791n/a Py_RETURN_TRUE;
4792n/a }
4793n/a return PyErr_SetFromWindowsErr(error);
4794n/a }
4795n/a
4796n/a usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4797n/a if (usage == NULL) {
4798n/a return PyErr_NoMemory();
4799n/a }
4800n/a
4801n/a /* Now get the actual enhanced usage property */
4802n/a if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4803n/a PyMem_Free(usage);
4804n/a error = GetLastError();
4805n/a if (error == CRYPT_E_NOT_FOUND) {
4806n/a Py_RETURN_TRUE;
4807n/a }
4808n/a return PyErr_SetFromWindowsErr(error);
4809n/a }
4810n/a retval = PySet_New(NULL);
4811n/a if (retval == NULL) {
4812n/a goto error;
4813n/a }
4814n/a for (i = 0; i < usage->cUsageIdentifier; ++i) {
4815n/a if (usage->rgpszUsageIdentifier[i]) {
4816n/a PyObject *oid;
4817n/a int err;
4818n/a oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4819n/a if (oid == NULL) {
4820n/a Py_CLEAR(retval);
4821n/a goto error;
4822n/a }
4823n/a err = PySet_Add(retval, oid);
4824n/a Py_DECREF(oid);
4825n/a if (err == -1) {
4826n/a Py_CLEAR(retval);
4827n/a goto error;
4828n/a }
4829n/a }
4830n/a }
4831n/a error:
4832n/a PyMem_Free(usage);
4833n/a return retval;
4834n/a}
4835n/a
4836n/a/*[clinic input]
4837n/a_ssl.enum_certificates
4838n/a store_name: str
4839n/a
4840n/aRetrieve certificates from Windows' cert store.
4841n/a
4842n/astore_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4843n/amore cert storages, too. The function returns a list of (bytes,
4844n/aencoding_type, trust) tuples. The encoding_type flag can be interpreted
4845n/awith X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4846n/aa set of OIDs or the boolean True.
4847n/a[clinic start generated code]*/
4848n/a
4849n/astatic PyObject *
4850n/a_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4851n/a/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
4852n/a{
4853n/a HCERTSTORE hStore = NULL;
4854n/a PCCERT_CONTEXT pCertCtx = NULL;
4855n/a PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
4856n/a PyObject *result = NULL;
4857n/a
4858n/a result = PyList_New(0);
4859n/a if (result == NULL) {
4860n/a return NULL;
4861n/a }
4862n/a hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4863n/a CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4864n/a store_name);
4865n/a if (hStore == NULL) {
4866n/a Py_DECREF(result);
4867n/a return PyErr_SetFromWindowsErr(GetLastError());
4868n/a }
4869n/a
4870n/a while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4871n/a cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4872n/a pCertCtx->cbCertEncoded);
4873n/a if (!cert) {
4874n/a Py_CLEAR(result);
4875n/a break;
4876n/a }
4877n/a if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4878n/a Py_CLEAR(result);
4879n/a break;
4880n/a }
4881n/a keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4882n/a if (keyusage == Py_True) {
4883n/a Py_DECREF(keyusage);
4884n/a keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
4885n/a }
4886n/a if (keyusage == NULL) {
4887n/a Py_CLEAR(result);
4888n/a break;
4889n/a }
4890n/a if ((tup = PyTuple_New(3)) == NULL) {
4891n/a Py_CLEAR(result);
4892n/a break;
4893n/a }
4894n/a PyTuple_SET_ITEM(tup, 0, cert);
4895n/a cert = NULL;
4896n/a PyTuple_SET_ITEM(tup, 1, enc);
4897n/a enc = NULL;
4898n/a PyTuple_SET_ITEM(tup, 2, keyusage);
4899n/a keyusage = NULL;
4900n/a if (PyList_Append(result, tup) < 0) {
4901n/a Py_CLEAR(result);
4902n/a break;
4903n/a }
4904n/a Py_CLEAR(tup);
4905n/a }
4906n/a if (pCertCtx) {
4907n/a /* loop ended with an error, need to clean up context manually */
4908n/a CertFreeCertificateContext(pCertCtx);
4909n/a }
4910n/a
4911n/a /* In error cases cert, enc and tup may not be NULL */
4912n/a Py_XDECREF(cert);
4913n/a Py_XDECREF(enc);
4914n/a Py_XDECREF(keyusage);
4915n/a Py_XDECREF(tup);
4916n/a
4917n/a if (!CertCloseStore(hStore, 0)) {
4918n/a /* This error case might shadow another exception.*/
4919n/a Py_XDECREF(result);
4920n/a return PyErr_SetFromWindowsErr(GetLastError());
4921n/a }
4922n/a return result;
4923n/a}
4924n/a
4925n/a/*[clinic input]
4926n/a_ssl.enum_crls
4927n/a store_name: str
4928n/a
4929n/aRetrieve CRLs from Windows' cert store.
4930n/a
4931n/astore_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4932n/amore cert storages, too. The function returns a list of (bytes,
4933n/aencoding_type) tuples. The encoding_type flag can be interpreted with
4934n/aX509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4935n/a[clinic start generated code]*/
4936n/a
4937n/astatic PyObject *
4938n/a_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4939n/a/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
4940n/a{
4941n/a HCERTSTORE hStore = NULL;
4942n/a PCCRL_CONTEXT pCrlCtx = NULL;
4943n/a PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4944n/a PyObject *result = NULL;
4945n/a
4946n/a result = PyList_New(0);
4947n/a if (result == NULL) {
4948n/a return NULL;
4949n/a }
4950n/a hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4951n/a CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4952n/a store_name);
4953n/a if (hStore == NULL) {
4954n/a Py_DECREF(result);
4955n/a return PyErr_SetFromWindowsErr(GetLastError());
4956n/a }
4957n/a
4958n/a while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4959n/a crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4960n/a pCrlCtx->cbCrlEncoded);
4961n/a if (!crl) {
4962n/a Py_CLEAR(result);
4963n/a break;
4964n/a }
4965n/a if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4966n/a Py_CLEAR(result);
4967n/a break;
4968n/a }
4969n/a if ((tup = PyTuple_New(2)) == NULL) {
4970n/a Py_CLEAR(result);
4971n/a break;
4972n/a }
4973n/a PyTuple_SET_ITEM(tup, 0, crl);
4974n/a crl = NULL;
4975n/a PyTuple_SET_ITEM(tup, 1, enc);
4976n/a enc = NULL;
4977n/a
4978n/a if (PyList_Append(result, tup) < 0) {
4979n/a Py_CLEAR(result);
4980n/a break;
4981n/a }
4982n/a Py_CLEAR(tup);
4983n/a }
4984n/a if (pCrlCtx) {
4985n/a /* loop ended with an error, need to clean up context manually */
4986n/a CertFreeCRLContext(pCrlCtx);
4987n/a }
4988n/a
4989n/a /* In error cases cert, enc and tup may not be NULL */
4990n/a Py_XDECREF(crl);
4991n/a Py_XDECREF(enc);
4992n/a Py_XDECREF(tup);
4993n/a
4994n/a if (!CertCloseStore(hStore, 0)) {
4995n/a /* This error case might shadow another exception.*/
4996n/a Py_XDECREF(result);
4997n/a return PyErr_SetFromWindowsErr(GetLastError());
4998n/a }
4999n/a return result;
5000n/a}
5001n/a
5002n/a#endif /* _MSC_VER */
5003n/a
5004n/a/* List of functions exported by this module. */
5005n/astatic PyMethodDef PySSL_methods[] = {
5006n/a _SSL__TEST_DECODE_CERT_METHODDEF
5007n/a _SSL_RAND_ADD_METHODDEF
5008n/a _SSL_RAND_BYTES_METHODDEF
5009n/a _SSL_RAND_PSEUDO_BYTES_METHODDEF
5010n/a _SSL_RAND_EGD_METHODDEF
5011n/a _SSL_RAND_STATUS_METHODDEF
5012n/a _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5013n/a _SSL_ENUM_CERTIFICATES_METHODDEF
5014n/a _SSL_ENUM_CRLS_METHODDEF
5015n/a _SSL_TXT2OBJ_METHODDEF
5016n/a _SSL_NID2OBJ_METHODDEF
5017n/a {NULL, NULL} /* Sentinel */
5018n/a};
5019n/a
5020n/a
5021n/a#ifdef HAVE_OPENSSL_CRYPTO_LOCK
5022n/a
5023n/a/* an implementation of OpenSSL threading operations in terms
5024n/a * of the Python C thread library
5025n/a * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5026n/a */
5027n/a
5028n/astatic PyThread_type_lock *_ssl_locks = NULL;
5029n/a
5030n/a#if OPENSSL_VERSION_NUMBER >= 0x10000000
5031n/a/* use new CRYPTO_THREADID API. */
5032n/astatic void
5033n/a_ssl_threadid_callback(CRYPTO_THREADID *id)
5034n/a{
5035n/a CRYPTO_THREADID_set_numeric(id,
5036n/a (unsigned long)PyThread_get_thread_ident());
5037n/a}
5038n/a#else
5039n/a/* deprecated CRYPTO_set_id_callback() API. */
5040n/astatic unsigned long
5041n/a_ssl_thread_id_function (void) {
5042n/a return PyThread_get_thread_ident();
5043n/a}
5044n/a#endif
5045n/a
5046n/astatic void _ssl_thread_locking_function
5047n/a (int mode, int n, const char *file, int line) {
5048n/a /* this function is needed to perform locking on shared data
5049n/a structures. (Note that OpenSSL uses a number of global data
5050n/a structures that will be implicitly shared whenever multiple
5051n/a threads use OpenSSL.) Multi-threaded applications will
5052n/a crash at random if it is not set.
5053n/a
5054n/a locking_function() must be able to handle up to
5055n/a CRYPTO_num_locks() different mutex locks. It sets the n-th
5056n/a lock if mode & CRYPTO_LOCK, and releases it otherwise.
5057n/a
5058n/a file and line are the file number of the function setting the
5059n/a lock. They can be useful for debugging.
5060n/a */
5061n/a
5062n/a if ((_ssl_locks == NULL) ||
5063n/a (n < 0) || ((unsigned)n >= _ssl_locks_count))
5064n/a return;
5065n/a
5066n/a if (mode & CRYPTO_LOCK) {
5067n/a PyThread_acquire_lock(_ssl_locks[n], 1);
5068n/a } else {
5069n/a PyThread_release_lock(_ssl_locks[n]);
5070n/a }
5071n/a}
5072n/a
5073n/astatic int _setup_ssl_threads(void) {
5074n/a
5075n/a unsigned int i;
5076n/a
5077n/a if (_ssl_locks == NULL) {
5078n/a _ssl_locks_count = CRYPTO_num_locks();
5079n/a _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5080n/a sizeof(PyThread_type_lock));
5081n/a if (_ssl_locks == NULL) {
5082n/a PyErr_NoMemory();
5083n/a return 0;
5084n/a }
5085n/a for (i = 0; i < _ssl_locks_count; i++) {
5086n/a _ssl_locks[i] = PyThread_allocate_lock();
5087n/a if (_ssl_locks[i] == NULL) {
5088n/a unsigned int j;
5089n/a for (j = 0; j < i; j++) {
5090n/a PyThread_free_lock(_ssl_locks[j]);
5091n/a }
5092n/a PyMem_Free(_ssl_locks);
5093n/a return 0;
5094n/a }
5095n/a }
5096n/a CRYPTO_set_locking_callback(_ssl_thread_locking_function);
5097n/a#if OPENSSL_VERSION_NUMBER >= 0x10000000
5098n/a CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5099n/a#else
5100n/a CRYPTO_set_id_callback(_ssl_thread_id_function);
5101n/a#endif
5102n/a }
5103n/a return 1;
5104n/a}
5105n/a
5106n/a#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
5107n/a
5108n/aPyDoc_STRVAR(module_doc,
5109n/a"Implementation module for SSL socket operations. See the socket module\n\
5110n/afor documentation.");
5111n/a
5112n/a
5113n/astatic struct PyModuleDef _sslmodule = {
5114n/a PyModuleDef_HEAD_INIT,
5115n/a "_ssl",
5116n/a module_doc,
5117n/a -1,
5118n/a PySSL_methods,
5119n/a NULL,
5120n/a NULL,
5121n/a NULL,
5122n/a NULL
5123n/a};
5124n/a
5125n/a
5126n/astatic void
5127n/aparse_openssl_version(unsigned long libver,
5128n/a unsigned int *major, unsigned int *minor,
5129n/a unsigned int *fix, unsigned int *patch,
5130n/a unsigned int *status)
5131n/a{
5132n/a *status = libver & 0xF;
5133n/a libver >>= 4;
5134n/a *patch = libver & 0xFF;
5135n/a libver >>= 8;
5136n/a *fix = libver & 0xFF;
5137n/a libver >>= 8;
5138n/a *minor = libver & 0xFF;
5139n/a libver >>= 8;
5140n/a *major = libver & 0xFF;
5141n/a}
5142n/a
5143n/aPyMODINIT_FUNC
5144n/aPyInit__ssl(void)
5145n/a{
5146n/a PyObject *m, *d, *r;
5147n/a unsigned long libver;
5148n/a unsigned int major, minor, fix, patch, status;
5149n/a PySocketModule_APIObject *socket_api;
5150n/a struct py_ssl_error_code *errcode;
5151n/a struct py_ssl_library_code *libcode;
5152n/a
5153n/a if (PyType_Ready(&PySSLContext_Type) < 0)
5154n/a return NULL;
5155n/a if (PyType_Ready(&PySSLSocket_Type) < 0)
5156n/a return NULL;
5157n/a if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5158n/a return NULL;
5159n/a if (PyType_Ready(&PySSLSession_Type) < 0)
5160n/a return NULL;
5161n/a
5162n/a
5163n/a m = PyModule_Create(&_sslmodule);
5164n/a if (m == NULL)
5165n/a return NULL;
5166n/a d = PyModule_GetDict(m);
5167n/a
5168n/a /* Load _socket module and its C API */
5169n/a socket_api = PySocketModule_ImportModuleAndAPI();
5170n/a if (!socket_api)
5171n/a return NULL;
5172n/a PySocketModule = *socket_api;
5173n/a
5174n/a /* Init OpenSSL */
5175n/a SSL_load_error_strings();
5176n/a SSL_library_init();
5177n/a#ifdef WITH_THREAD
5178n/a#ifdef HAVE_OPENSSL_CRYPTO_LOCK
5179n/a /* note that this will start threading if not already started */
5180n/a if (!_setup_ssl_threads()) {
5181n/a return NULL;
5182n/a }
5183n/a#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5184n/a /* OpenSSL 1.1.0 builtin thread support is enabled */
5185n/a _ssl_locks_count++;
5186n/a#endif
5187n/a#endif /* WITH_THREAD */
5188n/a OpenSSL_add_all_algorithms();
5189n/a
5190n/a /* Add symbols to module dict */
5191n/a sslerror_type_slots[0].pfunc = PyExc_OSError;
5192n/a PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
5193n/a if (PySSLErrorObject == NULL)
5194n/a return NULL;
5195n/a
5196n/a PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5197n/a "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5198n/a PySSLErrorObject, NULL);
5199n/a PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5200n/a "ssl.SSLWantReadError", SSLWantReadError_doc,
5201n/a PySSLErrorObject, NULL);
5202n/a PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5203n/a "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5204n/a PySSLErrorObject, NULL);
5205n/a PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5206n/a "ssl.SSLSyscallError", SSLSyscallError_doc,
5207n/a PySSLErrorObject, NULL);
5208n/a PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5209n/a "ssl.SSLEOFError", SSLEOFError_doc,
5210n/a PySSLErrorObject, NULL);
5211n/a if (PySSLZeroReturnErrorObject == NULL
5212n/a || PySSLWantReadErrorObject == NULL
5213n/a || PySSLWantWriteErrorObject == NULL
5214n/a || PySSLSyscallErrorObject == NULL
5215n/a || PySSLEOFErrorObject == NULL)
5216n/a return NULL;
5217n/a if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5218n/a || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5219n/a || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5220n/a || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5221n/a || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5222n/a || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
5223n/a return NULL;
5224n/a if (PyDict_SetItemString(d, "_SSLContext",
5225n/a (PyObject *)&PySSLContext_Type) != 0)
5226n/a return NULL;
5227n/a if (PyDict_SetItemString(d, "_SSLSocket",
5228n/a (PyObject *)&PySSLSocket_Type) != 0)
5229n/a return NULL;
5230n/a if (PyDict_SetItemString(d, "MemoryBIO",
5231n/a (PyObject *)&PySSLMemoryBIO_Type) != 0)
5232n/a return NULL;
5233n/a if (PyDict_SetItemString(d, "SSLSession",
5234n/a (PyObject *)&PySSLSession_Type) != 0)
5235n/a return NULL;
5236n/a
5237n/a PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5238n/a PY_SSL_ERROR_ZERO_RETURN);
5239n/a PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5240n/a PY_SSL_ERROR_WANT_READ);
5241n/a PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5242n/a PY_SSL_ERROR_WANT_WRITE);
5243n/a PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5244n/a PY_SSL_ERROR_WANT_X509_LOOKUP);
5245n/a PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5246n/a PY_SSL_ERROR_SYSCALL);
5247n/a PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5248n/a PY_SSL_ERROR_SSL);
5249n/a PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5250n/a PY_SSL_ERROR_WANT_CONNECT);
5251n/a /* non ssl.h errorcodes */
5252n/a PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5253n/a PY_SSL_ERROR_EOF);
5254n/a PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5255n/a PY_SSL_ERROR_INVALID_ERROR_CODE);
5256n/a /* cert requirements */
5257n/a PyModule_AddIntConstant(m, "CERT_NONE",
5258n/a PY_SSL_CERT_NONE);
5259n/a PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5260n/a PY_SSL_CERT_OPTIONAL);
5261n/a PyModule_AddIntConstant(m, "CERT_REQUIRED",
5262n/a PY_SSL_CERT_REQUIRED);
5263n/a /* CRL verification for verification_flags */
5264n/a PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5265n/a 0);
5266n/a PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5267n/a X509_V_FLAG_CRL_CHECK);
5268n/a PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5269n/a X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5270n/a PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5271n/a X509_V_FLAG_X509_STRICT);
5272n/a#ifdef X509_V_FLAG_TRUSTED_FIRST
5273n/a PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5274n/a X509_V_FLAG_TRUSTED_FIRST);
5275n/a#endif
5276n/a
5277n/a /* Alert Descriptions from ssl.h */
5278n/a /* note RESERVED constants no longer intended for use have been removed */
5279n/a /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5280n/a
5281n/a#define ADD_AD_CONSTANT(s) \
5282n/a PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5283n/a SSL_AD_##s)
5284n/a
5285n/a ADD_AD_CONSTANT(CLOSE_NOTIFY);
5286n/a ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5287n/a ADD_AD_CONSTANT(BAD_RECORD_MAC);
5288n/a ADD_AD_CONSTANT(RECORD_OVERFLOW);
5289n/a ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5290n/a ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5291n/a ADD_AD_CONSTANT(BAD_CERTIFICATE);
5292n/a ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5293n/a ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5294n/a ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5295n/a ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5296n/a ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5297n/a ADD_AD_CONSTANT(UNKNOWN_CA);
5298n/a ADD_AD_CONSTANT(ACCESS_DENIED);
5299n/a ADD_AD_CONSTANT(DECODE_ERROR);
5300n/a ADD_AD_CONSTANT(DECRYPT_ERROR);
5301n/a ADD_AD_CONSTANT(PROTOCOL_VERSION);
5302n/a ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5303n/a ADD_AD_CONSTANT(INTERNAL_ERROR);
5304n/a ADD_AD_CONSTANT(USER_CANCELLED);
5305n/a ADD_AD_CONSTANT(NO_RENEGOTIATION);
5306n/a /* Not all constants are in old OpenSSL versions */
5307n/a#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5308n/a ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5309n/a#endif
5310n/a#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5311n/a ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5312n/a#endif
5313n/a#ifdef SSL_AD_UNRECOGNIZED_NAME
5314n/a ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5315n/a#endif
5316n/a#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5317n/a ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5318n/a#endif
5319n/a#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5320n/a ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5321n/a#endif
5322n/a#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5323n/a ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5324n/a#endif
5325n/a
5326n/a#undef ADD_AD_CONSTANT
5327n/a
5328n/a /* protocol versions */
5329n/a#ifndef OPENSSL_NO_SSL2
5330n/a PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5331n/a PY_SSL_VERSION_SSL2);
5332n/a#endif
5333n/a#ifndef OPENSSL_NO_SSL3
5334n/a PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5335n/a PY_SSL_VERSION_SSL3);
5336n/a#endif
5337n/a PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
5338n/a PY_SSL_VERSION_TLS);
5339n/a PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5340n/a PY_SSL_VERSION_TLS);
5341n/a PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5342n/a PY_SSL_VERSION_TLS_CLIENT);
5343n/a PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5344n/a PY_SSL_VERSION_TLS_SERVER);
5345n/a PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5346n/a PY_SSL_VERSION_TLS1);
5347n/a#if HAVE_TLSv1_2
5348n/a PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5349n/a PY_SSL_VERSION_TLS1_1);
5350n/a PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5351n/a PY_SSL_VERSION_TLS1_2);
5352n/a#endif
5353n/a
5354n/a /* protocol options */
5355n/a PyModule_AddIntConstant(m, "OP_ALL",
5356n/a SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
5357n/a PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5358n/a PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5359n/a PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
5360n/a#if HAVE_TLSv1_2
5361n/a PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5362n/a PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5363n/a#endif
5364n/a PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5365n/a SSL_OP_CIPHER_SERVER_PREFERENCE);
5366n/a PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
5367n/a PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
5368n/a#ifdef SSL_OP_SINGLE_ECDH_USE
5369n/a PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
5370n/a#endif
5371n/a#ifdef SSL_OP_NO_COMPRESSION
5372n/a PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5373n/a SSL_OP_NO_COMPRESSION);
5374n/a#endif
5375n/a
5376n/a#if HAVE_SNI
5377n/a r = Py_True;
5378n/a#else
5379n/a r = Py_False;
5380n/a#endif
5381n/a Py_INCREF(r);
5382n/a PyModule_AddObject(m, "HAS_SNI", r);
5383n/a
5384n/a r = Py_True;
5385n/a Py_INCREF(r);
5386n/a PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5387n/a
5388n/a#ifdef OPENSSL_NO_ECDH
5389n/a r = Py_False;
5390n/a#else
5391n/a r = Py_True;
5392n/a#endif
5393n/a Py_INCREF(r);
5394n/a PyModule_AddObject(m, "HAS_ECDH", r);
5395n/a
5396n/a#ifdef OPENSSL_NPN_NEGOTIATED
5397n/a r = Py_True;
5398n/a#else
5399n/a r = Py_False;
5400n/a#endif
5401n/a Py_INCREF(r);
5402n/a PyModule_AddObject(m, "HAS_NPN", r);
5403n/a
5404n/a#ifdef HAVE_ALPN
5405n/a r = Py_True;
5406n/a#else
5407n/a r = Py_False;
5408n/a#endif
5409n/a Py_INCREF(r);
5410n/a PyModule_AddObject(m, "HAS_ALPN", r);
5411n/a
5412n/a /* Mappings for error codes */
5413n/a err_codes_to_names = PyDict_New();
5414n/a err_names_to_codes = PyDict_New();
5415n/a if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5416n/a return NULL;
5417n/a errcode = error_codes;
5418n/a while (errcode->mnemonic != NULL) {
5419n/a PyObject *mnemo, *key;
5420n/a mnemo = PyUnicode_FromString(errcode->mnemonic);
5421n/a key = Py_BuildValue("ii", errcode->library, errcode->reason);
5422n/a if (mnemo == NULL || key == NULL)
5423n/a return NULL;
5424n/a if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5425n/a return NULL;
5426n/a if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5427n/a return NULL;
5428n/a Py_DECREF(key);
5429n/a Py_DECREF(mnemo);
5430n/a errcode++;
5431n/a }
5432n/a if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5433n/a return NULL;
5434n/a if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5435n/a return NULL;
5436n/a
5437n/a lib_codes_to_names = PyDict_New();
5438n/a if (lib_codes_to_names == NULL)
5439n/a return NULL;
5440n/a libcode = library_codes;
5441n/a while (libcode->library != NULL) {
5442n/a PyObject *mnemo, *key;
5443n/a key = PyLong_FromLong(libcode->code);
5444n/a mnemo = PyUnicode_FromString(libcode->library);
5445n/a if (key == NULL || mnemo == NULL)
5446n/a return NULL;
5447n/a if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5448n/a return NULL;
5449n/a Py_DECREF(key);
5450n/a Py_DECREF(mnemo);
5451n/a libcode++;
5452n/a }
5453n/a if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5454n/a return NULL;
5455n/a
5456n/a /* OpenSSL version */
5457n/a /* SSLeay() gives us the version of the library linked against,
5458n/a which could be different from the headers version.
5459n/a */
5460n/a libver = SSLeay();
5461n/a r = PyLong_FromUnsignedLong(libver);
5462n/a if (r == NULL)
5463n/a return NULL;
5464n/a if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5465n/a return NULL;
5466n/a parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5467n/a r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5468n/a if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5469n/a return NULL;
5470n/a r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5471n/a if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5472n/a return NULL;
5473n/a
5474n/a libver = OPENSSL_VERSION_NUMBER;
5475n/a parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5476n/a r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5477n/a if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5478n/a return NULL;
5479n/a
5480n/a return m;
5481n/a}