blob: 147703c11e350ae8f2f9ed1cf1951d7a677150eb [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#ifdef WITH_THREAD
22#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020023
Christian Heimesf77b4b22013-08-21 13:26:05 +020024
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020025#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
26 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
27#define PySSL_END_ALLOW_THREADS_S(save) \
28 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000029#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000030 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020031 PySSL_BEGIN_ALLOW_THREADS_S(_save);
32#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
33#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
34#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000035
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000036#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000037
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020038#define PySSL_BEGIN_ALLOW_THREADS_S(save)
39#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000040#define PySSL_BEGIN_ALLOW_THREADS
41#define PySSL_BLOCK_THREADS
42#define PySSL_UNBLOCK_THREADS
43#define PySSL_END_ALLOW_THREADS
44
45#endif
46
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010047/* Include symbols from _socket module */
48#include "socketmodule.h"
49
50static PySocketModule_APIObject PySocketModule;
51
52#if defined(HAVE_POLL_H)
53#include <poll.h>
54#elif defined(HAVE_SYS_POLL_H)
55#include <sys/poll.h>
56#endif
57
Christian Heimes598894f2016-09-05 23:19:05 +020058/* Don't warn about deprecated functions */
59#ifdef __GNUC__
60#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
61#endif
62#ifdef __clang__
63#pragma clang diagnostic ignored "-Wdeprecated-declarations"
64#endif
65
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010066/* Include OpenSSL header files */
67#include "openssl/rsa.h"
68#include "openssl/crypto.h"
69#include "openssl/x509.h"
70#include "openssl/x509v3.h"
71#include "openssl/pem.h"
72#include "openssl/ssl.h"
73#include "openssl/err.h"
74#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020075#include "openssl/bio.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010076
77/* SSL error object */
78static PyObject *PySSLErrorObject;
79static PyObject *PySSLZeroReturnErrorObject;
80static PyObject *PySSLWantReadErrorObject;
81static PyObject *PySSLWantWriteErrorObject;
82static PyObject *PySSLSyscallErrorObject;
83static PyObject *PySSLEOFErrorObject;
84
85/* Error mappings */
86static PyObject *err_codes_to_names;
87static PyObject *err_names_to_codes;
88static PyObject *lib_codes_to_names;
89
90struct py_ssl_error_code {
91 const char *mnemonic;
92 int library, reason;
93};
94struct py_ssl_library_code {
95 const char *library;
96 int code;
97};
98
99/* Include generated data (error codes) */
100#include "_ssl_data.h"
101
Christian Heimes598894f2016-09-05 23:19:05 +0200102#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
103# define OPENSSL_VERSION_1_1 1
104#endif
105
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100106/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
107 http://www.openssl.org/news/changelog.html
108 */
109#if OPENSSL_VERSION_NUMBER >= 0x10001000L
110# define HAVE_TLSv1_2 1
111#else
112# define HAVE_TLSv1_2 0
113#endif
114
Christian Heimes470fba12013-11-28 15:12:15 +0100115/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100116 * This includes the SSL_set_SSL_CTX() function.
117 */
118#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
119# define HAVE_SNI 1
120#else
121# define HAVE_SNI 0
122#endif
123
Benjamin Petersond3308222015-09-27 00:09:02 -0700124#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Benjamin Petersoncca27322015-01-23 16:35:37 -0500125# define HAVE_ALPN
126#endif
127
Victor Stinner524714e2016-07-22 17:43:59 +0200128#ifndef INVALID_SOCKET /* MS defines this */
129#define INVALID_SOCKET (-1)
130#endif
131
Christian Heimes598894f2016-09-05 23:19:05 +0200132#ifdef OPENSSL_VERSION_1_1
133/* OpenSSL 1.1.0+ */
134#ifndef OPENSSL_NO_SSL2
135#define OPENSSL_NO_SSL2
136#endif
137#else /* OpenSSL < 1.1.0 */
138#if defined(WITH_THREAD)
139#define HAVE_OPENSSL_CRYPTO_LOCK
140#endif
141
142#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200143#define TLS_client_method SSLv23_client_method
144#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200145
146static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
147{
148 return ne->set;
149}
150
151#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200152/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200153static int COMP_get_type(const COMP_METHOD *meth)
154{
155 return meth->type;
156}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200157/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200158#endif
159
160static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
161{
162 return ctx->default_passwd_callback;
163}
164
165static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
166{
167 return ctx->default_passwd_callback_userdata;
168}
169
170static int X509_OBJECT_get_type(X509_OBJECT *x)
171{
172 return x->type;
173}
174
175static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
176{
177 return x->data.x509;
178}
179
180static int BIO_up_ref(BIO *b)
181{
182 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
183 return 1;
184}
185
186static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
187 return store->objs;
188}
189
190static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
191{
192 return store->param;
193}
Christian Heimes99a65702016-09-10 23:44:53 +0200194
195static int
196SSL_SESSION_has_ticket(const SSL_SESSION *s)
197{
198 return (s->tlsext_ticklen > 0) ? 1 : 0;
199}
200
201static unsigned long
202SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
203{
204 return s->tlsext_tick_lifetime_hint;
205}
206
Christian Heimes598894f2016-09-05 23:19:05 +0200207#endif /* OpenSSL < 1.1.0 or LibreSSL */
208
209
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000210enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000211 /* these mirror ssl.h */
212 PY_SSL_ERROR_NONE,
213 PY_SSL_ERROR_SSL,
214 PY_SSL_ERROR_WANT_READ,
215 PY_SSL_ERROR_WANT_WRITE,
216 PY_SSL_ERROR_WANT_X509_LOOKUP,
217 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
218 PY_SSL_ERROR_ZERO_RETURN,
219 PY_SSL_ERROR_WANT_CONNECT,
220 /* start of non ssl.h errorcodes */
221 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
222 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
223 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000224};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000225
Thomas Woutersed03b412007-08-28 21:37:11 +0000226enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000227 PY_SSL_CLIENT,
228 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000229};
230
231enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000232 PY_SSL_CERT_NONE,
233 PY_SSL_CERT_OPTIONAL,
234 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000235};
236
237enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000238 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200239 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200240 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100241#if HAVE_TLSv1_2
242 PY_SSL_VERSION_TLS1,
243 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200244 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100245#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200246 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000247#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200248 PY_SSL_VERSION_TLS_CLIENT=0x10,
249 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100250};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200251
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000252#ifdef WITH_THREAD
253
254/* serves as a flag to see whether we've initialized the SSL thread support. */
255/* 0 means no, greater than 0 means yes */
256
257static unsigned int _ssl_locks_count = 0;
258
259#endif /* def WITH_THREAD */
260
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000261/* SSL socket object */
262
263#define X509_NAME_MAXLEN 256
264
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000265/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
266 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
267 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
268#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000269# define HAVE_SSL_CTX_CLEAR_OPTIONS
270#else
271# undef HAVE_SSL_CTX_CLEAR_OPTIONS
272#endif
273
Antoine Pitroud6494802011-07-21 01:11:30 +0200274/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
275 * older SSL, but let's be safe */
276#define PySSL_CB_MAXLEN 128
277
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100278
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000279typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000280 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000281 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100282#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -0500283 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100284 int npn_protocols_len;
285#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500286#ifdef HAVE_ALPN
287 unsigned char *alpn_protocols;
288 int alpn_protocols_len;
289#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100290#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200291 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100292#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100293 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000294} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000295
Antoine Pitrou152efa22010-05-16 18:19:27 +0000296typedef struct {
297 PyObject_HEAD
298 PyObject *Socket; /* weakref to socket on which we're layered */
299 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100300 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200301 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200302 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200303 PyObject *owner; /* Python level "owner" passed to servername callback */
304 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000305} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000306
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200307typedef struct {
308 PyObject_HEAD
309 BIO *bio;
310 int eof_written;
311} PySSLMemoryBIO;
312
Christian Heimes99a65702016-09-10 23:44:53 +0200313typedef struct {
314 PyObject_HEAD
315 SSL_SESSION *session;
316 PySSLContext *ctx;
317} PySSLSession;
318
Antoine Pitrou152efa22010-05-16 18:19:27 +0000319static PyTypeObject PySSLContext_Type;
320static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200321static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200322static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000323
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300324/*[clinic input]
325module _ssl
326class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
327class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
328class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200329class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300330[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200331/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300332
333#include "clinic/_ssl.c.h"
334
Victor Stinner14690702015-04-06 22:46:13 +0200335static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000336
Christian Heimes99a65702016-09-10 23:44:53 +0200337
Antoine Pitrou152efa22010-05-16 18:19:27 +0000338#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
339#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200340#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200341#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000342
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000343typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000344 SOCKET_IS_NONBLOCKING,
345 SOCKET_IS_BLOCKING,
346 SOCKET_HAS_TIMED_OUT,
347 SOCKET_HAS_BEEN_CLOSED,
348 SOCKET_TOO_LARGE_FOR_SELECT,
349 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000350} timeout_state;
351
Thomas Woutersed03b412007-08-28 21:37:11 +0000352/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000353#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200354#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000355
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200356/* Get the socket from a PySSLSocket, if it has one */
357#define GET_SOCKET(obj) ((obj)->Socket ? \
358 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200359
Victor Stinner14690702015-04-06 22:46:13 +0200360/* If sock is NULL, use a timeout of 0 second */
361#define GET_SOCKET_TIMEOUT(sock) \
362 ((sock != NULL) ? (sock)->sock_timeout : 0)
363
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200364/*
365 * SSL errors.
366 */
367
368PyDoc_STRVAR(SSLError_doc,
369"An error occurred in the SSL implementation.");
370
371PyDoc_STRVAR(SSLZeroReturnError_doc,
372"SSL/TLS session closed cleanly.");
373
374PyDoc_STRVAR(SSLWantReadError_doc,
375"Non-blocking SSL socket needs to read more data\n"
376"before the requested operation can be completed.");
377
378PyDoc_STRVAR(SSLWantWriteError_doc,
379"Non-blocking SSL socket needs to write more data\n"
380"before the requested operation can be completed.");
381
382PyDoc_STRVAR(SSLSyscallError_doc,
383"System error when attempting SSL operation.");
384
385PyDoc_STRVAR(SSLEOFError_doc,
386"SSL/TLS connection terminated abruptly.");
387
388static PyObject *
389SSLError_str(PyOSErrorObject *self)
390{
391 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
392 Py_INCREF(self->strerror);
393 return self->strerror;
394 }
395 else
396 return PyObject_Str(self->args);
397}
398
399static PyType_Slot sslerror_type_slots[] = {
400 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
401 {Py_tp_doc, SSLError_doc},
402 {Py_tp_str, SSLError_str},
403 {0, 0},
404};
405
406static PyType_Spec sslerror_type_spec = {
407 "ssl.SSLError",
408 sizeof(PyOSErrorObject),
409 0,
410 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
411 sslerror_type_slots
412};
413
414static void
415fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
416 int lineno, unsigned long errcode)
417{
418 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
419 PyObject *init_value, *msg, *key;
420 _Py_IDENTIFIER(reason);
421 _Py_IDENTIFIER(library);
422
423 if (errcode != 0) {
424 int lib, reason;
425
426 lib = ERR_GET_LIB(errcode);
427 reason = ERR_GET_REASON(errcode);
428 key = Py_BuildValue("ii", lib, reason);
429 if (key == NULL)
430 goto fail;
431 reason_obj = PyDict_GetItem(err_codes_to_names, key);
432 Py_DECREF(key);
433 if (reason_obj == NULL) {
434 /* XXX if reason < 100, it might reflect a library number (!!) */
435 PyErr_Clear();
436 }
437 key = PyLong_FromLong(lib);
438 if (key == NULL)
439 goto fail;
440 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
441 Py_DECREF(key);
442 if (lib_obj == NULL) {
443 PyErr_Clear();
444 }
445 if (errstr == NULL)
446 errstr = ERR_reason_error_string(errcode);
447 }
448 if (errstr == NULL)
449 errstr = "unknown error";
450
451 if (reason_obj && lib_obj)
452 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
453 lib_obj, reason_obj, errstr, lineno);
454 else if (lib_obj)
455 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
456 lib_obj, errstr, lineno);
457 else
458 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200459 if (msg == NULL)
460 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100461
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200462 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100463 if (init_value == NULL)
464 goto fail;
465
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200466 err_value = PyObject_CallObject(type, init_value);
467 Py_DECREF(init_value);
468 if (err_value == NULL)
469 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100470
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200471 if (reason_obj == NULL)
472 reason_obj = Py_None;
473 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
474 goto fail;
475 if (lib_obj == NULL)
476 lib_obj = Py_None;
477 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
478 goto fail;
479 PyErr_SetObject(type, err_value);
480fail:
481 Py_XDECREF(err_value);
482}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000483
484static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200485PySSL_SetError(PySSLSocket *obj, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000486{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200487 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200488 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000489 int err;
490 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200491 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000492
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000493 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200494 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000495
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000496 if (obj->ssl != NULL) {
497 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000498
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000499 switch (err) {
500 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200501 errstr = "TLS/SSL connection has been closed (EOF)";
502 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000503 p = PY_SSL_ERROR_ZERO_RETURN;
504 break;
505 case SSL_ERROR_WANT_READ:
506 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200507 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000508 p = PY_SSL_ERROR_WANT_READ;
509 break;
510 case SSL_ERROR_WANT_WRITE:
511 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200512 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000513 errstr = "The operation did not complete (write)";
514 break;
515 case SSL_ERROR_WANT_X509_LOOKUP:
516 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000517 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 break;
519 case SSL_ERROR_WANT_CONNECT:
520 p = PY_SSL_ERROR_WANT_CONNECT;
521 errstr = "The operation did not complete (connect)";
522 break;
523 case SSL_ERROR_SYSCALL:
524 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000525 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200526 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000527 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000528 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200529 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000530 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200531 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000532 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000533 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000534 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200535 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000536 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200537 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000538 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000539 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200540 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000541 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000542 }
543 } else {
544 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000545 }
546 break;
547 }
548 case SSL_ERROR_SSL:
549 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000550 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200551 if (e == 0)
552 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000553 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000554 break;
555 }
556 default:
557 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
558 errstr = "Invalid error code";
559 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000560 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200561 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000562 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000563 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000564}
565
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000566static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200567_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000568
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200569 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000570 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200571 else
572 errcode = 0;
573 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000574 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000575 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000576}
577
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200578/*
579 * SSL objects
580 */
581
Antoine Pitrou152efa22010-05-16 18:19:27 +0000582static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100583newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000584 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200585 char *server_hostname,
586 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000587{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000588 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100589 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200590 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000591
Antoine Pitrou152efa22010-05-16 18:19:27 +0000592 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000593 if (self == NULL)
594 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000596 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000597 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100598 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200599 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200600 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700601 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200602 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700603 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
604 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200605 if (hostname == NULL) {
606 Py_DECREF(self);
607 return NULL;
608 }
609 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700610 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200611
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100612 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000613
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000614 /* Make sure the SSL error state is initialized */
615 (void) ERR_get_state();
616 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000619 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000620 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200621 SSL_set_app_data(self->ssl, self);
622 if (sock) {
623 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
624 } else {
625 /* BIOs are reference counted and SSL_set_bio borrows our reference.
626 * To prevent a double free in memory_bio_dealloc() we need to take an
627 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200628 BIO_up_ref(inbio->bio);
629 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200630 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
631 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200632 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000633#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200634 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000635#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200636 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000637
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100638#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000639 if (server_hostname != NULL)
640 SSL_set_tlsext_host_name(self->ssl, server_hostname);
641#endif
642
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000643 /* If the socket is in non-blocking mode or timeout mode, set the BIO
644 * to non-blocking mode (blocking is the default)
645 */
Victor Stinnere2452312015-03-28 03:00:46 +0100646 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000647 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
648 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
649 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000650
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000651 PySSL_BEGIN_ALLOW_THREADS
652 if (socket_type == PY_SSL_CLIENT)
653 SSL_set_connect_state(self->ssl);
654 else
655 SSL_set_accept_state(self->ssl);
656 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000657
Antoine Pitroud6494802011-07-21 01:11:30 +0200658 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200659 if (sock != NULL) {
660 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
661 if (self->Socket == NULL) {
662 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200663 return NULL;
664 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100665 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000667}
668
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000669/* SSL object methods */
670
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300671/*[clinic input]
672_ssl._SSLSocket.do_handshake
673[clinic start generated code]*/
674
675static PyObject *
676_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
677/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000678{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000679 int ret;
680 int err;
681 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200682 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200683 _PyTime_t timeout, deadline = 0;
684 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000685
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200686 if (sock) {
687 if (((PyObject*)sock) == Py_None) {
688 _setSSLError("Underlying socket connection gone",
689 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
690 return NULL;
691 }
692 Py_INCREF(sock);
693
694 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100695 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200696 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
697 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000698 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000699
Victor Stinner14690702015-04-06 22:46:13 +0200700 timeout = GET_SOCKET_TIMEOUT(sock);
701 has_timeout = (timeout > 0);
702 if (has_timeout)
703 deadline = _PyTime_GetMonotonicClock() + timeout;
704
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000705 /* Actually negotiate SSL connection */
706 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000708 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000709 ret = SSL_do_handshake(self->ssl);
710 err = SSL_get_error(self->ssl, ret);
711 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200712
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000713 if (PyErr_CheckSignals())
714 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200715
Victor Stinner14690702015-04-06 22:46:13 +0200716 if (has_timeout)
717 timeout = deadline - _PyTime_GetMonotonicClock();
718
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000719 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200720 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000721 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200722 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 } else {
724 sockstate = SOCKET_OPERATION_OK;
725 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200726
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000727 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000728 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000729 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000730 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000731 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
732 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000733 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000734 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
736 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000737 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000738 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000739 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
740 break;
741 }
742 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200743 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000744 if (ret < 1)
745 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000746
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200747 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000748
749error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200750 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000751 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000752}
753
Thomas Woutersed03b412007-08-28 21:37:11 +0000754static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000755_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000756
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000757 char namebuf[X509_NAME_MAXLEN];
758 int buflen;
759 PyObject *name_obj;
760 PyObject *value_obj;
761 PyObject *attr;
762 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000763
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000764 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
765 if (buflen < 0) {
766 _setSSLError(NULL, 0, __FILE__, __LINE__);
767 goto fail;
768 }
769 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
770 if (name_obj == NULL)
771 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000772
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000773 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
774 if (buflen < 0) {
775 _setSSLError(NULL, 0, __FILE__, __LINE__);
776 Py_DECREF(name_obj);
777 goto fail;
778 }
779 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000780 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000781 OPENSSL_free(valuebuf);
782 if (value_obj == NULL) {
783 Py_DECREF(name_obj);
784 goto fail;
785 }
786 attr = PyTuple_New(2);
787 if (attr == NULL) {
788 Py_DECREF(name_obj);
789 Py_DECREF(value_obj);
790 goto fail;
791 }
792 PyTuple_SET_ITEM(attr, 0, name_obj);
793 PyTuple_SET_ITEM(attr, 1, value_obj);
794 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000795
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000796 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000798}
799
800static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000801_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000802{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
804 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
805 PyObject *rdnt;
806 PyObject *attr = NULL; /* tuple to hold an attribute */
807 int entry_count = X509_NAME_entry_count(xname);
808 X509_NAME_ENTRY *entry;
809 ASN1_OBJECT *name;
810 ASN1_STRING *value;
811 int index_counter;
812 int rdn_level = -1;
813 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000814
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000815 dn = PyList_New(0);
816 if (dn == NULL)
817 return NULL;
818 /* now create another tuple to hold the top-level RDN */
819 rdn = PyList_New(0);
820 if (rdn == NULL)
821 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000822
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000823 for (index_counter = 0;
824 index_counter < entry_count;
825 index_counter++)
826 {
827 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000829 /* check to see if we've gotten to a new RDN */
830 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200831 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 /* yes, new RDN */
833 /* add old RDN to DN */
834 rdnt = PyList_AsTuple(rdn);
835 Py_DECREF(rdn);
836 if (rdnt == NULL)
837 goto fail0;
838 retcode = PyList_Append(dn, rdnt);
839 Py_DECREF(rdnt);
840 if (retcode < 0)
841 goto fail0;
842 /* create new RDN */
843 rdn = PyList_New(0);
844 if (rdn == NULL)
845 goto fail0;
846 }
847 }
Christian Heimes598894f2016-09-05 23:19:05 +0200848 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000849
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000850 /* now add this attribute to the current RDN */
851 name = X509_NAME_ENTRY_get_object(entry);
852 value = X509_NAME_ENTRY_get_data(entry);
853 attr = _create_tuple_for_attribute(name, value);
854 /*
855 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
856 entry->set,
857 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
858 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
859 */
860 if (attr == NULL)
861 goto fail1;
862 retcode = PyList_Append(rdn, attr);
863 Py_DECREF(attr);
864 if (retcode < 0)
865 goto fail1;
866 }
867 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100868 if (rdn != NULL) {
869 if (PyList_GET_SIZE(rdn) > 0) {
870 rdnt = PyList_AsTuple(rdn);
871 Py_DECREF(rdn);
872 if (rdnt == NULL)
873 goto fail0;
874 retcode = PyList_Append(dn, rdnt);
875 Py_DECREF(rdnt);
876 if (retcode < 0)
877 goto fail0;
878 }
879 else {
880 Py_DECREF(rdn);
881 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000882 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000883
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000884 /* convert list to tuple */
885 rdnt = PyList_AsTuple(dn);
886 Py_DECREF(dn);
887 if (rdnt == NULL)
888 return NULL;
889 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890
891 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000892 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000893
894 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000895 Py_XDECREF(dn);
896 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000897}
898
899static PyObject *
900_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000901
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 /* this code follows the procedure outlined in
903 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
904 function to extract the STACK_OF(GENERAL_NAME),
905 then iterates through the stack to add the
906 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000907
Alex Gaynorb87c0df2017-06-06 07:53:11 -0400908 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000909 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200910 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000911 GENERAL_NAMES *names = NULL;
912 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000913 BIO *biobuf = NULL;
914 char buf[2048];
915 char *vptr;
916 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000917
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000918 if (certificate == NULL)
919 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000920
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000921 /* get a memory buffer */
922 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923
Alex Gaynorb87c0df2017-06-06 07:53:11 -0400924 names = (GENERAL_NAMES *)X509_get_ext_d2i(
925 certificate, NID_subject_alt_name, NULL, NULL);
926 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000927 if (peer_alt_names == Py_None) {
928 peer_alt_names = PyList_New(0);
929 if (peer_alt_names == NULL)
930 goto fail;
931 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000932
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200935 int gntype;
936 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000937
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200939 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200940 switch (gntype) {
941 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 /* we special-case DirName as a tuple of
943 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000944
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 t = PyTuple_New(2);
946 if (t == NULL) {
947 goto fail;
948 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000949
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000950 v = PyUnicode_FromString("DirName");
951 if (v == NULL) {
952 Py_DECREF(t);
953 goto fail;
954 }
955 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000956
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 v = _create_tuple_for_X509_NAME (name->d.dirn);
958 if (v == NULL) {
959 Py_DECREF(t);
960 goto fail;
961 }
962 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200963 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000964
Christian Heimes824f7f32013-08-17 00:54:47 +0200965 case GEN_EMAIL:
966 case GEN_DNS:
967 case GEN_URI:
968 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
969 correctly, CVE-2013-4238 */
970 t = PyTuple_New(2);
971 if (t == NULL)
972 goto fail;
973 switch (gntype) {
974 case GEN_EMAIL:
975 v = PyUnicode_FromString("email");
976 as = name->d.rfc822Name;
977 break;
978 case GEN_DNS:
979 v = PyUnicode_FromString("DNS");
980 as = name->d.dNSName;
981 break;
982 case GEN_URI:
983 v = PyUnicode_FromString("URI");
984 as = name->d.uniformResourceIdentifier;
985 break;
986 }
987 if (v == NULL) {
988 Py_DECREF(t);
989 goto fail;
990 }
991 PyTuple_SET_ITEM(t, 0, v);
992 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
993 ASN1_STRING_length(as));
994 if (v == NULL) {
995 Py_DECREF(t);
996 goto fail;
997 }
998 PyTuple_SET_ITEM(t, 1, v);
999 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001000
Christian Heimes1c03abd2016-09-06 23:25:35 +02001001 case GEN_RID:
1002 t = PyTuple_New(2);
1003 if (t == NULL)
1004 goto fail;
1005
1006 v = PyUnicode_FromString("Registered ID");
1007 if (v == NULL) {
1008 Py_DECREF(t);
1009 goto fail;
1010 }
1011 PyTuple_SET_ITEM(t, 0, v);
1012
1013 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1014 if (len < 0) {
1015 Py_DECREF(t);
1016 _setSSLError(NULL, 0, __FILE__, __LINE__);
1017 goto fail;
1018 } else if (len >= (int)sizeof(buf)) {
1019 v = PyUnicode_FromString("<INVALID>");
1020 } else {
1021 v = PyUnicode_FromStringAndSize(buf, len);
1022 }
1023 if (v == NULL) {
1024 Py_DECREF(t);
1025 goto fail;
1026 }
1027 PyTuple_SET_ITEM(t, 1, v);
1028 break;
1029
Christian Heimes824f7f32013-08-17 00:54:47 +02001030 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001031 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001032 switch (gntype) {
1033 /* check for new general name type */
1034 case GEN_OTHERNAME:
1035 case GEN_X400:
1036 case GEN_EDIPARTY:
1037 case GEN_IPADD:
1038 case GEN_RID:
1039 break;
1040 default:
1041 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1042 "Unknown general name type %d",
1043 gntype) == -1) {
1044 goto fail;
1045 }
1046 break;
1047 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001048 (void) BIO_reset(biobuf);
1049 GENERAL_NAME_print(biobuf, name);
1050 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1051 if (len < 0) {
1052 _setSSLError(NULL, 0, __FILE__, __LINE__);
1053 goto fail;
1054 }
1055 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001056 if (vptr == NULL) {
1057 PyErr_Format(PyExc_ValueError,
1058 "Invalid value %.200s",
1059 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001060 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001061 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001062 t = PyTuple_New(2);
1063 if (t == NULL)
1064 goto fail;
1065 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1066 if (v == NULL) {
1067 Py_DECREF(t);
1068 goto fail;
1069 }
1070 PyTuple_SET_ITEM(t, 0, v);
1071 v = PyUnicode_FromStringAndSize((vptr + 1),
1072 (len - (vptr - buf + 1)));
1073 if (v == NULL) {
1074 Py_DECREF(t);
1075 goto fail;
1076 }
1077 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001078 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001079 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001080
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001082
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001083 if (PyList_Append(peer_alt_names, t) < 0) {
1084 Py_DECREF(t);
1085 goto fail;
1086 }
1087 Py_DECREF(t);
1088 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001089 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001090 }
1091 BIO_free(biobuf);
1092 if (peer_alt_names != Py_None) {
1093 v = PyList_AsTuple(peer_alt_names);
1094 Py_DECREF(peer_alt_names);
1095 return v;
1096 } else {
1097 return peer_alt_names;
1098 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001099
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001100
1101 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001102 if (biobuf != NULL)
1103 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001104
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 if (peer_alt_names != Py_None) {
1106 Py_XDECREF(peer_alt_names);
1107 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001108
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001110}
1111
1112static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001113_get_aia_uri(X509 *certificate, int nid) {
1114 PyObject *lst = NULL, *ostr = NULL;
1115 int i, result;
1116 AUTHORITY_INFO_ACCESS *info;
1117
1118 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001119 if (info == NULL)
1120 return Py_None;
1121 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1122 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001123 return Py_None;
1124 }
1125
1126 if ((lst = PyList_New(0)) == NULL) {
1127 goto fail;
1128 }
1129
1130 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1131 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1132 ASN1_IA5STRING *uri;
1133
1134 if ((OBJ_obj2nid(ad->method) != nid) ||
1135 (ad->location->type != GEN_URI)) {
1136 continue;
1137 }
1138 uri = ad->location->d.uniformResourceIdentifier;
1139 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1140 uri->length);
1141 if (ostr == NULL) {
1142 goto fail;
1143 }
1144 result = PyList_Append(lst, ostr);
1145 Py_DECREF(ostr);
1146 if (result < 0) {
1147 goto fail;
1148 }
1149 }
1150 AUTHORITY_INFO_ACCESS_free(info);
1151
1152 /* convert to tuple or None */
1153 if (PyList_Size(lst) == 0) {
1154 Py_DECREF(lst);
1155 return Py_None;
1156 } else {
1157 PyObject *tup;
1158 tup = PyList_AsTuple(lst);
1159 Py_DECREF(lst);
1160 return tup;
1161 }
1162
1163 fail:
1164 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001165 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001166 return NULL;
1167}
1168
1169static PyObject *
1170_get_crl_dp(X509 *certificate) {
1171 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001172 int i, j;
1173 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001174
Christian Heimes598894f2016-09-05 23:19:05 +02001175 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001176
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001177 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001178 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001179
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001180 lst = PyList_New(0);
1181 if (lst == NULL)
1182 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001183
1184 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1185 DIST_POINT *dp;
1186 STACK_OF(GENERAL_NAME) *gns;
1187
1188 dp = sk_DIST_POINT_value(dps, i);
1189 gns = dp->distpoint->name.fullname;
1190
1191 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1192 GENERAL_NAME *gn;
1193 ASN1_IA5STRING *uri;
1194 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001195 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001196
1197 gn = sk_GENERAL_NAME_value(gns, j);
1198 if (gn->type != GEN_URI) {
1199 continue;
1200 }
1201 uri = gn->d.uniformResourceIdentifier;
1202 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1203 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001204 if (ouri == NULL)
1205 goto done;
1206
1207 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001208 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001209 if (err < 0)
1210 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001211 }
1212 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001213
1214 /* Convert to tuple. */
1215 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1216
1217 done:
1218 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001219 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001220 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001221}
1222
1223static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001224_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001225
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001226 PyObject *retval = NULL;
1227 BIO *biobuf = NULL;
1228 PyObject *peer;
1229 PyObject *peer_alt_names = NULL;
1230 PyObject *issuer;
1231 PyObject *version;
1232 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001233 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001234 ASN1_INTEGER *serialNumber;
1235 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001236 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001237 ASN1_TIME *notBefore, *notAfter;
1238 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001239
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001240 retval = PyDict_New();
1241 if (retval == NULL)
1242 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001243
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001244 peer = _create_tuple_for_X509_NAME(
1245 X509_get_subject_name(certificate));
1246 if (peer == NULL)
1247 goto fail0;
1248 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1249 Py_DECREF(peer);
1250 goto fail0;
1251 }
1252 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001253
Antoine Pitroufb046912010-11-09 20:21:19 +00001254 issuer = _create_tuple_for_X509_NAME(
1255 X509_get_issuer_name(certificate));
1256 if (issuer == NULL)
1257 goto fail0;
1258 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001259 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001260 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001261 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001262 Py_DECREF(issuer);
1263
1264 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001265 if (version == NULL)
1266 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001267 if (PyDict_SetItemString(retval, "version", version) < 0) {
1268 Py_DECREF(version);
1269 goto fail0;
1270 }
1271 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001272
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001273 /* get a memory buffer */
1274 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001275
Antoine Pitroufb046912010-11-09 20:21:19 +00001276 (void) BIO_reset(biobuf);
1277 serialNumber = X509_get_serialNumber(certificate);
1278 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1279 i2a_ASN1_INTEGER(biobuf, serialNumber);
1280 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1281 if (len < 0) {
1282 _setSSLError(NULL, 0, __FILE__, __LINE__);
1283 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001284 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001285 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1286 if (sn_obj == NULL)
1287 goto fail1;
1288 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1289 Py_DECREF(sn_obj);
1290 goto fail1;
1291 }
1292 Py_DECREF(sn_obj);
1293
1294 (void) BIO_reset(biobuf);
1295 notBefore = X509_get_notBefore(certificate);
1296 ASN1_TIME_print(biobuf, notBefore);
1297 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1298 if (len < 0) {
1299 _setSSLError(NULL, 0, __FILE__, __LINE__);
1300 goto fail1;
1301 }
1302 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1303 if (pnotBefore == NULL)
1304 goto fail1;
1305 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1306 Py_DECREF(pnotBefore);
1307 goto fail1;
1308 }
1309 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001310
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001311 (void) BIO_reset(biobuf);
1312 notAfter = X509_get_notAfter(certificate);
1313 ASN1_TIME_print(biobuf, notAfter);
1314 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1315 if (len < 0) {
1316 _setSSLError(NULL, 0, __FILE__, __LINE__);
1317 goto fail1;
1318 }
1319 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1320 if (pnotAfter == NULL)
1321 goto fail1;
1322 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1323 Py_DECREF(pnotAfter);
1324 goto fail1;
1325 }
1326 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001327
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001328 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001329
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 peer_alt_names = _get_peer_alt_names(certificate);
1331 if (peer_alt_names == NULL)
1332 goto fail1;
1333 else if (peer_alt_names != Py_None) {
1334 if (PyDict_SetItemString(retval, "subjectAltName",
1335 peer_alt_names) < 0) {
1336 Py_DECREF(peer_alt_names);
1337 goto fail1;
1338 }
1339 Py_DECREF(peer_alt_names);
1340 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001341
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001342 /* Authority Information Access: OCSP URIs */
1343 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1344 if (obj == NULL) {
1345 goto fail1;
1346 } else if (obj != Py_None) {
1347 result = PyDict_SetItemString(retval, "OCSP", obj);
1348 Py_DECREF(obj);
1349 if (result < 0) {
1350 goto fail1;
1351 }
1352 }
1353
1354 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1355 if (obj == NULL) {
1356 goto fail1;
1357 } else if (obj != Py_None) {
1358 result = PyDict_SetItemString(retval, "caIssuers", obj);
1359 Py_DECREF(obj);
1360 if (result < 0) {
1361 goto fail1;
1362 }
1363 }
1364
1365 /* CDP (CRL distribution points) */
1366 obj = _get_crl_dp(certificate);
1367 if (obj == NULL) {
1368 goto fail1;
1369 } else if (obj != Py_None) {
1370 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1371 Py_DECREF(obj);
1372 if (result < 0) {
1373 goto fail1;
1374 }
1375 }
1376
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001377 BIO_free(biobuf);
1378 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001379
1380 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001381 if (biobuf != NULL)
1382 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001383 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001384 Py_XDECREF(retval);
1385 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001386}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001387
Christian Heimes9a5395a2013-06-17 15:44:12 +02001388static PyObject *
1389_certificate_to_der(X509 *certificate)
1390{
1391 unsigned char *bytes_buf = NULL;
1392 int len;
1393 PyObject *retval;
1394
1395 bytes_buf = NULL;
1396 len = i2d_X509(certificate, &bytes_buf);
1397 if (len < 0) {
1398 _setSSLError(NULL, 0, __FILE__, __LINE__);
1399 return NULL;
1400 }
1401 /* this is actually an immutable bytes sequence */
1402 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1403 OPENSSL_free(bytes_buf);
1404 return retval;
1405}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001406
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001407/*[clinic input]
1408_ssl._test_decode_cert
1409 path: object(converter="PyUnicode_FSConverter")
1410 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001411
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001412[clinic start generated code]*/
1413
1414static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001415_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1416/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001417{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001418 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001419 X509 *x=NULL;
1420 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001421
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001422 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1423 PyErr_SetString(PySSLErrorObject,
1424 "Can't malloc memory to read file");
1425 goto fail0;
1426 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001427
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001428 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001429 PyErr_SetString(PySSLErrorObject,
1430 "Can't open file");
1431 goto fail0;
1432 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001433
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001434 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1435 if (x == NULL) {
1436 PyErr_SetString(PySSLErrorObject,
1437 "Error decoding PEM-encoded file");
1438 goto fail0;
1439 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001440
Antoine Pitroufb046912010-11-09 20:21:19 +00001441 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001442 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001443
1444 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001445 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001446 if (cert != NULL) BIO_free(cert);
1447 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001448}
1449
1450
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001451/*[clinic input]
1452_ssl._SSLSocket.peer_certificate
1453 der as binary_mode: bool = False
1454 /
1455
1456Returns the certificate for the peer.
1457
1458If no certificate was provided, returns None. If a certificate was
1459provided, but not validated, returns an empty dictionary. Otherwise
1460returns a dict containing information about the peer certificate.
1461
1462If the optional argument is True, returns a DER-encoded copy of the
1463peer certificate, or None if no certificate was provided. This will
1464return the certificate even if it wasn't validated.
1465[clinic start generated code]*/
1466
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001467static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001468_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1469/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001470{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001471 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001472 X509 *peer_cert;
1473 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001474
Christian Heimes66dc33b2017-05-23 16:02:02 -07001475 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001476 PyErr_SetString(PyExc_ValueError,
1477 "handshake not done yet");
1478 return NULL;
1479 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001480 peer_cert = SSL_get_peer_certificate(self->ssl);
1481 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001482 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001483
Antoine Pitrou721738f2012-08-15 23:20:39 +02001484 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001485 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001486 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001487 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001488 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001489 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001490 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001491 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001492 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001493 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001494 X509_free(peer_cert);
1495 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001496}
1497
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001498static PyObject *
1499cipher_to_tuple(const SSL_CIPHER *cipher)
1500{
1501 const char *cipher_name, *cipher_protocol;
1502 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001503 if (retval == NULL)
1504 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001505
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001506 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001507 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001508 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001509 PyTuple_SET_ITEM(retval, 0, Py_None);
1510 } else {
1511 v = PyUnicode_FromString(cipher_name);
1512 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001513 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001514 PyTuple_SET_ITEM(retval, 0, v);
1515 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001516
1517 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001518 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001519 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001520 PyTuple_SET_ITEM(retval, 1, Py_None);
1521 } else {
1522 v = PyUnicode_FromString(cipher_protocol);
1523 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001524 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001525 PyTuple_SET_ITEM(retval, 1, v);
1526 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001527
1528 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001529 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001530 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001531 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001532
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001533 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001534
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001535 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001536 Py_DECREF(retval);
1537 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001538}
1539
Christian Heimes25bfcd52016-09-06 00:04:45 +02001540#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1541static PyObject *
1542cipher_to_dict(const SSL_CIPHER *cipher)
1543{
1544 const char *cipher_name, *cipher_protocol;
1545
1546 unsigned long cipher_id;
1547 int alg_bits, strength_bits, len;
1548 char buf[512] = {0};
1549#if OPENSSL_VERSION_1_1
1550 int aead, nid;
1551 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1552#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001553
1554 /* can be NULL */
1555 cipher_name = SSL_CIPHER_get_name(cipher);
1556 cipher_protocol = SSL_CIPHER_get_version(cipher);
1557 cipher_id = SSL_CIPHER_get_id(cipher);
1558 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1559 len = strlen(buf);
1560 if (len > 1 && buf[len-1] == '\n')
1561 buf[len-1] = '\0';
1562 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1563
1564#if OPENSSL_VERSION_1_1
1565 aead = SSL_CIPHER_is_aead(cipher);
1566 nid = SSL_CIPHER_get_cipher_nid(cipher);
1567 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1568 nid = SSL_CIPHER_get_digest_nid(cipher);
1569 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1570 nid = SSL_CIPHER_get_kx_nid(cipher);
1571 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1572 nid = SSL_CIPHER_get_auth_nid(cipher);
1573 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1574#endif
1575
Victor Stinner410b9882016-09-12 12:00:23 +02001576 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001577 "{sksssssssisi"
1578#if OPENSSL_VERSION_1_1
1579 "sOssssssss"
1580#endif
1581 "}",
1582 "id", cipher_id,
1583 "name", cipher_name,
1584 "protocol", cipher_protocol,
1585 "description", buf,
1586 "strength_bits", strength_bits,
1587 "alg_bits", alg_bits
1588#if OPENSSL_VERSION_1_1
1589 ,"aead", aead ? Py_True : Py_False,
1590 "symmetric", skcipher,
1591 "digest", digest,
1592 "kea", kx,
1593 "auth", auth
1594#endif
1595 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001596}
1597#endif
1598
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001599/*[clinic input]
1600_ssl._SSLSocket.shared_ciphers
1601[clinic start generated code]*/
1602
1603static PyObject *
1604_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1605/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001606{
1607 STACK_OF(SSL_CIPHER) *ciphers;
1608 int i;
1609 PyObject *res;
1610
Christian Heimes598894f2016-09-05 23:19:05 +02001611 ciphers = SSL_get_ciphers(self->ssl);
1612 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001613 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001614 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1615 if (!res)
1616 return NULL;
1617 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1618 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1619 if (!tup) {
1620 Py_DECREF(res);
1621 return NULL;
1622 }
1623 PyList_SET_ITEM(res, i, tup);
1624 }
1625 return res;
1626}
1627
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001628/*[clinic input]
1629_ssl._SSLSocket.cipher
1630[clinic start generated code]*/
1631
1632static PyObject *
1633_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1634/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001635{
1636 const SSL_CIPHER *current;
1637
1638 if (self->ssl == NULL)
1639 Py_RETURN_NONE;
1640 current = SSL_get_current_cipher(self->ssl);
1641 if (current == NULL)
1642 Py_RETURN_NONE;
1643 return cipher_to_tuple(current);
1644}
1645
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001646/*[clinic input]
1647_ssl._SSLSocket.version
1648[clinic start generated code]*/
1649
1650static PyObject *
1651_ssl__SSLSocket_version_impl(PySSLSocket *self)
1652/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001653{
1654 const char *version;
1655
1656 if (self->ssl == NULL)
1657 Py_RETURN_NONE;
1658 version = SSL_get_version(self->ssl);
1659 if (!strcmp(version, "unknown"))
1660 Py_RETURN_NONE;
1661 return PyUnicode_FromString(version);
1662}
1663
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001664#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001665/*[clinic input]
1666_ssl._SSLSocket.selected_npn_protocol
1667[clinic start generated code]*/
1668
1669static PyObject *
1670_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1671/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1672{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001673 const unsigned char *out;
1674 unsigned int outlen;
1675
Victor Stinner4569cd52013-06-23 14:58:43 +02001676 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001677 &out, &outlen);
1678
1679 if (out == NULL)
1680 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001681 return PyUnicode_FromStringAndSize((char *)out, outlen);
1682}
1683#endif
1684
1685#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001686/*[clinic input]
1687_ssl._SSLSocket.selected_alpn_protocol
1688[clinic start generated code]*/
1689
1690static PyObject *
1691_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1692/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1693{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001694 const unsigned char *out;
1695 unsigned int outlen;
1696
1697 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1698
1699 if (out == NULL)
1700 Py_RETURN_NONE;
1701 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001702}
1703#endif
1704
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001705/*[clinic input]
1706_ssl._SSLSocket.compression
1707[clinic start generated code]*/
1708
1709static PyObject *
1710_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1711/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1712{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001713#ifdef OPENSSL_NO_COMP
1714 Py_RETURN_NONE;
1715#else
1716 const COMP_METHOD *comp_method;
1717 const char *short_name;
1718
1719 if (self->ssl == NULL)
1720 Py_RETURN_NONE;
1721 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001722 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001723 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001724 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001725 if (short_name == NULL)
1726 Py_RETURN_NONE;
1727 return PyUnicode_DecodeFSDefault(short_name);
1728#endif
1729}
1730
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001731static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1732 Py_INCREF(self->ctx);
1733 return self->ctx;
1734}
1735
1736static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1737 void *closure) {
1738
1739 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001740#if !HAVE_SNI
1741 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1742 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001743 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001744#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001745 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001746 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001747 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001748#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001749 } else {
1750 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1751 return -1;
1752 }
1753
1754 return 0;
1755}
1756
1757PyDoc_STRVAR(PySSL_set_context_doc,
1758"_setter_context(ctx)\n\
1759\
1760This changes the context associated with the SSLSocket. This is typically\n\
1761used from within a callback function set by the set_servername_callback\n\
1762on the SSLContext to change the certificate information associated with the\n\
1763SSLSocket before the cryptographic exchange handshake messages\n");
1764
1765
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001766static PyObject *
1767PySSL_get_server_side(PySSLSocket *self, void *c)
1768{
1769 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1770}
1771
1772PyDoc_STRVAR(PySSL_get_server_side_doc,
1773"Whether this is a server-side socket.");
1774
1775static PyObject *
1776PySSL_get_server_hostname(PySSLSocket *self, void *c)
1777{
1778 if (self->server_hostname == NULL)
1779 Py_RETURN_NONE;
1780 Py_INCREF(self->server_hostname);
1781 return self->server_hostname;
1782}
1783
1784PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1785"The currently set server hostname (for SNI).");
1786
1787static PyObject *
1788PySSL_get_owner(PySSLSocket *self, void *c)
1789{
1790 PyObject *owner;
1791
1792 if (self->owner == NULL)
1793 Py_RETURN_NONE;
1794
1795 owner = PyWeakref_GetObject(self->owner);
1796 Py_INCREF(owner);
1797 return owner;
1798}
1799
1800static int
1801PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1802{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001803 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001804 if (self->owner == NULL)
1805 return -1;
1806 return 0;
1807}
1808
1809PyDoc_STRVAR(PySSL_get_owner_doc,
1810"The Python-level owner of this object.\
1811Passed as \"self\" in servername callback.");
1812
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001813
Antoine Pitrou152efa22010-05-16 18:19:27 +00001814static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001815{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001816 if (self->ssl)
1817 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001818 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001819 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001820 Py_XDECREF(self->server_hostname);
1821 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001822 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001823}
1824
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001825/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001826 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001827 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001828 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001829
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001830static int
Victor Stinner14690702015-04-06 22:46:13 +02001831PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001832{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001833 int rc;
1834#ifdef HAVE_POLL
1835 struct pollfd pollfd;
1836 _PyTime_t ms;
1837#else
1838 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001839 fd_set fds;
1840 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001841#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001842
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001843 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001844 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001845 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001846 else if (timeout < 0) {
1847 if (s->sock_timeout > 0)
1848 return SOCKET_HAS_TIMED_OUT;
1849 else
1850 return SOCKET_IS_BLOCKING;
1851 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001852
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001853 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001854 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001855 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001856
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001857 /* Prefer poll, if available, since you can poll() any fd
1858 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001859#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001860 pollfd.fd = s->sock_fd;
1861 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001862
Victor Stinner14690702015-04-06 22:46:13 +02001863 /* timeout is in seconds, poll() uses milliseconds */
1864 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001865 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001866
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001867 PySSL_BEGIN_ALLOW_THREADS
1868 rc = poll(&pollfd, 1, (int)ms);
1869 PySSL_END_ALLOW_THREADS
1870#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001871 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001872 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001873 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001874
Victor Stinner14690702015-04-06 22:46:13 +02001875 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001876
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001877 FD_ZERO(&fds);
1878 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001879
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001880 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001881 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001882 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001883 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001884 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001885 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001886 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001887 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001888#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001889
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001890 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1891 (when we are able to write or when there's something to read) */
1892 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001893}
1894
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001895/*[clinic input]
1896_ssl._SSLSocket.write
1897 b: Py_buffer
1898 /
1899
1900Writes the bytes-like object b into the SSL object.
1901
1902Returns the number of bytes written.
1903[clinic start generated code]*/
1904
1905static PyObject *
1906_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1907/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001908{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001909 int len;
1910 int sockstate;
1911 int err;
1912 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001913 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001914 _PyTime_t timeout, deadline = 0;
1915 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001916
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001917 if (sock != NULL) {
1918 if (((PyObject*)sock) == Py_None) {
1919 _setSSLError("Underlying socket connection gone",
1920 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1921 return NULL;
1922 }
1923 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001924 }
1925
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001926 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001927 PyErr_Format(PyExc_OverflowError,
1928 "string longer than %d bytes", INT_MAX);
1929 goto error;
1930 }
1931
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001932 if (sock != NULL) {
1933 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001934 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001935 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1936 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1937 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001938
Victor Stinner14690702015-04-06 22:46:13 +02001939 timeout = GET_SOCKET_TIMEOUT(sock);
1940 has_timeout = (timeout > 0);
1941 if (has_timeout)
1942 deadline = _PyTime_GetMonotonicClock() + timeout;
1943
1944 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001945 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001946 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001947 "The write operation timed out");
1948 goto error;
1949 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1950 PyErr_SetString(PySSLErrorObject,
1951 "Underlying socket has been closed.");
1952 goto error;
1953 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1954 PyErr_SetString(PySSLErrorObject,
1955 "Underlying socket too large for select().");
1956 goto error;
1957 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001958
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001959 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001960 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001961 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001962 err = SSL_get_error(self->ssl, len);
1963 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001964
1965 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001966 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001967
Victor Stinner14690702015-04-06 22:46:13 +02001968 if (has_timeout)
1969 timeout = deadline - _PyTime_GetMonotonicClock();
1970
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001971 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001972 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001973 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001974 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001975 } else {
1976 sockstate = SOCKET_OPERATION_OK;
1977 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001978
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001979 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001980 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001981 "The write operation timed out");
1982 goto error;
1983 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1984 PyErr_SetString(PySSLErrorObject,
1985 "Underlying socket has been closed.");
1986 goto error;
1987 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1988 break;
1989 }
1990 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001991
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001992 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001993 if (len > 0)
1994 return PyLong_FromLong(len);
1995 else
1996 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001997
1998error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001999 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002000 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002001}
2002
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002003/*[clinic input]
2004_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002005
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002006Returns the number of already decrypted bytes available for read, pending on the connection.
2007[clinic start generated code]*/
2008
2009static PyObject *
2010_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2011/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002012{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002013 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002014
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002015 PySSL_BEGIN_ALLOW_THREADS
2016 count = SSL_pending(self->ssl);
2017 PySSL_END_ALLOW_THREADS
2018 if (count < 0)
2019 return PySSL_SetError(self, count, __FILE__, __LINE__);
2020 else
2021 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002022}
2023
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002024/*[clinic input]
2025_ssl._SSLSocket.read
2026 size as len: int
2027 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002028 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002029 ]
2030 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002031
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002032Read up to size bytes from the SSL socket.
2033[clinic start generated code]*/
2034
2035static PyObject *
2036_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2037 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002038/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002039{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002040 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002041 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002042 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002043 int sockstate;
2044 int err;
2045 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002046 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002047 _PyTime_t timeout, deadline = 0;
2048 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002049
Martin Panter5503d472016-03-27 05:35:19 +00002050 if (!group_right_1 && len < 0) {
2051 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2052 return NULL;
2053 }
2054
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002055 if (sock != NULL) {
2056 if (((PyObject*)sock) == Py_None) {
2057 _setSSLError("Underlying socket connection gone",
2058 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2059 return NULL;
2060 }
2061 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002062 }
2063
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002064 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002065 dest = PyBytes_FromStringAndSize(NULL, len);
2066 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002067 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002068 if (len == 0) {
2069 Py_XDECREF(sock);
2070 return dest;
2071 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002072 mem = PyBytes_AS_STRING(dest);
2073 }
2074 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002075 mem = buffer->buf;
2076 if (len <= 0 || len > buffer->len) {
2077 len = (int) buffer->len;
2078 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002079 PyErr_SetString(PyExc_OverflowError,
2080 "maximum length can't fit in a C 'int'");
2081 goto error;
2082 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002083 if (len == 0) {
2084 count = 0;
2085 goto done;
2086 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002087 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002088 }
2089
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002090 if (sock != NULL) {
2091 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002092 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002093 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2094 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2095 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002096
Victor Stinner14690702015-04-06 22:46:13 +02002097 timeout = GET_SOCKET_TIMEOUT(sock);
2098 has_timeout = (timeout > 0);
2099 if (has_timeout)
2100 deadline = _PyTime_GetMonotonicClock() + timeout;
2101
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002102 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002103 PySSL_BEGIN_ALLOW_THREADS
2104 count = SSL_read(self->ssl, mem, len);
2105 err = SSL_get_error(self->ssl, count);
2106 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002107
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002108 if (PyErr_CheckSignals())
2109 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002110
Victor Stinner14690702015-04-06 22:46:13 +02002111 if (has_timeout)
2112 timeout = deadline - _PyTime_GetMonotonicClock();
2113
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002114 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002115 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002116 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002117 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002118 } else if (err == SSL_ERROR_ZERO_RETURN &&
2119 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002120 {
2121 count = 0;
2122 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002123 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002124 else
2125 sockstate = SOCKET_OPERATION_OK;
2126
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002127 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002128 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002129 "The read operation timed out");
2130 goto error;
2131 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2132 break;
2133 }
2134 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002135
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002136 if (count <= 0) {
2137 PySSL_SetError(self, count, __FILE__, __LINE__);
2138 goto error;
2139 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002140
2141done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002142 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002143 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002144 _PyBytes_Resize(&dest, count);
2145 return dest;
2146 }
2147 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002148 return PyLong_FromLong(count);
2149 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002150
2151error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002152 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002153 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002154 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002155 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002156}
2157
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002158/*[clinic input]
2159_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002160
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002161Does the SSL shutdown handshake with the remote end.
2162
2163Returns the underlying socket object.
2164[clinic start generated code]*/
2165
2166static PyObject *
2167_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2168/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002169{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002170 int err, ssl_err, sockstate, nonblocking;
2171 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002172 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002173 _PyTime_t timeout, deadline = 0;
2174 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002175
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002176 if (sock != NULL) {
2177 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002178 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002179 _setSSLError("Underlying socket connection gone",
2180 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2181 return NULL;
2182 }
2183 Py_INCREF(sock);
2184
2185 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002186 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002187 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2188 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002189 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002190
Victor Stinner14690702015-04-06 22:46:13 +02002191 timeout = GET_SOCKET_TIMEOUT(sock);
2192 has_timeout = (timeout > 0);
2193 if (has_timeout)
2194 deadline = _PyTime_GetMonotonicClock() + timeout;
2195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002196 while (1) {
2197 PySSL_BEGIN_ALLOW_THREADS
2198 /* Disable read-ahead so that unwrap can work correctly.
2199 * Otherwise OpenSSL might read in too much data,
2200 * eating clear text data that happens to be
2201 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002202 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002203 * function is used and the shutdown_seen_zero != 0
2204 * condition is met.
2205 */
2206 if (self->shutdown_seen_zero)
2207 SSL_set_read_ahead(self->ssl, 0);
2208 err = SSL_shutdown(self->ssl);
2209 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002210
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002211 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2212 if (err > 0)
2213 break;
2214 if (err == 0) {
2215 /* Don't loop endlessly; instead preserve legacy
2216 behaviour of trying SSL_shutdown() only twice.
2217 This looks necessary for OpenSSL < 0.9.8m */
2218 if (++zeros > 1)
2219 break;
2220 /* Shutdown was sent, now try receiving */
2221 self->shutdown_seen_zero = 1;
2222 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002223 }
2224
Victor Stinner14690702015-04-06 22:46:13 +02002225 if (has_timeout)
2226 timeout = deadline - _PyTime_GetMonotonicClock();
2227
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002228 /* Possibly retry shutdown until timeout or failure */
2229 ssl_err = SSL_get_error(self->ssl, err);
2230 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002231 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002232 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002233 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002234 else
2235 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002236
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002237 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2238 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002239 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002240 "The read operation timed out");
2241 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002242 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002243 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002244 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002245 }
2246 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2247 PyErr_SetString(PySSLErrorObject,
2248 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002249 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002250 }
2251 else if (sockstate != SOCKET_OPERATION_OK)
2252 /* Retain the SSL error code */
2253 break;
2254 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002255
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002256 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002257 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002258 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002259 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002260 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002261 /* It's already INCREF'ed */
2262 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002263 else
2264 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002265
2266error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002267 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002268 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002269}
2270
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002271/*[clinic input]
2272_ssl._SSLSocket.tls_unique_cb
2273
2274Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2275
2276If the TLS handshake is not yet complete, None is returned.
2277[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002278
Antoine Pitroud6494802011-07-21 01:11:30 +02002279static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002280_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2281/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002282{
2283 PyObject *retval = NULL;
2284 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002285 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002286
2287 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2288 /* if session is resumed XOR we are the client */
2289 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2290 }
2291 else {
2292 /* if a new session XOR we are the server */
2293 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2294 }
2295
2296 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002297 if (len == 0)
2298 Py_RETURN_NONE;
2299
2300 retval = PyBytes_FromStringAndSize(buf, len);
2301
2302 return retval;
2303}
2304
Christian Heimes99a65702016-09-10 23:44:53 +02002305#ifdef OPENSSL_VERSION_1_1
2306
2307static SSL_SESSION*
2308_ssl_session_dup(SSL_SESSION *session) {
2309 SSL_SESSION *newsession = NULL;
2310 int slen;
2311 unsigned char *senc = NULL, *p;
2312 const unsigned char *const_p;
2313
2314 if (session == NULL) {
2315 PyErr_SetString(PyExc_ValueError, "Invalid session");
2316 goto error;
2317 }
2318
2319 /* get length */
2320 slen = i2d_SSL_SESSION(session, NULL);
2321 if (slen == 0 || slen > 0xFF00) {
2322 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2323 goto error;
2324 }
2325 if ((senc = PyMem_Malloc(slen)) == NULL) {
2326 PyErr_NoMemory();
2327 goto error;
2328 }
2329 p = senc;
2330 if (!i2d_SSL_SESSION(session, &p)) {
2331 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2332 goto error;
2333 }
2334 const_p = senc;
2335 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2336 if (session == NULL) {
2337 goto error;
2338 }
2339 PyMem_Free(senc);
2340 return newsession;
2341 error:
2342 if (senc != NULL) {
2343 PyMem_Free(senc);
2344 }
2345 return NULL;
2346}
2347#endif
2348
2349static PyObject *
2350PySSL_get_session(PySSLSocket *self, void *closure) {
2351 /* get_session can return sessions from a server-side connection,
2352 * it does not check for handshake done or client socket. */
2353 PySSLSession *pysess;
2354 SSL_SESSION *session;
2355
2356#ifdef OPENSSL_VERSION_1_1
2357 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2358 * https://github.com/openssl/openssl/issues/1550 */
2359 session = SSL_get0_session(self->ssl); /* borrowed reference */
2360 if (session == NULL) {
2361 Py_RETURN_NONE;
2362 }
2363 if ((session = _ssl_session_dup(session)) == NULL) {
2364 return NULL;
2365 }
2366#else
2367 session = SSL_get1_session(self->ssl);
2368 if (session == NULL) {
2369 Py_RETURN_NONE;
2370 }
2371#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002372 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002373 if (pysess == NULL) {
2374 SSL_SESSION_free(session);
2375 return NULL;
2376 }
2377
2378 assert(self->ctx);
2379 pysess->ctx = self->ctx;
2380 Py_INCREF(pysess->ctx);
2381 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002382 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002383 return (PyObject *)pysess;
2384}
2385
2386static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2387 void *closure)
2388 {
2389 PySSLSession *pysess;
2390#ifdef OPENSSL_VERSION_1_1
2391 SSL_SESSION *session;
2392#endif
2393 int result;
2394
2395 if (!PySSLSession_Check(value)) {
2396 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2397 return -1;
2398 }
2399 pysess = (PySSLSession *)value;
2400
2401 if (self->ctx->ctx != pysess->ctx->ctx) {
2402 PyErr_SetString(PyExc_ValueError,
2403 "Session refers to a different SSLContext.");
2404 return -1;
2405 }
2406 if (self->socket_type != PY_SSL_CLIENT) {
2407 PyErr_SetString(PyExc_ValueError,
2408 "Cannot set session for server-side SSLSocket.");
2409 return -1;
2410 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002411 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002412 PyErr_SetString(PyExc_ValueError,
2413 "Cannot set session after handshake.");
2414 return -1;
2415 }
2416#ifdef OPENSSL_VERSION_1_1
2417 /* duplicate session */
2418 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2419 return -1;
2420 }
2421 result = SSL_set_session(self->ssl, session);
2422 /* free duplicate, SSL_set_session() bumps ref count */
2423 SSL_SESSION_free(session);
2424#else
2425 result = SSL_set_session(self->ssl, pysess->session);
2426#endif
2427 if (result == 0) {
2428 _setSSLError(NULL, 0, __FILE__, __LINE__);
2429 return -1;
2430 }
2431 return 0;
2432}
2433
2434PyDoc_STRVAR(PySSL_set_session_doc,
2435"_setter_session(session)\n\
2436\
2437Get / set SSLSession.");
2438
2439static PyObject *
2440PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2441 if (SSL_session_reused(self->ssl)) {
2442 Py_RETURN_TRUE;
2443 } else {
2444 Py_RETURN_FALSE;
2445 }
2446}
2447
2448PyDoc_STRVAR(PySSL_get_session_reused_doc,
2449"Was the client session reused during handshake?");
2450
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002451static PyGetSetDef ssl_getsetlist[] = {
2452 {"context", (getter) PySSL_get_context,
2453 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002454 {"server_side", (getter) PySSL_get_server_side, NULL,
2455 PySSL_get_server_side_doc},
2456 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2457 PySSL_get_server_hostname_doc},
2458 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2459 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002460 {"session", (getter) PySSL_get_session,
2461 (setter) PySSL_set_session, PySSL_set_session_doc},
2462 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2463 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002464 {NULL}, /* sentinel */
2465};
2466
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002467static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002468 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2469 _SSL__SSLSOCKET_WRITE_METHODDEF
2470 _SSL__SSLSOCKET_READ_METHODDEF
2471 _SSL__SSLSOCKET_PENDING_METHODDEF
2472 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2473 _SSL__SSLSOCKET_CIPHER_METHODDEF
2474 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2475 _SSL__SSLSOCKET_VERSION_METHODDEF
2476 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2477 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2478 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2479 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2480 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002481 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002482};
2483
Antoine Pitrou152efa22010-05-16 18:19:27 +00002484static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002485 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002486 "_ssl._SSLSocket", /*tp_name*/
2487 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002488 0, /*tp_itemsize*/
2489 /* methods */
2490 (destructor)PySSL_dealloc, /*tp_dealloc*/
2491 0, /*tp_print*/
2492 0, /*tp_getattr*/
2493 0, /*tp_setattr*/
2494 0, /*tp_reserved*/
2495 0, /*tp_repr*/
2496 0, /*tp_as_number*/
2497 0, /*tp_as_sequence*/
2498 0, /*tp_as_mapping*/
2499 0, /*tp_hash*/
2500 0, /*tp_call*/
2501 0, /*tp_str*/
2502 0, /*tp_getattro*/
2503 0, /*tp_setattro*/
2504 0, /*tp_as_buffer*/
2505 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2506 0, /*tp_doc*/
2507 0, /*tp_traverse*/
2508 0, /*tp_clear*/
2509 0, /*tp_richcompare*/
2510 0, /*tp_weaklistoffset*/
2511 0, /*tp_iter*/
2512 0, /*tp_iternext*/
2513 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002514 0, /*tp_members*/
2515 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002516};
2517
Antoine Pitrou152efa22010-05-16 18:19:27 +00002518
2519/*
2520 * _SSLContext objects
2521 */
2522
Christian Heimes5fe668c2016-09-12 00:01:11 +02002523static int
2524_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2525{
2526 int mode;
2527 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2528
2529 switch(n) {
2530 case PY_SSL_CERT_NONE:
2531 mode = SSL_VERIFY_NONE;
2532 break;
2533 case PY_SSL_CERT_OPTIONAL:
2534 mode = SSL_VERIFY_PEER;
2535 break;
2536 case PY_SSL_CERT_REQUIRED:
2537 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2538 break;
2539 default:
2540 PyErr_SetString(PyExc_ValueError,
2541 "invalid value for verify_mode");
2542 return -1;
2543 }
2544 /* keep current verify cb */
2545 verify_cb = SSL_CTX_get_verify_callback(ctx);
2546 SSL_CTX_set_verify(ctx, mode, verify_cb);
2547 return 0;
2548}
2549
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002550/*[clinic input]
2551@classmethod
2552_ssl._SSLContext.__new__
2553 protocol as proto_version: int
2554 /
2555[clinic start generated code]*/
2556
Antoine Pitrou152efa22010-05-16 18:19:27 +00002557static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002558_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2559/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002560{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002561 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002562 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002563 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002564 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002565#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002566 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002567#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002568
Antoine Pitrou152efa22010-05-16 18:19:27 +00002569 PySSL_BEGIN_ALLOW_THREADS
2570 if (proto_version == PY_SSL_VERSION_TLS1)
2571 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002572#if HAVE_TLSv1_2
2573 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2574 ctx = SSL_CTX_new(TLSv1_1_method());
2575 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2576 ctx = SSL_CTX_new(TLSv1_2_method());
2577#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002578#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002579 else if (proto_version == PY_SSL_VERSION_SSL3)
2580 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002581#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002582#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002583 else if (proto_version == PY_SSL_VERSION_SSL2)
2584 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002585#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002586 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002587 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002588 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2589 ctx = SSL_CTX_new(TLS_client_method());
2590 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2591 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002592 else
2593 proto_version = -1;
2594 PySSL_END_ALLOW_THREADS
2595
2596 if (proto_version == -1) {
2597 PyErr_SetString(PyExc_ValueError,
2598 "invalid protocol version");
2599 return NULL;
2600 }
2601 if (ctx == NULL) {
2602 PyErr_SetString(PySSLErrorObject,
2603 "failed to allocate SSL context");
2604 return NULL;
2605 }
2606
2607 assert(type != NULL && type->tp_alloc != NULL);
2608 self = (PySSLContext *) type->tp_alloc(type, 0);
2609 if (self == NULL) {
2610 SSL_CTX_free(ctx);
2611 return NULL;
2612 }
2613 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002614#ifdef OPENSSL_NPN_NEGOTIATED
2615 self->npn_protocols = NULL;
2616#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002617#ifdef HAVE_ALPN
2618 self->alpn_protocols = NULL;
2619#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002620#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002621 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002622#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002623 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002624 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2625 self->check_hostname = 1;
2626 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2627 Py_DECREF(self);
2628 return NULL;
2629 }
2630 } else {
2631 self->check_hostname = 0;
2632 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2633 Py_DECREF(self);
2634 return NULL;
2635 }
2636 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002637 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002638 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2639 if (proto_version != PY_SSL_VERSION_SSL2)
2640 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002641 if (proto_version != PY_SSL_VERSION_SSL3)
2642 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002643 /* Minimal security flags for server and client side context.
2644 * Client sockets ignore server-side parameters. */
2645#ifdef SSL_OP_NO_COMPRESSION
2646 options |= SSL_OP_NO_COMPRESSION;
2647#endif
2648#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2649 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2650#endif
2651#ifdef SSL_OP_SINGLE_DH_USE
2652 options |= SSL_OP_SINGLE_DH_USE;
2653#endif
2654#ifdef SSL_OP_SINGLE_ECDH_USE
2655 options |= SSL_OP_SINGLE_ECDH_USE;
2656#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002657 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002658
Christian Heimes358cfd42016-09-10 22:43:48 +02002659 /* A bare minimum cipher list without completly broken cipher suites.
2660 * It's far from perfect but gives users a better head start. */
2661 if (proto_version != PY_SSL_VERSION_SSL2) {
2662 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2663 } else {
2664 /* SSLv2 needs MD5 */
2665 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2666 }
2667 if (result == 0) {
2668 Py_DECREF(self);
2669 ERR_clear_error();
2670 PyErr_SetString(PySSLErrorObject,
2671 "No cipher can be selected.");
2672 return NULL;
2673 }
2674
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002675#if defined(SSL_MODE_RELEASE_BUFFERS)
2676 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2677 usage for no cost at all. However, don't do this for OpenSSL versions
2678 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2679 2014-0198. I can't find exactly which beta fixed this CVE, so be
2680 conservative and assume it wasn't fixed until release. We do this check
2681 at runtime to avoid problems from the dynamic linker.
2682 See #25672 for more on this. */
2683 libver = SSLeay();
2684 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2685 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2686 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2687 }
2688#endif
2689
2690
Donald Stufft8ae264c2017-03-02 11:45:29 -05002691#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002692 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2693 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002694 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2695 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002696#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002697 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2698#else
2699 {
2700 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2701 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2702 EC_KEY_free(key);
2703 }
2704#endif
2705#endif
2706
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002707#define SID_CTX "Python"
2708 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2709 sizeof(SID_CTX));
2710#undef SID_CTX
2711
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002712#ifdef X509_V_FLAG_TRUSTED_FIRST
2713 {
2714 /* Improve trust chain building when cross-signed intermediate
2715 certificates are present. See https://bugs.python.org/issue23476. */
2716 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2717 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2718 }
2719#endif
2720
Antoine Pitrou152efa22010-05-16 18:19:27 +00002721 return (PyObject *)self;
2722}
2723
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002724static int
2725context_traverse(PySSLContext *self, visitproc visit, void *arg)
2726{
2727#ifndef OPENSSL_NO_TLSEXT
2728 Py_VISIT(self->set_hostname);
2729#endif
2730 return 0;
2731}
2732
2733static int
2734context_clear(PySSLContext *self)
2735{
2736#ifndef OPENSSL_NO_TLSEXT
2737 Py_CLEAR(self->set_hostname);
2738#endif
2739 return 0;
2740}
2741
Antoine Pitrou152efa22010-05-16 18:19:27 +00002742static void
2743context_dealloc(PySSLContext *self)
2744{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002745 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002746 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002747#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002748 PyMem_FREE(self->npn_protocols);
2749#endif
2750#ifdef HAVE_ALPN
2751 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002752#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002753 Py_TYPE(self)->tp_free(self);
2754}
2755
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002756/*[clinic input]
2757_ssl._SSLContext.set_ciphers
2758 cipherlist: str
2759 /
2760[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002761
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002762static PyObject *
2763_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2764/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2765{
2766 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002767 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002768 /* Clearing the error queue is necessary on some OpenSSL versions,
2769 otherwise the error will be reported again when another SSL call
2770 is done. */
2771 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002772 PyErr_SetString(PySSLErrorObject,
2773 "No cipher can be selected.");
2774 return NULL;
2775 }
2776 Py_RETURN_NONE;
2777}
2778
Christian Heimes25bfcd52016-09-06 00:04:45 +02002779#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2780/*[clinic input]
2781_ssl._SSLContext.get_ciphers
2782[clinic start generated code]*/
2783
2784static PyObject *
2785_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2786/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2787{
2788 SSL *ssl = NULL;
2789 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002790 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002791 int i=0;
2792 PyObject *result = NULL, *dct;
2793
2794 ssl = SSL_new(self->ctx);
2795 if (ssl == NULL) {
2796 _setSSLError(NULL, 0, __FILE__, __LINE__);
2797 goto exit;
2798 }
2799 sk = SSL_get_ciphers(ssl);
2800
2801 result = PyList_New(sk_SSL_CIPHER_num(sk));
2802 if (result == NULL) {
2803 goto exit;
2804 }
2805
2806 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2807 cipher = sk_SSL_CIPHER_value(sk, i);
2808 dct = cipher_to_dict(cipher);
2809 if (dct == NULL) {
2810 Py_CLEAR(result);
2811 goto exit;
2812 }
2813 PyList_SET_ITEM(result, i, dct);
2814 }
2815
2816 exit:
2817 if (ssl != NULL)
2818 SSL_free(ssl);
2819 return result;
2820
2821}
2822#endif
2823
2824
Benjamin Petersonc54de472015-01-28 12:06:39 -05002825#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002826static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002827do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2828 const unsigned char *server_protocols, unsigned int server_protocols_len,
2829 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002830{
Benjamin Peterson88615022015-01-23 17:30:26 -05002831 int ret;
2832 if (client_protocols == NULL) {
2833 client_protocols = (unsigned char *)"";
2834 client_protocols_len = 0;
2835 }
2836 if (server_protocols == NULL) {
2837 server_protocols = (unsigned char *)"";
2838 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002839 }
2840
Benjamin Peterson88615022015-01-23 17:30:26 -05002841 ret = SSL_select_next_proto(out, outlen,
2842 server_protocols, server_protocols_len,
2843 client_protocols, client_protocols_len);
2844 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2845 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002846
2847 return SSL_TLSEXT_ERR_OK;
2848}
2849
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002850/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2851static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002852_advertiseNPN_cb(SSL *s,
2853 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002854 void *args)
2855{
2856 PySSLContext *ssl_ctx = (PySSLContext *) args;
2857
2858 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002859 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002860 *len = 0;
2861 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002862 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002863 *len = ssl_ctx->npn_protocols_len;
2864 }
2865
2866 return SSL_TLSEXT_ERR_OK;
2867}
2868/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2869static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002870_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002871 unsigned char **out, unsigned char *outlen,
2872 const unsigned char *server, unsigned int server_len,
2873 void *args)
2874{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002875 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002876 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002877 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002878}
2879#endif
2880
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002881/*[clinic input]
2882_ssl._SSLContext._set_npn_protocols
2883 protos: Py_buffer
2884 /
2885[clinic start generated code]*/
2886
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002887static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002888_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2889 Py_buffer *protos)
2890/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002891{
2892#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002893 PyMem_Free(self->npn_protocols);
2894 self->npn_protocols = PyMem_Malloc(protos->len);
2895 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002896 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002897 memcpy(self->npn_protocols, protos->buf, protos->len);
2898 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002899
2900 /* set both server and client callbacks, because the context can
2901 * be used to create both types of sockets */
2902 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2903 _advertiseNPN_cb,
2904 self);
2905 SSL_CTX_set_next_proto_select_cb(self->ctx,
2906 _selectNPN_cb,
2907 self);
2908
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002909 Py_RETURN_NONE;
2910#else
2911 PyErr_SetString(PyExc_NotImplementedError,
2912 "The NPN extension requires OpenSSL 1.0.1 or later.");
2913 return NULL;
2914#endif
2915}
2916
Benjamin Petersoncca27322015-01-23 16:35:37 -05002917#ifdef HAVE_ALPN
2918static int
2919_selectALPN_cb(SSL *s,
2920 const unsigned char **out, unsigned char *outlen,
2921 const unsigned char *client_protocols, unsigned int client_protocols_len,
2922 void *args)
2923{
2924 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002925 return do_protocol_selection(1, (unsigned char **)out, outlen,
2926 ctx->alpn_protocols, ctx->alpn_protocols_len,
2927 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002928}
2929#endif
2930
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002931/*[clinic input]
2932_ssl._SSLContext._set_alpn_protocols
2933 protos: Py_buffer
2934 /
2935[clinic start generated code]*/
2936
Benjamin Petersoncca27322015-01-23 16:35:37 -05002937static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002938_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2939 Py_buffer *protos)
2940/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002941{
2942#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002943 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002944 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002945 if (!self->alpn_protocols)
2946 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002947 memcpy(self->alpn_protocols, protos->buf, protos->len);
2948 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002949
2950 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2951 return PyErr_NoMemory();
2952 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2953
Benjamin Petersoncca27322015-01-23 16:35:37 -05002954 Py_RETURN_NONE;
2955#else
2956 PyErr_SetString(PyExc_NotImplementedError,
2957 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2958 return NULL;
2959#endif
2960}
2961
Antoine Pitrou152efa22010-05-16 18:19:27 +00002962static PyObject *
2963get_verify_mode(PySSLContext *self, void *c)
2964{
2965 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2966 case SSL_VERIFY_NONE:
2967 return PyLong_FromLong(PY_SSL_CERT_NONE);
2968 case SSL_VERIFY_PEER:
2969 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2970 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2971 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2972 }
2973 PyErr_SetString(PySSLErrorObject,
2974 "invalid return value from SSL_CTX_get_verify_mode");
2975 return NULL;
2976}
2977
2978static int
2979set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2980{
Christian Heimes5fe668c2016-09-12 00:01:11 +02002981 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002982 if (!PyArg_Parse(arg, "i", &n))
2983 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02002984 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01002985 PyErr_SetString(PyExc_ValueError,
2986 "Cannot set verify_mode to CERT_NONE when "
2987 "check_hostname is enabled.");
2988 return -1;
2989 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02002990 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002991}
2992
2993static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002994get_verify_flags(PySSLContext *self, void *c)
2995{
2996 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02002997 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01002998 unsigned long flags;
2999
3000 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003001 param = X509_STORE_get0_param(store);
3002 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003003 return PyLong_FromUnsignedLong(flags);
3004}
3005
3006static int
3007set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3008{
3009 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003010 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003011 unsigned long new_flags, flags, set, clear;
3012
3013 if (!PyArg_Parse(arg, "k", &new_flags))
3014 return -1;
3015 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003016 param = X509_STORE_get0_param(store);
3017 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003018 clear = flags & ~new_flags;
3019 set = ~flags & new_flags;
3020 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003021 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003022 _setSSLError(NULL, 0, __FILE__, __LINE__);
3023 return -1;
3024 }
3025 }
3026 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003027 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003028 _setSSLError(NULL, 0, __FILE__, __LINE__);
3029 return -1;
3030 }
3031 }
3032 return 0;
3033}
3034
3035static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003036get_options(PySSLContext *self, void *c)
3037{
3038 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3039}
3040
3041static int
3042set_options(PySSLContext *self, PyObject *arg, void *c)
3043{
3044 long new_opts, opts, set, clear;
3045 if (!PyArg_Parse(arg, "l", &new_opts))
3046 return -1;
3047 opts = SSL_CTX_get_options(self->ctx);
3048 clear = opts & ~new_opts;
3049 set = ~opts & new_opts;
3050 if (clear) {
3051#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3052 SSL_CTX_clear_options(self->ctx, clear);
3053#else
3054 PyErr_SetString(PyExc_ValueError,
3055 "can't clear options before OpenSSL 0.9.8m");
3056 return -1;
3057#endif
3058 }
3059 if (set)
3060 SSL_CTX_set_options(self->ctx, set);
3061 return 0;
3062}
3063
Christian Heimes1aa9a752013-12-02 02:41:19 +01003064static PyObject *
3065get_check_hostname(PySSLContext *self, void *c)
3066{
3067 return PyBool_FromLong(self->check_hostname);
3068}
3069
3070static int
3071set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3072{
3073 int check_hostname;
3074 if (!PyArg_Parse(arg, "p", &check_hostname))
3075 return -1;
3076 if (check_hostname &&
3077 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3078 PyErr_SetString(PyExc_ValueError,
3079 "check_hostname needs a SSL context with either "
3080 "CERT_OPTIONAL or CERT_REQUIRED");
3081 return -1;
3082 }
3083 self->check_hostname = check_hostname;
3084 return 0;
3085}
3086
3087
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003088typedef struct {
3089 PyThreadState *thread_state;
3090 PyObject *callable;
3091 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003092 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003093 int error;
3094} _PySSLPasswordInfo;
3095
3096static int
3097_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3098 const char *bad_type_error)
3099{
3100 /* Set the password and size fields of a _PySSLPasswordInfo struct
3101 from a unicode, bytes, or byte array object.
3102 The password field will be dynamically allocated and must be freed
3103 by the caller */
3104 PyObject *password_bytes = NULL;
3105 const char *data = NULL;
3106 Py_ssize_t size;
3107
3108 if (PyUnicode_Check(password)) {
3109 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3110 if (!password_bytes) {
3111 goto error;
3112 }
3113 data = PyBytes_AS_STRING(password_bytes);
3114 size = PyBytes_GET_SIZE(password_bytes);
3115 } else if (PyBytes_Check(password)) {
3116 data = PyBytes_AS_STRING(password);
3117 size = PyBytes_GET_SIZE(password);
3118 } else if (PyByteArray_Check(password)) {
3119 data = PyByteArray_AS_STRING(password);
3120 size = PyByteArray_GET_SIZE(password);
3121 } else {
3122 PyErr_SetString(PyExc_TypeError, bad_type_error);
3123 goto error;
3124 }
3125
Victor Stinner9ee02032013-06-23 15:08:23 +02003126 if (size > (Py_ssize_t)INT_MAX) {
3127 PyErr_Format(PyExc_ValueError,
3128 "password cannot be longer than %d bytes", INT_MAX);
3129 goto error;
3130 }
3131
Victor Stinner11ebff22013-07-07 17:07:52 +02003132 PyMem_Free(pw_info->password);
3133 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003134 if (!pw_info->password) {
3135 PyErr_SetString(PyExc_MemoryError,
3136 "unable to allocate password buffer");
3137 goto error;
3138 }
3139 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003140 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003141
3142 Py_XDECREF(password_bytes);
3143 return 1;
3144
3145error:
3146 Py_XDECREF(password_bytes);
3147 return 0;
3148}
3149
3150static int
3151_password_callback(char *buf, int size, int rwflag, void *userdata)
3152{
3153 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3154 PyObject *fn_ret = NULL;
3155
3156 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3157
3158 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003159 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003160 if (!fn_ret) {
3161 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3162 core python API, so we could use it to add a frame here */
3163 goto error;
3164 }
3165
3166 if (!_pwinfo_set(pw_info, fn_ret,
3167 "password callback must return a string")) {
3168 goto error;
3169 }
3170 Py_CLEAR(fn_ret);
3171 }
3172
3173 if (pw_info->size > size) {
3174 PyErr_Format(PyExc_ValueError,
3175 "password cannot be longer than %d bytes", size);
3176 goto error;
3177 }
3178
3179 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3180 memcpy(buf, pw_info->password, pw_info->size);
3181 return pw_info->size;
3182
3183error:
3184 Py_XDECREF(fn_ret);
3185 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3186 pw_info->error = 1;
3187 return -1;
3188}
3189
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003190/*[clinic input]
3191_ssl._SSLContext.load_cert_chain
3192 certfile: object
3193 keyfile: object = NULL
3194 password: object = NULL
3195
3196[clinic start generated code]*/
3197
Antoine Pitroub5218772010-05-21 09:56:06 +00003198static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003199_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3200 PyObject *keyfile, PyObject *password)
3201/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003202{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003203 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003204 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3205 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003206 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003207 int r;
3208
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003209 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003210 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003211 if (keyfile == Py_None)
3212 keyfile = NULL;
3213 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3214 PyErr_SetString(PyExc_TypeError,
3215 "certfile should be a valid filesystem path");
3216 return NULL;
3217 }
3218 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3219 PyErr_SetString(PyExc_TypeError,
3220 "keyfile should be a valid filesystem path");
3221 goto error;
3222 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003223 if (password && password != Py_None) {
3224 if (PyCallable_Check(password)) {
3225 pw_info.callable = password;
3226 } else if (!_pwinfo_set(&pw_info, password,
3227 "password should be a string or callable")) {
3228 goto error;
3229 }
3230 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3231 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3232 }
3233 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003234 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3235 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003236 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003237 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003238 if (pw_info.error) {
3239 ERR_clear_error();
3240 /* the password callback has already set the error information */
3241 }
3242 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003243 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003244 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003245 }
3246 else {
3247 _setSSLError(NULL, 0, __FILE__, __LINE__);
3248 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003249 goto error;
3250 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003251 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003252 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003253 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3254 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003255 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3256 Py_CLEAR(keyfile_bytes);
3257 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003258 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003259 if (pw_info.error) {
3260 ERR_clear_error();
3261 /* the password callback has already set the error information */
3262 }
3263 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003264 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003265 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003266 }
3267 else {
3268 _setSSLError(NULL, 0, __FILE__, __LINE__);
3269 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003270 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003271 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003272 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003273 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003274 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003275 if (r != 1) {
3276 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003277 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003278 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003279 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3280 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003281 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003282 Py_RETURN_NONE;
3283
3284error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003285 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3286 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003287 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003288 Py_XDECREF(keyfile_bytes);
3289 Py_XDECREF(certfile_bytes);
3290 return NULL;
3291}
3292
Christian Heimesefff7062013-11-21 03:35:02 +01003293/* internal helper function, returns -1 on error
3294 */
3295static int
3296_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3297 int filetype)
3298{
3299 BIO *biobuf = NULL;
3300 X509_STORE *store;
3301 int retval = 0, err, loaded = 0;
3302
3303 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3304
3305 if (len <= 0) {
3306 PyErr_SetString(PyExc_ValueError,
3307 "Empty certificate data");
3308 return -1;
3309 } else if (len > INT_MAX) {
3310 PyErr_SetString(PyExc_OverflowError,
3311 "Certificate data is too long.");
3312 return -1;
3313 }
3314
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003315 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003316 if (biobuf == NULL) {
3317 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3318 return -1;
3319 }
3320
3321 store = SSL_CTX_get_cert_store(self->ctx);
3322 assert(store != NULL);
3323
3324 while (1) {
3325 X509 *cert = NULL;
3326 int r;
3327
3328 if (filetype == SSL_FILETYPE_ASN1) {
3329 cert = d2i_X509_bio(biobuf, NULL);
3330 } else {
3331 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003332 SSL_CTX_get_default_passwd_cb(self->ctx),
3333 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3334 );
Christian Heimesefff7062013-11-21 03:35:02 +01003335 }
3336 if (cert == NULL) {
3337 break;
3338 }
3339 r = X509_STORE_add_cert(store, cert);
3340 X509_free(cert);
3341 if (!r) {
3342 err = ERR_peek_last_error();
3343 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3344 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3345 /* cert already in hash table, not an error */
3346 ERR_clear_error();
3347 } else {
3348 break;
3349 }
3350 }
3351 loaded++;
3352 }
3353
3354 err = ERR_peek_last_error();
3355 if ((filetype == SSL_FILETYPE_ASN1) &&
3356 (loaded > 0) &&
3357 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3358 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3359 /* EOF ASN1 file, not an error */
3360 ERR_clear_error();
3361 retval = 0;
3362 } else if ((filetype == SSL_FILETYPE_PEM) &&
3363 (loaded > 0) &&
3364 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3365 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3366 /* EOF PEM file, not an error */
3367 ERR_clear_error();
3368 retval = 0;
3369 } else {
3370 _setSSLError(NULL, 0, __FILE__, __LINE__);
3371 retval = -1;
3372 }
3373
3374 BIO_free(biobuf);
3375 return retval;
3376}
3377
3378
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003379/*[clinic input]
3380_ssl._SSLContext.load_verify_locations
3381 cafile: object = NULL
3382 capath: object = NULL
3383 cadata: object = NULL
3384
3385[clinic start generated code]*/
3386
Antoine Pitrou152efa22010-05-16 18:19:27 +00003387static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003388_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3389 PyObject *cafile,
3390 PyObject *capath,
3391 PyObject *cadata)
3392/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003393{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003394 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3395 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003396 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003397
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003398 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003399 if (cafile == Py_None)
3400 cafile = NULL;
3401 if (capath == Py_None)
3402 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003403 if (cadata == Py_None)
3404 cadata = NULL;
3405
3406 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003407 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003408 "cafile, capath and cadata cannot be all omitted");
3409 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003410 }
3411 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3412 PyErr_SetString(PyExc_TypeError,
3413 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003414 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003415 }
3416 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003417 PyErr_SetString(PyExc_TypeError,
3418 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003419 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003420 }
Christian Heimesefff7062013-11-21 03:35:02 +01003421
3422 /* validata cadata type and load cadata */
3423 if (cadata) {
3424 Py_buffer buf;
3425 PyObject *cadata_ascii = NULL;
3426
3427 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3428 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3429 PyBuffer_Release(&buf);
3430 PyErr_SetString(PyExc_TypeError,
3431 "cadata should be a contiguous buffer with "
3432 "a single dimension");
3433 goto error;
3434 }
3435 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3436 PyBuffer_Release(&buf);
3437 if (r == -1) {
3438 goto error;
3439 }
3440 } else {
3441 PyErr_Clear();
3442 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3443 if (cadata_ascii == NULL) {
3444 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003445 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003446 "bytes-like object");
3447 goto error;
3448 }
3449 r = _add_ca_certs(self,
3450 PyBytes_AS_STRING(cadata_ascii),
3451 PyBytes_GET_SIZE(cadata_ascii),
3452 SSL_FILETYPE_PEM);
3453 Py_DECREF(cadata_ascii);
3454 if (r == -1) {
3455 goto error;
3456 }
3457 }
3458 }
3459
3460 /* load cafile or capath */
3461 if (cafile || capath) {
3462 if (cafile)
3463 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3464 if (capath)
3465 capath_buf = PyBytes_AS_STRING(capath_bytes);
3466 PySSL_BEGIN_ALLOW_THREADS
3467 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3468 PySSL_END_ALLOW_THREADS
3469 if (r != 1) {
3470 ok = 0;
3471 if (errno != 0) {
3472 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003473 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003474 }
3475 else {
3476 _setSSLError(NULL, 0, __FILE__, __LINE__);
3477 }
3478 goto error;
3479 }
3480 }
3481 goto end;
3482
3483 error:
3484 ok = 0;
3485 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003486 Py_XDECREF(cafile_bytes);
3487 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003488 if (ok) {
3489 Py_RETURN_NONE;
3490 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003491 return NULL;
3492 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003493}
3494
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003495/*[clinic input]
3496_ssl._SSLContext.load_dh_params
3497 path as filepath: object
3498 /
3499
3500[clinic start generated code]*/
3501
Antoine Pitrou152efa22010-05-16 18:19:27 +00003502static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003503_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3504/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003505{
3506 FILE *f;
3507 DH *dh;
3508
Victor Stinnerdaf45552013-08-28 00:53:59 +02003509 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003510 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003511 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003512
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003513 errno = 0;
3514 PySSL_BEGIN_ALLOW_THREADS
3515 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003516 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003517 PySSL_END_ALLOW_THREADS
3518 if (dh == NULL) {
3519 if (errno != 0) {
3520 ERR_clear_error();
3521 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3522 }
3523 else {
3524 _setSSLError(NULL, 0, __FILE__, __LINE__);
3525 }
3526 return NULL;
3527 }
3528 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3529 _setSSLError(NULL, 0, __FILE__, __LINE__);
3530 DH_free(dh);
3531 Py_RETURN_NONE;
3532}
3533
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003534/*[clinic input]
3535_ssl._SSLContext._wrap_socket
3536 sock: object(subclass_of="PySocketModule.Sock_Type")
3537 server_side: int
3538 server_hostname as hostname_obj: object = None
3539
3540[clinic start generated code]*/
3541
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003542static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003543_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3544 int server_side, PyObject *hostname_obj)
3545/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003546{
Antoine Pitroud5323212010-10-22 18:19:07 +00003547 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003548 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003549
Antoine Pitroud5323212010-10-22 18:19:07 +00003550 /* server_hostname is either None (or absent), or to be encoded
3551 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003552 if (hostname_obj != Py_None) {
3553 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003554 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003555 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003556
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003557 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3558 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003559 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003560 if (hostname != NULL)
3561 PyMem_Free(hostname);
3562 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003563}
3564
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003565/*[clinic input]
3566_ssl._SSLContext._wrap_bio
3567 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3568 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3569 server_side: int
3570 server_hostname as hostname_obj: object = None
3571
3572[clinic start generated code]*/
3573
Antoine Pitroub0182c82010-10-12 20:09:02 +00003574static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003575_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3576 PySSLMemoryBIO *outgoing, int server_side,
3577 PyObject *hostname_obj)
3578/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003579{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003580 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003581 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003582
3583 /* server_hostname is either None (or absent), or to be encoded
3584 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003585 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003586 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3587 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003588 }
3589
3590 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3591 incoming, outgoing);
3592
3593 PyMem_Free(hostname);
3594 return res;
3595}
3596
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003597/*[clinic input]
3598_ssl._SSLContext.session_stats
3599[clinic start generated code]*/
3600
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003601static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003602_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3603/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003604{
3605 int r;
3606 PyObject *value, *stats = PyDict_New();
3607 if (!stats)
3608 return NULL;
3609
3610#define ADD_STATS(SSL_NAME, KEY_NAME) \
3611 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3612 if (value == NULL) \
3613 goto error; \
3614 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3615 Py_DECREF(value); \
3616 if (r < 0) \
3617 goto error;
3618
3619 ADD_STATS(number, "number");
3620 ADD_STATS(connect, "connect");
3621 ADD_STATS(connect_good, "connect_good");
3622 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3623 ADD_STATS(accept, "accept");
3624 ADD_STATS(accept_good, "accept_good");
3625 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3626 ADD_STATS(accept, "accept");
3627 ADD_STATS(hits, "hits");
3628 ADD_STATS(misses, "misses");
3629 ADD_STATS(timeouts, "timeouts");
3630 ADD_STATS(cache_full, "cache_full");
3631
3632#undef ADD_STATS
3633
3634 return stats;
3635
3636error:
3637 Py_DECREF(stats);
3638 return NULL;
3639}
3640
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003641/*[clinic input]
3642_ssl._SSLContext.set_default_verify_paths
3643[clinic start generated code]*/
3644
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003645static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003646_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3647/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003648{
3649 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3650 _setSSLError(NULL, 0, __FILE__, __LINE__);
3651 return NULL;
3652 }
3653 Py_RETURN_NONE;
3654}
3655
Antoine Pitrou501da612011-12-21 09:27:41 +01003656#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003657/*[clinic input]
3658_ssl._SSLContext.set_ecdh_curve
3659 name: object
3660 /
3661
3662[clinic start generated code]*/
3663
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003664static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003665_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3666/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003667{
3668 PyObject *name_bytes;
3669 int nid;
3670 EC_KEY *key;
3671
3672 if (!PyUnicode_FSConverter(name, &name_bytes))
3673 return NULL;
3674 assert(PyBytes_Check(name_bytes));
3675 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3676 Py_DECREF(name_bytes);
3677 if (nid == 0) {
3678 PyErr_Format(PyExc_ValueError,
3679 "unknown elliptic curve name %R", name);
3680 return NULL;
3681 }
3682 key = EC_KEY_new_by_curve_name(nid);
3683 if (key == NULL) {
3684 _setSSLError(NULL, 0, __FILE__, __LINE__);
3685 return NULL;
3686 }
3687 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3688 EC_KEY_free(key);
3689 Py_RETURN_NONE;
3690}
Antoine Pitrou501da612011-12-21 09:27:41 +01003691#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003692
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003693#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003694static int
3695_servername_callback(SSL *s, int *al, void *args)
3696{
3697 int ret;
3698 PySSLContext *ssl_ctx = (PySSLContext *) args;
3699 PySSLSocket *ssl;
3700 PyObject *servername_o;
3701 PyObject *servername_idna;
3702 PyObject *result;
3703 /* The high-level ssl.SSLSocket object */
3704 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003705 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003706#ifdef WITH_THREAD
3707 PyGILState_STATE gstate = PyGILState_Ensure();
3708#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003709
3710 if (ssl_ctx->set_hostname == NULL) {
3711 /* remove race condition in this the call back while if removing the
3712 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003713#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003714 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003715#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003716 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003717 }
3718
3719 ssl = SSL_get_app_data(s);
3720 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003721
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003722 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003723 * SSL connection and that has a .context attribute that can be changed to
3724 * identify the requested hostname. Since the official API is the Python
3725 * level API we want to pass the callback a Python level object rather than
3726 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3727 * SSLObject) that will be passed. Otherwise if there's a socket then that
3728 * will be passed. If both do not exist only then the C-level object is
3729 * passed. */
3730 if (ssl->owner)
3731 ssl_socket = PyWeakref_GetObject(ssl->owner);
3732 else if (ssl->Socket)
3733 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3734 else
3735 ssl_socket = (PyObject *) ssl;
3736
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003737 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003738 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003739 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003740
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003741 if (servername == NULL) {
3742 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3743 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003744 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003745 else {
3746 servername_o = PyBytes_FromString(servername);
3747 if (servername_o == NULL) {
3748 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3749 goto error;
3750 }
3751 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3752 if (servername_idna == NULL) {
3753 PyErr_WriteUnraisable(servername_o);
3754 Py_DECREF(servername_o);
3755 goto error;
3756 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003757 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003758 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3759 servername_idna, ssl_ctx, NULL);
3760 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003761 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003762 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003763
3764 if (result == NULL) {
3765 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3766 *al = SSL_AD_HANDSHAKE_FAILURE;
3767 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3768 }
3769 else {
3770 if (result != Py_None) {
3771 *al = (int) PyLong_AsLong(result);
3772 if (PyErr_Occurred()) {
3773 PyErr_WriteUnraisable(result);
3774 *al = SSL_AD_INTERNAL_ERROR;
3775 }
3776 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3777 }
3778 else {
3779 ret = SSL_TLSEXT_ERR_OK;
3780 }
3781 Py_DECREF(result);
3782 }
3783
Stefan Krah20d60802013-01-17 17:07:17 +01003784#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003785 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003786#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003787 return ret;
3788
3789error:
3790 Py_DECREF(ssl_socket);
3791 *al = SSL_AD_INTERNAL_ERROR;
3792 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003793#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003794 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003795#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003796 return ret;
3797}
Antoine Pitroua5963382013-03-30 16:39:00 +01003798#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003799
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003800/*[clinic input]
3801_ssl._SSLContext.set_servername_callback
3802 method as cb: object
3803 /
3804
3805Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3806
3807If the argument is None then the callback is disabled. The method is called
3808with the SSLSocket, the server name as a string, and the SSLContext object.
3809See RFC 6066 for details of the SNI extension.
3810[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003811
3812static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003813_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3814/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003815{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003816#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003817 Py_CLEAR(self->set_hostname);
3818 if (cb == Py_None) {
3819 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3820 }
3821 else {
3822 if (!PyCallable_Check(cb)) {
3823 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3824 PyErr_SetString(PyExc_TypeError,
3825 "not a callable object");
3826 return NULL;
3827 }
3828 Py_INCREF(cb);
3829 self->set_hostname = cb;
3830 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3831 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3832 }
3833 Py_RETURN_NONE;
3834#else
3835 PyErr_SetString(PyExc_NotImplementedError,
3836 "The TLS extension servername callback, "
3837 "SSL_CTX_set_tlsext_servername_callback, "
3838 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003839 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003840#endif
3841}
3842
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003843/*[clinic input]
3844_ssl._SSLContext.cert_store_stats
3845
3846Returns quantities of loaded X.509 certificates.
3847
3848X.509 certificates with a CA extension and certificate revocation lists
3849inside the context's cert store.
3850
3851NOTE: Certificates in a capath directory aren't loaded unless they have
3852been used at least once.
3853[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003854
3855static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003856_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3857/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003858{
3859 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003860 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003861 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003862 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003863
3864 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003865 objs = X509_STORE_get0_objects(store);
3866 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3867 obj = sk_X509_OBJECT_value(objs, i);
3868 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003869 case X509_LU_X509:
3870 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003871 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003872 ca++;
3873 }
3874 break;
3875 case X509_LU_CRL:
3876 crl++;
3877 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003878 default:
3879 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3880 * As far as I can tell they are internal states and never
3881 * stored in a cert store */
3882 break;
3883 }
3884 }
3885 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3886 "x509_ca", ca);
3887}
3888
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003889/*[clinic input]
3890_ssl._SSLContext.get_ca_certs
3891 binary_form: bool = False
3892
3893Returns a list of dicts with information of loaded CA certs.
3894
3895If the optional argument is True, returns a DER-encoded copy of the CA
3896certificate.
3897
3898NOTE: Certificates in a capath directory aren't loaded unless they have
3899been used at least once.
3900[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003901
3902static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003903_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3904/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003905{
3906 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003907 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003908 PyObject *ci = NULL, *rlist = NULL;
3909 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003910
3911 if ((rlist = PyList_New(0)) == NULL) {
3912 return NULL;
3913 }
3914
3915 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003916 objs = X509_STORE_get0_objects(store);
3917 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003918 X509_OBJECT *obj;
3919 X509 *cert;
3920
Christian Heimes598894f2016-09-05 23:19:05 +02003921 obj = sk_X509_OBJECT_value(objs, i);
3922 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003923 /* not a x509 cert */
3924 continue;
3925 }
3926 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003927 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003928 if (!X509_check_ca(cert)) {
3929 continue;
3930 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003931 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003932 ci = _certificate_to_der(cert);
3933 } else {
3934 ci = _decode_certificate(cert);
3935 }
3936 if (ci == NULL) {
3937 goto error;
3938 }
3939 if (PyList_Append(rlist, ci) == -1) {
3940 goto error;
3941 }
3942 Py_CLEAR(ci);
3943 }
3944 return rlist;
3945
3946 error:
3947 Py_XDECREF(ci);
3948 Py_XDECREF(rlist);
3949 return NULL;
3950}
3951
3952
Antoine Pitrou152efa22010-05-16 18:19:27 +00003953static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003954 {"check_hostname", (getter) get_check_hostname,
3955 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003956 {"options", (getter) get_options,
3957 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003958 {"verify_flags", (getter) get_verify_flags,
3959 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003960 {"verify_mode", (getter) get_verify_mode,
3961 (setter) set_verify_mode, NULL},
3962 {NULL}, /* sentinel */
3963};
3964
3965static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003966 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
3967 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
3968 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
3969 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
3970 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
3971 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
3972 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
3973 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
3974 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
3975 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
3976 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
3977 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
3978 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
3979 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02003980 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00003981 {NULL, NULL} /* sentinel */
3982};
3983
3984static PyTypeObject PySSLContext_Type = {
3985 PyVarObject_HEAD_INIT(NULL, 0)
3986 "_ssl._SSLContext", /*tp_name*/
3987 sizeof(PySSLContext), /*tp_basicsize*/
3988 0, /*tp_itemsize*/
3989 (destructor)context_dealloc, /*tp_dealloc*/
3990 0, /*tp_print*/
3991 0, /*tp_getattr*/
3992 0, /*tp_setattr*/
3993 0, /*tp_reserved*/
3994 0, /*tp_repr*/
3995 0, /*tp_as_number*/
3996 0, /*tp_as_sequence*/
3997 0, /*tp_as_mapping*/
3998 0, /*tp_hash*/
3999 0, /*tp_call*/
4000 0, /*tp_str*/
4001 0, /*tp_getattro*/
4002 0, /*tp_setattro*/
4003 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004004 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004005 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004006 (traverseproc) context_traverse, /*tp_traverse*/
4007 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004008 0, /*tp_richcompare*/
4009 0, /*tp_weaklistoffset*/
4010 0, /*tp_iter*/
4011 0, /*tp_iternext*/
4012 context_methods, /*tp_methods*/
4013 0, /*tp_members*/
4014 context_getsetlist, /*tp_getset*/
4015 0, /*tp_base*/
4016 0, /*tp_dict*/
4017 0, /*tp_descr_get*/
4018 0, /*tp_descr_set*/
4019 0, /*tp_dictoffset*/
4020 0, /*tp_init*/
4021 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004022 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004023};
4024
4025
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004026/*
4027 * MemoryBIO objects
4028 */
4029
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004030/*[clinic input]
4031@classmethod
4032_ssl.MemoryBIO.__new__
4033
4034[clinic start generated code]*/
4035
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004036static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004037_ssl_MemoryBIO_impl(PyTypeObject *type)
4038/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004039{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004040 BIO *bio;
4041 PySSLMemoryBIO *self;
4042
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004043 bio = BIO_new(BIO_s_mem());
4044 if (bio == NULL) {
4045 PyErr_SetString(PySSLErrorObject,
4046 "failed to allocate BIO");
4047 return NULL;
4048 }
4049 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4050 * just that no data is currently available. The SSL routines should retry
4051 * the read, which we can achieve by calling BIO_set_retry_read(). */
4052 BIO_set_retry_read(bio);
4053 BIO_set_mem_eof_return(bio, -1);
4054
4055 assert(type != NULL && type->tp_alloc != NULL);
4056 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4057 if (self == NULL) {
4058 BIO_free(bio);
4059 return NULL;
4060 }
4061 self->bio = bio;
4062 self->eof_written = 0;
4063
4064 return (PyObject *) self;
4065}
4066
4067static void
4068memory_bio_dealloc(PySSLMemoryBIO *self)
4069{
4070 BIO_free(self->bio);
4071 Py_TYPE(self)->tp_free(self);
4072}
4073
4074static PyObject *
4075memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4076{
4077 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
4078}
4079
4080PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4081"The number of bytes pending in the memory BIO.");
4082
4083static PyObject *
4084memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4085{
4086 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4087 && self->eof_written);
4088}
4089
4090PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4091"Whether the memory BIO is at EOF.");
4092
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004093/*[clinic input]
4094_ssl.MemoryBIO.read
4095 size as len: int = -1
4096 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004097
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004098Read up to size bytes from the memory BIO.
4099
4100If size is not specified, read the entire buffer.
4101If the return value is an empty bytes instance, this means either
4102EOF or that no data is available. Use the "eof" property to
4103distinguish between the two.
4104[clinic start generated code]*/
4105
4106static PyObject *
4107_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4108/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4109{
4110 int avail, nbytes;
4111 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004112
4113 avail = BIO_ctrl_pending(self->bio);
4114 if ((len < 0) || (len > avail))
4115 len = avail;
4116
4117 result = PyBytes_FromStringAndSize(NULL, len);
4118 if ((result == NULL) || (len == 0))
4119 return result;
4120
4121 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4122 /* There should never be any short reads but check anyway. */
4123 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4124 Py_DECREF(result);
4125 return NULL;
4126 }
4127
4128 return result;
4129}
4130
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004131/*[clinic input]
4132_ssl.MemoryBIO.write
4133 b: Py_buffer
4134 /
4135
4136Writes the bytes b into the memory BIO.
4137
4138Returns the number of bytes written.
4139[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004140
4141static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004142_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4143/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004144{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004145 int nbytes;
4146
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004147 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004148 PyErr_Format(PyExc_OverflowError,
4149 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004150 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004151 }
4152
4153 if (self->eof_written) {
4154 PyErr_SetString(PySSLErrorObject,
4155 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004156 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004157 }
4158
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004159 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004160 if (nbytes < 0) {
4161 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004162 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004163 }
4164
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004165 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004166}
4167
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004168/*[clinic input]
4169_ssl.MemoryBIO.write_eof
4170
4171Write an EOF marker to the memory BIO.
4172
4173When all data has been read, the "eof" property will be True.
4174[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004175
4176static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004177_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4178/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004179{
4180 self->eof_written = 1;
4181 /* After an EOF is written, a zero return from read() should be a real EOF
4182 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4183 BIO_clear_retry_flags(self->bio);
4184 BIO_set_mem_eof_return(self->bio, 0);
4185
4186 Py_RETURN_NONE;
4187}
4188
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004189static PyGetSetDef memory_bio_getsetlist[] = {
4190 {"pending", (getter) memory_bio_get_pending, NULL,
4191 PySSL_memory_bio_pending_doc},
4192 {"eof", (getter) memory_bio_get_eof, NULL,
4193 PySSL_memory_bio_eof_doc},
4194 {NULL}, /* sentinel */
4195};
4196
4197static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004198 _SSL_MEMORYBIO_READ_METHODDEF
4199 _SSL_MEMORYBIO_WRITE_METHODDEF
4200 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004201 {NULL, NULL} /* sentinel */
4202};
4203
4204static PyTypeObject PySSLMemoryBIO_Type = {
4205 PyVarObject_HEAD_INIT(NULL, 0)
4206 "_ssl.MemoryBIO", /*tp_name*/
4207 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4208 0, /*tp_itemsize*/
4209 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4210 0, /*tp_print*/
4211 0, /*tp_getattr*/
4212 0, /*tp_setattr*/
4213 0, /*tp_reserved*/
4214 0, /*tp_repr*/
4215 0, /*tp_as_number*/
4216 0, /*tp_as_sequence*/
4217 0, /*tp_as_mapping*/
4218 0, /*tp_hash*/
4219 0, /*tp_call*/
4220 0, /*tp_str*/
4221 0, /*tp_getattro*/
4222 0, /*tp_setattro*/
4223 0, /*tp_as_buffer*/
4224 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4225 0, /*tp_doc*/
4226 0, /*tp_traverse*/
4227 0, /*tp_clear*/
4228 0, /*tp_richcompare*/
4229 0, /*tp_weaklistoffset*/
4230 0, /*tp_iter*/
4231 0, /*tp_iternext*/
4232 memory_bio_methods, /*tp_methods*/
4233 0, /*tp_members*/
4234 memory_bio_getsetlist, /*tp_getset*/
4235 0, /*tp_base*/
4236 0, /*tp_dict*/
4237 0, /*tp_descr_get*/
4238 0, /*tp_descr_set*/
4239 0, /*tp_dictoffset*/
4240 0, /*tp_init*/
4241 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004242 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004243};
4244
Antoine Pitrou152efa22010-05-16 18:19:27 +00004245
Christian Heimes99a65702016-09-10 23:44:53 +02004246/*
4247 * SSL Session object
4248 */
4249
4250static void
4251PySSLSession_dealloc(PySSLSession *self)
4252{
Christian Heimesa5d07652016-09-24 10:48:05 +02004253 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004254 Py_XDECREF(self->ctx);
4255 if (self->session != NULL) {
4256 SSL_SESSION_free(self->session);
4257 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004258 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004259}
4260
4261static PyObject *
4262PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4263{
4264 int result;
4265
4266 if (left == NULL || right == NULL) {
4267 PyErr_BadInternalCall();
4268 return NULL;
4269 }
4270
4271 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4272 Py_RETURN_NOTIMPLEMENTED;
4273 }
4274
4275 if (left == right) {
4276 result = 0;
4277 } else {
4278 const unsigned char *left_id, *right_id;
4279 unsigned int left_len, right_len;
4280 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4281 &left_len);
4282 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4283 &right_len);
4284 if (left_len == right_len) {
4285 result = memcmp(left_id, right_id, left_len);
4286 } else {
4287 result = 1;
4288 }
4289 }
4290
4291 switch (op) {
4292 case Py_EQ:
4293 if (result == 0) {
4294 Py_RETURN_TRUE;
4295 } else {
4296 Py_RETURN_FALSE;
4297 }
4298 break;
4299 case Py_NE:
4300 if (result != 0) {
4301 Py_RETURN_TRUE;
4302 } else {
4303 Py_RETURN_FALSE;
4304 }
4305 break;
4306 case Py_LT:
4307 case Py_LE:
4308 case Py_GT:
4309 case Py_GE:
4310 Py_RETURN_NOTIMPLEMENTED;
4311 break;
4312 default:
4313 PyErr_BadArgument();
4314 return NULL;
4315 }
4316}
4317
4318static int
4319PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4320{
4321 Py_VISIT(self->ctx);
4322 return 0;
4323}
4324
4325static int
4326PySSLSession_clear(PySSLSession *self)
4327{
4328 Py_CLEAR(self->ctx);
4329 return 0;
4330}
4331
4332
4333static PyObject *
4334PySSLSession_get_time(PySSLSession *self, void *closure) {
4335 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4336}
4337
4338PyDoc_STRVAR(PySSLSession_get_time_doc,
4339"Session creation time (seconds since epoch).");
4340
4341
4342static PyObject *
4343PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4344 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4345}
4346
4347PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4348"Session timeout (delta in seconds).");
4349
4350
4351static PyObject *
4352PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4353 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4354 return PyLong_FromUnsignedLong(hint);
4355}
4356
4357PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4358"Ticket life time hint.");
4359
4360
4361static PyObject *
4362PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4363 const unsigned char *id;
4364 unsigned int len;
4365 id = SSL_SESSION_get_id(self->session, &len);
4366 return PyBytes_FromStringAndSize((const char *)id, len);
4367}
4368
4369PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4370"Session id");
4371
4372
4373static PyObject *
4374PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4375 if (SSL_SESSION_has_ticket(self->session)) {
4376 Py_RETURN_TRUE;
4377 } else {
4378 Py_RETURN_FALSE;
4379 }
4380}
4381
4382PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4383"Does the session contain a ticket?");
4384
4385
4386static PyGetSetDef PySSLSession_getsetlist[] = {
4387 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4388 PySSLSession_get_has_ticket_doc},
4389 {"id", (getter) PySSLSession_get_session_id, NULL,
4390 PySSLSession_get_session_id_doc},
4391 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4392 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4393 {"time", (getter) PySSLSession_get_time, NULL,
4394 PySSLSession_get_time_doc},
4395 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4396 PySSLSession_get_timeout_doc},
4397 {NULL}, /* sentinel */
4398};
4399
4400static PyTypeObject PySSLSession_Type = {
4401 PyVarObject_HEAD_INIT(NULL, 0)
4402 "_ssl.Session", /*tp_name*/
4403 sizeof(PySSLSession), /*tp_basicsize*/
4404 0, /*tp_itemsize*/
4405 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4406 0, /*tp_print*/
4407 0, /*tp_getattr*/
4408 0, /*tp_setattr*/
4409 0, /*tp_reserved*/
4410 0, /*tp_repr*/
4411 0, /*tp_as_number*/
4412 0, /*tp_as_sequence*/
4413 0, /*tp_as_mapping*/
4414 0, /*tp_hash*/
4415 0, /*tp_call*/
4416 0, /*tp_str*/
4417 0, /*tp_getattro*/
4418 0, /*tp_setattro*/
4419 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004420 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004421 0, /*tp_doc*/
4422 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4423 (inquiry)PySSLSession_clear, /*tp_clear*/
4424 PySSLSession_richcompare, /*tp_richcompare*/
4425 0, /*tp_weaklistoffset*/
4426 0, /*tp_iter*/
4427 0, /*tp_iternext*/
4428 0, /*tp_methods*/
4429 0, /*tp_members*/
4430 PySSLSession_getsetlist, /*tp_getset*/
4431};
4432
4433
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004434/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004435/*[clinic input]
4436_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004437 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004438 entropy: double
4439 /
4440
4441Mix string into the OpenSSL PRNG state.
4442
4443entropy (a float) is a lower bound on the entropy contained in
4444string. See RFC 1750.
4445[clinic start generated code]*/
4446
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004447static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004448_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
4449/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004450{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004451 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004452 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004453
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004454 buf = (const char *)view->buf;
4455 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004456 do {
4457 written = Py_MIN(len, INT_MAX);
4458 RAND_add(buf, (int)written, entropy);
4459 buf += written;
4460 len -= written;
4461 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004462 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004463}
4464
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004465static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004466PySSL_RAND(int len, int pseudo)
4467{
4468 int ok;
4469 PyObject *bytes;
4470 unsigned long err;
4471 const char *errstr;
4472 PyObject *v;
4473
Victor Stinner1e81a392013-12-19 16:47:04 +01004474 if (len < 0) {
4475 PyErr_SetString(PyExc_ValueError, "num must be positive");
4476 return NULL;
4477 }
4478
Victor Stinner99c8b162011-05-24 12:05:19 +02004479 bytes = PyBytes_FromStringAndSize(NULL, len);
4480 if (bytes == NULL)
4481 return NULL;
4482 if (pseudo) {
4483 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4484 if (ok == 0 || ok == 1)
4485 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4486 }
4487 else {
4488 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4489 if (ok == 1)
4490 return bytes;
4491 }
4492 Py_DECREF(bytes);
4493
4494 err = ERR_get_error();
4495 errstr = ERR_reason_error_string(err);
4496 v = Py_BuildValue("(ks)", err, errstr);
4497 if (v != NULL) {
4498 PyErr_SetObject(PySSLErrorObject, v);
4499 Py_DECREF(v);
4500 }
4501 return NULL;
4502}
4503
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004504/*[clinic input]
4505_ssl.RAND_bytes
4506 n: int
4507 /
4508
4509Generate n cryptographically strong pseudo-random bytes.
4510[clinic start generated code]*/
4511
Victor Stinner99c8b162011-05-24 12:05:19 +02004512static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004513_ssl_RAND_bytes_impl(PyObject *module, int n)
4514/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004515{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004516 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004517}
4518
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004519/*[clinic input]
4520_ssl.RAND_pseudo_bytes
4521 n: int
4522 /
4523
4524Generate n pseudo-random bytes.
4525
4526Return a pair (bytes, is_cryptographic). is_cryptographic is True
4527if the bytes generated are cryptographically strong.
4528[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004529
4530static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004531_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4532/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004533{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004534 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004535}
4536
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004537/*[clinic input]
4538_ssl.RAND_status
4539
4540Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4541
4542It is necessary to seed the PRNG with RAND_add() on some platforms before
4543using the ssl() function.
4544[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004545
4546static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004547_ssl_RAND_status_impl(PyObject *module)
4548/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004549{
Christian Heimes217cfd12007-12-02 14:31:20 +00004550 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004551}
4552
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004553#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004554/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004555/*[clinic input]
4556_ssl.RAND_egd
4557 path: object(converter="PyUnicode_FSConverter")
4558 /
4559
4560Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4561
4562Returns number of bytes read. Raises SSLError if connection to EGD
4563fails or if it does not provide enough data to seed PRNG.
4564[clinic start generated code]*/
4565
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004566static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004567_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4568/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004569{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004570 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004571 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004572 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004573 PyErr_SetString(PySSLErrorObject,
4574 "EGD connection failed or EGD did not return "
4575 "enough data to seed the PRNG");
4576 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004577 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004578 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004579}
Christian Heimesa5d07652016-09-24 10:48:05 +02004580/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004581#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004582
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004583
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004584
4585/*[clinic input]
4586_ssl.get_default_verify_paths
4587
4588Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4589
4590The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4591[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004592
4593static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004594_ssl_get_default_verify_paths_impl(PyObject *module)
4595/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004596{
4597 PyObject *ofile_env = NULL;
4598 PyObject *ofile = NULL;
4599 PyObject *odir_env = NULL;
4600 PyObject *odir = NULL;
4601
Benjamin Petersond113c962015-07-18 10:59:13 -07004602#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004603 const char *tmp = (info); \
4604 target = NULL; \
4605 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4606 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4607 target = PyBytes_FromString(tmp); } \
4608 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004609 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004610
Benjamin Petersond113c962015-07-18 10:59:13 -07004611 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4612 CONVERT(X509_get_default_cert_file(), ofile);
4613 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4614 CONVERT(X509_get_default_cert_dir(), odir);
4615#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004616
Christian Heimes200bb1b2013-06-14 15:14:29 +02004617 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004618
4619 error:
4620 Py_XDECREF(ofile_env);
4621 Py_XDECREF(ofile);
4622 Py_XDECREF(odir_env);
4623 Py_XDECREF(odir);
4624 return NULL;
4625}
4626
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004627static PyObject*
4628asn1obj2py(ASN1_OBJECT *obj)
4629{
4630 int nid;
4631 const char *ln, *sn;
4632 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004633 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004634
4635 nid = OBJ_obj2nid(obj);
4636 if (nid == NID_undef) {
4637 PyErr_Format(PyExc_ValueError, "Unknown object");
4638 return NULL;
4639 }
4640 sn = OBJ_nid2sn(nid);
4641 ln = OBJ_nid2ln(nid);
4642 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4643 if (buflen < 0) {
4644 _setSSLError(NULL, 0, __FILE__, __LINE__);
4645 return NULL;
4646 }
4647 if (buflen) {
4648 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4649 } else {
4650 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4651 }
4652}
4653
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004654/*[clinic input]
4655_ssl.txt2obj
4656 txt: str
4657 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004658
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004659Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4660
4661By default objects are looked up by OID. With name=True short and
4662long name are also matched.
4663[clinic start generated code]*/
4664
4665static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004666_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4667/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004668{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004669 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004670 ASN1_OBJECT *obj;
4671
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004672 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4673 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004674 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004675 return NULL;
4676 }
4677 result = asn1obj2py(obj);
4678 ASN1_OBJECT_free(obj);
4679 return result;
4680}
4681
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004682/*[clinic input]
4683_ssl.nid2obj
4684 nid: int
4685 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004686
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004687Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4688[clinic start generated code]*/
4689
4690static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004691_ssl_nid2obj_impl(PyObject *module, int nid)
4692/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004693{
4694 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004695 ASN1_OBJECT *obj;
4696
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004697 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004698 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004699 return NULL;
4700 }
4701 obj = OBJ_nid2obj(nid);
4702 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004703 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004704 return NULL;
4705 }
4706 result = asn1obj2py(obj);
4707 ASN1_OBJECT_free(obj);
4708 return result;
4709}
4710
Christian Heimes46bebee2013-06-09 19:03:31 +02004711#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004712
4713static PyObject*
4714certEncodingType(DWORD encodingType)
4715{
4716 static PyObject *x509_asn = NULL;
4717 static PyObject *pkcs_7_asn = NULL;
4718
4719 if (x509_asn == NULL) {
4720 x509_asn = PyUnicode_InternFromString("x509_asn");
4721 if (x509_asn == NULL)
4722 return NULL;
4723 }
4724 if (pkcs_7_asn == NULL) {
4725 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4726 if (pkcs_7_asn == NULL)
4727 return NULL;
4728 }
4729 switch(encodingType) {
4730 case X509_ASN_ENCODING:
4731 Py_INCREF(x509_asn);
4732 return x509_asn;
4733 case PKCS_7_ASN_ENCODING:
4734 Py_INCREF(pkcs_7_asn);
4735 return pkcs_7_asn;
4736 default:
4737 return PyLong_FromLong(encodingType);
4738 }
4739}
4740
4741static PyObject*
4742parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4743{
4744 CERT_ENHKEY_USAGE *usage;
4745 DWORD size, error, i;
4746 PyObject *retval;
4747
4748 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4749 error = GetLastError();
4750 if (error == CRYPT_E_NOT_FOUND) {
4751 Py_RETURN_TRUE;
4752 }
4753 return PyErr_SetFromWindowsErr(error);
4754 }
4755
4756 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4757 if (usage == NULL) {
4758 return PyErr_NoMemory();
4759 }
4760
4761 /* Now get the actual enhanced usage property */
4762 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4763 PyMem_Free(usage);
4764 error = GetLastError();
4765 if (error == CRYPT_E_NOT_FOUND) {
4766 Py_RETURN_TRUE;
4767 }
4768 return PyErr_SetFromWindowsErr(error);
4769 }
4770 retval = PySet_New(NULL);
4771 if (retval == NULL) {
4772 goto error;
4773 }
4774 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4775 if (usage->rgpszUsageIdentifier[i]) {
4776 PyObject *oid;
4777 int err;
4778 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4779 if (oid == NULL) {
4780 Py_CLEAR(retval);
4781 goto error;
4782 }
4783 err = PySet_Add(retval, oid);
4784 Py_DECREF(oid);
4785 if (err == -1) {
4786 Py_CLEAR(retval);
4787 goto error;
4788 }
4789 }
4790 }
4791 error:
4792 PyMem_Free(usage);
4793 return retval;
4794}
4795
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004796/*[clinic input]
4797_ssl.enum_certificates
4798 store_name: str
4799
4800Retrieve certificates from Windows' cert store.
4801
4802store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4803more cert storages, too. The function returns a list of (bytes,
4804encoding_type, trust) tuples. The encoding_type flag can be interpreted
4805with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4806a set of OIDs or the boolean True.
4807[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004808
Christian Heimes46bebee2013-06-09 19:03:31 +02004809static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004810_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4811/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004812{
Christian Heimes46bebee2013-06-09 19:03:31 +02004813 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004814 PCCERT_CONTEXT pCertCtx = NULL;
4815 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004816 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004817
Christian Heimes44109d72013-11-22 01:51:30 +01004818 result = PyList_New(0);
4819 if (result == NULL) {
4820 return NULL;
4821 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004822 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4823 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4824 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004825 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004826 Py_DECREF(result);
4827 return PyErr_SetFromWindowsErr(GetLastError());
4828 }
4829
Christian Heimes44109d72013-11-22 01:51:30 +01004830 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4831 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4832 pCertCtx->cbCertEncoded);
4833 if (!cert) {
4834 Py_CLEAR(result);
4835 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004836 }
Christian Heimes44109d72013-11-22 01:51:30 +01004837 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4838 Py_CLEAR(result);
4839 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004840 }
Christian Heimes44109d72013-11-22 01:51:30 +01004841 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4842 if (keyusage == Py_True) {
4843 Py_DECREF(keyusage);
4844 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004845 }
Christian Heimes44109d72013-11-22 01:51:30 +01004846 if (keyusage == NULL) {
4847 Py_CLEAR(result);
4848 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004849 }
Christian Heimes44109d72013-11-22 01:51:30 +01004850 if ((tup = PyTuple_New(3)) == NULL) {
4851 Py_CLEAR(result);
4852 break;
4853 }
4854 PyTuple_SET_ITEM(tup, 0, cert);
4855 cert = NULL;
4856 PyTuple_SET_ITEM(tup, 1, enc);
4857 enc = NULL;
4858 PyTuple_SET_ITEM(tup, 2, keyusage);
4859 keyusage = NULL;
4860 if (PyList_Append(result, tup) < 0) {
4861 Py_CLEAR(result);
4862 break;
4863 }
4864 Py_CLEAR(tup);
4865 }
4866 if (pCertCtx) {
4867 /* loop ended with an error, need to clean up context manually */
4868 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004869 }
4870
4871 /* In error cases cert, enc and tup may not be NULL */
4872 Py_XDECREF(cert);
4873 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004874 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004875 Py_XDECREF(tup);
4876
4877 if (!CertCloseStore(hStore, 0)) {
4878 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004879 Py_XDECREF(result);
4880 return PyErr_SetFromWindowsErr(GetLastError());
4881 }
4882 return result;
4883}
4884
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004885/*[clinic input]
4886_ssl.enum_crls
4887 store_name: str
4888
4889Retrieve CRLs from Windows' cert store.
4890
4891store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4892more cert storages, too. The function returns a list of (bytes,
4893encoding_type) tuples. The encoding_type flag can be interpreted with
4894X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4895[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004896
4897static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004898_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4899/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004900{
Christian Heimes44109d72013-11-22 01:51:30 +01004901 HCERTSTORE hStore = NULL;
4902 PCCRL_CONTEXT pCrlCtx = NULL;
4903 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4904 PyObject *result = NULL;
4905
Christian Heimes44109d72013-11-22 01:51:30 +01004906 result = PyList_New(0);
4907 if (result == NULL) {
4908 return NULL;
4909 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004910 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4911 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4912 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004913 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004914 Py_DECREF(result);
4915 return PyErr_SetFromWindowsErr(GetLastError());
4916 }
Christian Heimes44109d72013-11-22 01:51:30 +01004917
4918 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4919 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4920 pCrlCtx->cbCrlEncoded);
4921 if (!crl) {
4922 Py_CLEAR(result);
4923 break;
4924 }
4925 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4926 Py_CLEAR(result);
4927 break;
4928 }
4929 if ((tup = PyTuple_New(2)) == NULL) {
4930 Py_CLEAR(result);
4931 break;
4932 }
4933 PyTuple_SET_ITEM(tup, 0, crl);
4934 crl = NULL;
4935 PyTuple_SET_ITEM(tup, 1, enc);
4936 enc = NULL;
4937
4938 if (PyList_Append(result, tup) < 0) {
4939 Py_CLEAR(result);
4940 break;
4941 }
4942 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004943 }
Christian Heimes44109d72013-11-22 01:51:30 +01004944 if (pCrlCtx) {
4945 /* loop ended with an error, need to clean up context manually */
4946 CertFreeCRLContext(pCrlCtx);
4947 }
4948
4949 /* In error cases cert, enc and tup may not be NULL */
4950 Py_XDECREF(crl);
4951 Py_XDECREF(enc);
4952 Py_XDECREF(tup);
4953
4954 if (!CertCloseStore(hStore, 0)) {
4955 /* This error case might shadow another exception.*/
4956 Py_XDECREF(result);
4957 return PyErr_SetFromWindowsErr(GetLastError());
4958 }
4959 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004960}
Christian Heimes44109d72013-11-22 01:51:30 +01004961
4962#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004963
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004964/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004965static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004966 _SSL__TEST_DECODE_CERT_METHODDEF
4967 _SSL_RAND_ADD_METHODDEF
4968 _SSL_RAND_BYTES_METHODDEF
4969 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4970 _SSL_RAND_EGD_METHODDEF
4971 _SSL_RAND_STATUS_METHODDEF
4972 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
4973 _SSL_ENUM_CERTIFICATES_METHODDEF
4974 _SSL_ENUM_CRLS_METHODDEF
4975 _SSL_TXT2OBJ_METHODDEF
4976 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004977 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004978};
4979
4980
Christian Heimes598894f2016-09-05 23:19:05 +02004981#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004982
4983/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02004984 * of the Python C thread library
4985 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
4986 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004987
4988static PyThread_type_lock *_ssl_locks = NULL;
4989
Christian Heimes4d98ca92013-08-19 17:36:29 +02004990#if OPENSSL_VERSION_NUMBER >= 0x10000000
4991/* use new CRYPTO_THREADID API. */
4992static void
4993_ssl_threadid_callback(CRYPTO_THREADID *id)
4994{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02004995 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02004996}
4997#else
4998/* deprecated CRYPTO_set_id_callback() API. */
4999static unsigned long
5000_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005001 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005002}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005003#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005004
Bill Janssen6e027db2007-11-15 22:23:56 +00005005static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005006 (int mode, int n, const char *file, int line) {
5007 /* this function is needed to perform locking on shared data
5008 structures. (Note that OpenSSL uses a number of global data
5009 structures that will be implicitly shared whenever multiple
5010 threads use OpenSSL.) Multi-threaded applications will
5011 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005012
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005013 locking_function() must be able to handle up to
5014 CRYPTO_num_locks() different mutex locks. It sets the n-th
5015 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005016
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005017 file and line are the file number of the function setting the
5018 lock. They can be useful for debugging.
5019 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005020
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005021 if ((_ssl_locks == NULL) ||
5022 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5023 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005024
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005025 if (mode & CRYPTO_LOCK) {
5026 PyThread_acquire_lock(_ssl_locks[n], 1);
5027 } else {
5028 PyThread_release_lock(_ssl_locks[n]);
5029 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005030}
5031
5032static int _setup_ssl_threads(void) {
5033
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005034 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005035
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005036 if (_ssl_locks == NULL) {
5037 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005038 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5039 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005040 if (_ssl_locks == NULL) {
5041 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005042 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005043 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005044 for (i = 0; i < _ssl_locks_count; i++) {
5045 _ssl_locks[i] = PyThread_allocate_lock();
5046 if (_ssl_locks[i] == NULL) {
5047 unsigned int j;
5048 for (j = 0; j < i; j++) {
5049 PyThread_free_lock(_ssl_locks[j]);
5050 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005051 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005052 return 0;
5053 }
5054 }
5055 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005056#if OPENSSL_VERSION_NUMBER >= 0x10000000
5057 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5058#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005059 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005060#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005061 }
5062 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005063}
5064
Christian Heimes598894f2016-09-05 23:19:05 +02005065#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005066
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005067PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005068"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005069for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005070
Martin v. Löwis1a214512008-06-11 05:26:20 +00005071
5072static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005073 PyModuleDef_HEAD_INIT,
5074 "_ssl",
5075 module_doc,
5076 -1,
5077 PySSL_methods,
5078 NULL,
5079 NULL,
5080 NULL,
5081 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005082};
5083
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005084
5085static void
5086parse_openssl_version(unsigned long libver,
5087 unsigned int *major, unsigned int *minor,
5088 unsigned int *fix, unsigned int *patch,
5089 unsigned int *status)
5090{
5091 *status = libver & 0xF;
5092 libver >>= 4;
5093 *patch = libver & 0xFF;
5094 libver >>= 8;
5095 *fix = libver & 0xFF;
5096 libver >>= 8;
5097 *minor = libver & 0xFF;
5098 libver >>= 8;
5099 *major = libver & 0xFF;
5100}
5101
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005102PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005103PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005104{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005105 PyObject *m, *d, *r;
5106 unsigned long libver;
5107 unsigned int major, minor, fix, patch, status;
5108 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005109 struct py_ssl_error_code *errcode;
5110 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005111
Antoine Pitrou152efa22010-05-16 18:19:27 +00005112 if (PyType_Ready(&PySSLContext_Type) < 0)
5113 return NULL;
5114 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005115 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005116 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5117 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005118 if (PyType_Ready(&PySSLSession_Type) < 0)
5119 return NULL;
5120
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005121
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005122 m = PyModule_Create(&_sslmodule);
5123 if (m == NULL)
5124 return NULL;
5125 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005126
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005127 /* Load _socket module and its C API */
5128 socket_api = PySocketModule_ImportModuleAndAPI();
5129 if (!socket_api)
5130 return NULL;
5131 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005132
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005133 /* Init OpenSSL */
5134 SSL_load_error_strings();
5135 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005136#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02005137#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005138 /* note that this will start threading if not already started */
5139 if (!_setup_ssl_threads()) {
5140 return NULL;
5141 }
Christian Heimes598894f2016-09-05 23:19:05 +02005142#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5143 /* OpenSSL 1.1.0 builtin thread support is enabled */
5144 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005145#endif
Christian Heimes598894f2016-09-05 23:19:05 +02005146#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005147 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005148
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005149 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005150 sslerror_type_slots[0].pfunc = PyExc_OSError;
5151 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005152 if (PySSLErrorObject == NULL)
5153 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005154
Antoine Pitrou41032a62011-10-27 23:56:55 +02005155 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5156 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5157 PySSLErrorObject, NULL);
5158 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5159 "ssl.SSLWantReadError", SSLWantReadError_doc,
5160 PySSLErrorObject, NULL);
5161 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5162 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5163 PySSLErrorObject, NULL);
5164 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5165 "ssl.SSLSyscallError", SSLSyscallError_doc,
5166 PySSLErrorObject, NULL);
5167 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5168 "ssl.SSLEOFError", SSLEOFError_doc,
5169 PySSLErrorObject, NULL);
5170 if (PySSLZeroReturnErrorObject == NULL
5171 || PySSLWantReadErrorObject == NULL
5172 || PySSLWantWriteErrorObject == NULL
5173 || PySSLSyscallErrorObject == NULL
5174 || PySSLEOFErrorObject == NULL)
5175 return NULL;
5176 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5177 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5178 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5179 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5180 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5181 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005182 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005183 if (PyDict_SetItemString(d, "_SSLContext",
5184 (PyObject *)&PySSLContext_Type) != 0)
5185 return NULL;
5186 if (PyDict_SetItemString(d, "_SSLSocket",
5187 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005188 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005189 if (PyDict_SetItemString(d, "MemoryBIO",
5190 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5191 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005192 if (PyDict_SetItemString(d, "SSLSession",
5193 (PyObject *)&PySSLSession_Type) != 0)
5194 return NULL;
5195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005196 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5197 PY_SSL_ERROR_ZERO_RETURN);
5198 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5199 PY_SSL_ERROR_WANT_READ);
5200 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5201 PY_SSL_ERROR_WANT_WRITE);
5202 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5203 PY_SSL_ERROR_WANT_X509_LOOKUP);
5204 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5205 PY_SSL_ERROR_SYSCALL);
5206 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5207 PY_SSL_ERROR_SSL);
5208 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5209 PY_SSL_ERROR_WANT_CONNECT);
5210 /* non ssl.h errorcodes */
5211 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5212 PY_SSL_ERROR_EOF);
5213 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5214 PY_SSL_ERROR_INVALID_ERROR_CODE);
5215 /* cert requirements */
5216 PyModule_AddIntConstant(m, "CERT_NONE",
5217 PY_SSL_CERT_NONE);
5218 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5219 PY_SSL_CERT_OPTIONAL);
5220 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5221 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005222 /* CRL verification for verification_flags */
5223 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5224 0);
5225 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5226 X509_V_FLAG_CRL_CHECK);
5227 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5228 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5229 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5230 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005231#ifdef X509_V_FLAG_TRUSTED_FIRST
5232 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5233 X509_V_FLAG_TRUSTED_FIRST);
5234#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005235
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005236 /* Alert Descriptions from ssl.h */
5237 /* note RESERVED constants no longer intended for use have been removed */
5238 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5239
5240#define ADD_AD_CONSTANT(s) \
5241 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5242 SSL_AD_##s)
5243
5244 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5245 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5246 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5247 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5248 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5249 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5250 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5251 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5252 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5253 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5254 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5255 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5256 ADD_AD_CONSTANT(UNKNOWN_CA);
5257 ADD_AD_CONSTANT(ACCESS_DENIED);
5258 ADD_AD_CONSTANT(DECODE_ERROR);
5259 ADD_AD_CONSTANT(DECRYPT_ERROR);
5260 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5261 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5262 ADD_AD_CONSTANT(INTERNAL_ERROR);
5263 ADD_AD_CONSTANT(USER_CANCELLED);
5264 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005265 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005266#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5267 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5268#endif
5269#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5270 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5271#endif
5272#ifdef SSL_AD_UNRECOGNIZED_NAME
5273 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5274#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005275#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5276 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5277#endif
5278#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5279 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5280#endif
5281#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5282 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5283#endif
5284
5285#undef ADD_AD_CONSTANT
5286
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005287 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005288#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005289 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5290 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005291#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005292#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005293 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5294 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005295#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005296 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005297 PY_SSL_VERSION_TLS);
5298 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5299 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005300 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5301 PY_SSL_VERSION_TLS_CLIENT);
5302 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5303 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005304 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5305 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005306#if HAVE_TLSv1_2
5307 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5308 PY_SSL_VERSION_TLS1_1);
5309 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5310 PY_SSL_VERSION_TLS1_2);
5311#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005312
Antoine Pitroub5218772010-05-21 09:56:06 +00005313 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005314 PyModule_AddIntConstant(m, "OP_ALL",
5315 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005316 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5317 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5318 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005319#if HAVE_TLSv1_2
5320 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5321 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5322#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005323 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5324 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005325 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005326 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005327#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005328 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005329#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005330#ifdef SSL_OP_NO_COMPRESSION
5331 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5332 SSL_OP_NO_COMPRESSION);
5333#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005334
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005335#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005336 r = Py_True;
5337#else
5338 r = Py_False;
5339#endif
5340 Py_INCREF(r);
5341 PyModule_AddObject(m, "HAS_SNI", r);
5342
Antoine Pitroud6494802011-07-21 01:11:30 +02005343 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005344 Py_INCREF(r);
5345 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5346
Antoine Pitrou501da612011-12-21 09:27:41 +01005347#ifdef OPENSSL_NO_ECDH
5348 r = Py_False;
5349#else
5350 r = Py_True;
5351#endif
5352 Py_INCREF(r);
5353 PyModule_AddObject(m, "HAS_ECDH", r);
5354
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005355#ifdef OPENSSL_NPN_NEGOTIATED
5356 r = Py_True;
5357#else
5358 r = Py_False;
5359#endif
5360 Py_INCREF(r);
5361 PyModule_AddObject(m, "HAS_NPN", r);
5362
Benjamin Petersoncca27322015-01-23 16:35:37 -05005363#ifdef HAVE_ALPN
5364 r = Py_True;
5365#else
5366 r = Py_False;
5367#endif
5368 Py_INCREF(r);
5369 PyModule_AddObject(m, "HAS_ALPN", r);
5370
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005371 /* Mappings for error codes */
5372 err_codes_to_names = PyDict_New();
5373 err_names_to_codes = PyDict_New();
5374 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5375 return NULL;
5376 errcode = error_codes;
5377 while (errcode->mnemonic != NULL) {
5378 PyObject *mnemo, *key;
5379 mnemo = PyUnicode_FromString(errcode->mnemonic);
5380 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5381 if (mnemo == NULL || key == NULL)
5382 return NULL;
5383 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5384 return NULL;
5385 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5386 return NULL;
5387 Py_DECREF(key);
5388 Py_DECREF(mnemo);
5389 errcode++;
5390 }
5391 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5392 return NULL;
5393 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5394 return NULL;
5395
5396 lib_codes_to_names = PyDict_New();
5397 if (lib_codes_to_names == NULL)
5398 return NULL;
5399 libcode = library_codes;
5400 while (libcode->library != NULL) {
5401 PyObject *mnemo, *key;
5402 key = PyLong_FromLong(libcode->code);
5403 mnemo = PyUnicode_FromString(libcode->library);
5404 if (key == NULL || mnemo == NULL)
5405 return NULL;
5406 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5407 return NULL;
5408 Py_DECREF(key);
5409 Py_DECREF(mnemo);
5410 libcode++;
5411 }
5412 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5413 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005414
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005415 /* OpenSSL version */
5416 /* SSLeay() gives us the version of the library linked against,
5417 which could be different from the headers version.
5418 */
5419 libver = SSLeay();
5420 r = PyLong_FromUnsignedLong(libver);
5421 if (r == NULL)
5422 return NULL;
5423 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5424 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005425 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005426 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5427 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5428 return NULL;
5429 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5430 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5431 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005432
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005433 libver = OPENSSL_VERSION_NUMBER;
5434 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5435 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5436 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5437 return NULL;
5438
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005439 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005440}