blob: a79a7470d20a3a6b0baa44e9f6f55c567402009e [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;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700599 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200600 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200601 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700602 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200603 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700604 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
605 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200606 if (hostname == NULL) {
607 Py_DECREF(self);
608 return NULL;
609 }
610 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700611 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200612
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000613 /* Make sure the SSL error state is initialized */
614 (void) ERR_get_state();
615 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000616
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000617 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000618 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000619 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200620 SSL_set_app_data(self->ssl, self);
621 if (sock) {
622 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
623 } else {
624 /* BIOs are reference counted and SSL_set_bio borrows our reference.
625 * To prevent a double free in memory_bio_dealloc() we need to take an
626 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200627 BIO_up_ref(inbio->bio);
628 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200629 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
630 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200631 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000632#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200633 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000634#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200635 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000636
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100637#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000638 if (server_hostname != NULL)
639 SSL_set_tlsext_host_name(self->ssl, server_hostname);
640#endif
641
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000642 /* If the socket is in non-blocking mode or timeout mode, set the BIO
643 * to non-blocking mode (blocking is the default)
644 */
Victor Stinnere2452312015-03-28 03:00:46 +0100645 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000646 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
647 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
648 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000649
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000650 PySSL_BEGIN_ALLOW_THREADS
651 if (socket_type == PY_SSL_CLIENT)
652 SSL_set_connect_state(self->ssl);
653 else
654 SSL_set_accept_state(self->ssl);
655 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000656
Antoine Pitroud6494802011-07-21 01:11:30 +0200657 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200658 if (sock != NULL) {
659 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
660 if (self->Socket == NULL) {
661 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200662 return NULL;
663 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100664 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000665 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000666}
667
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000668/* SSL object methods */
669
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300670/*[clinic input]
671_ssl._SSLSocket.do_handshake
672[clinic start generated code]*/
673
674static PyObject *
675_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
676/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000677{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000678 int ret;
679 int err;
680 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200681 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200682 _PyTime_t timeout, deadline = 0;
683 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000684
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200685 if (sock) {
686 if (((PyObject*)sock) == Py_None) {
687 _setSSLError("Underlying socket connection gone",
688 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
689 return NULL;
690 }
691 Py_INCREF(sock);
692
693 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100694 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200695 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
696 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000697 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000698
Victor Stinner14690702015-04-06 22:46:13 +0200699 timeout = GET_SOCKET_TIMEOUT(sock);
700 has_timeout = (timeout > 0);
701 if (has_timeout)
702 deadline = _PyTime_GetMonotonicClock() + timeout;
703
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000704 /* Actually negotiate SSL connection */
705 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000706 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000707 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000708 ret = SSL_do_handshake(self->ssl);
709 err = SSL_get_error(self->ssl, ret);
710 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200711
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000712 if (PyErr_CheckSignals())
713 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200714
Victor Stinner14690702015-04-06 22:46:13 +0200715 if (has_timeout)
716 timeout = deadline - _PyTime_GetMonotonicClock();
717
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000718 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200719 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000720 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200721 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000722 } else {
723 sockstate = SOCKET_OPERATION_OK;
724 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200725
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000726 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000727 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000728 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000729 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000730 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
731 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000732 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000733 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000734 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
735 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000736 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000737 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000738 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
739 break;
740 }
741 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200742 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 if (ret < 1)
744 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000745
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200746 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000747
748error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200749 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000750 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000751}
752
Thomas Woutersed03b412007-08-28 21:37:11 +0000753static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000754_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000755
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 char namebuf[X509_NAME_MAXLEN];
757 int buflen;
758 PyObject *name_obj;
759 PyObject *value_obj;
760 PyObject *attr;
761 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000762
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000763 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
764 if (buflen < 0) {
765 _setSSLError(NULL, 0, __FILE__, __LINE__);
766 goto fail;
767 }
768 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
769 if (name_obj == NULL)
770 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000771
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000772 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
773 if (buflen < 0) {
774 _setSSLError(NULL, 0, __FILE__, __LINE__);
775 Py_DECREF(name_obj);
776 goto fail;
777 }
778 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000779 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000780 OPENSSL_free(valuebuf);
781 if (value_obj == NULL) {
782 Py_DECREF(name_obj);
783 goto fail;
784 }
785 attr = PyTuple_New(2);
786 if (attr == NULL) {
787 Py_DECREF(name_obj);
788 Py_DECREF(value_obj);
789 goto fail;
790 }
791 PyTuple_SET_ITEM(attr, 0, name_obj);
792 PyTuple_SET_ITEM(attr, 1, value_obj);
793 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000794
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000795 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000797}
798
799static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000800_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000801{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000802 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
803 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
804 PyObject *rdnt;
805 PyObject *attr = NULL; /* tuple to hold an attribute */
806 int entry_count = X509_NAME_entry_count(xname);
807 X509_NAME_ENTRY *entry;
808 ASN1_OBJECT *name;
809 ASN1_STRING *value;
810 int index_counter;
811 int rdn_level = -1;
812 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000813
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000814 dn = PyList_New(0);
815 if (dn == NULL)
816 return NULL;
817 /* now create another tuple to hold the top-level RDN */
818 rdn = PyList_New(0);
819 if (rdn == NULL)
820 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000821
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000822 for (index_counter = 0;
823 index_counter < entry_count;
824 index_counter++)
825 {
826 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000827
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000828 /* check to see if we've gotten to a new RDN */
829 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200830 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000831 /* yes, new RDN */
832 /* add old RDN to DN */
833 rdnt = PyList_AsTuple(rdn);
834 Py_DECREF(rdn);
835 if (rdnt == NULL)
836 goto fail0;
837 retcode = PyList_Append(dn, rdnt);
838 Py_DECREF(rdnt);
839 if (retcode < 0)
840 goto fail0;
841 /* create new RDN */
842 rdn = PyList_New(0);
843 if (rdn == NULL)
844 goto fail0;
845 }
846 }
Christian Heimes598894f2016-09-05 23:19:05 +0200847 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000848
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000849 /* now add this attribute to the current RDN */
850 name = X509_NAME_ENTRY_get_object(entry);
851 value = X509_NAME_ENTRY_get_data(entry);
852 attr = _create_tuple_for_attribute(name, value);
853 /*
854 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
855 entry->set,
856 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
857 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
858 */
859 if (attr == NULL)
860 goto fail1;
861 retcode = PyList_Append(rdn, attr);
862 Py_DECREF(attr);
863 if (retcode < 0)
864 goto fail1;
865 }
866 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100867 if (rdn != NULL) {
868 if (PyList_GET_SIZE(rdn) > 0) {
869 rdnt = PyList_AsTuple(rdn);
870 Py_DECREF(rdn);
871 if (rdnt == NULL)
872 goto fail0;
873 retcode = PyList_Append(dn, rdnt);
874 Py_DECREF(rdnt);
875 if (retcode < 0)
876 goto fail0;
877 }
878 else {
879 Py_DECREF(rdn);
880 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000881 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000882
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000883 /* convert list to tuple */
884 rdnt = PyList_AsTuple(dn);
885 Py_DECREF(dn);
886 if (rdnt == NULL)
887 return NULL;
888 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000889
890 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892
893 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000894 Py_XDECREF(dn);
895 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000896}
897
898static PyObject *
899_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000900
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000901 /* this code follows the procedure outlined in
902 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
903 function to extract the STACK_OF(GENERAL_NAME),
904 then iterates through the stack to add the
905 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000906
Alex Gaynorb87c0df2017-06-06 07:53:11 -0400907 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000908 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200909 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000910 GENERAL_NAMES *names = NULL;
911 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000912 BIO *biobuf = NULL;
913 char buf[2048];
914 char *vptr;
915 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000916
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000917 if (certificate == NULL)
918 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000919
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000920 /* get a memory buffer */
921 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000922
Alex Gaynorb87c0df2017-06-06 07:53:11 -0400923 names = (GENERAL_NAMES *)X509_get_ext_d2i(
924 certificate, NID_subject_alt_name, NULL, NULL);
925 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000926 if (peer_alt_names == Py_None) {
927 peer_alt_names = PyList_New(0);
928 if (peer_alt_names == NULL)
929 goto fail;
930 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000931
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200934 int gntype;
935 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000936
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000937 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200938 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200939 switch (gntype) {
940 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 /* we special-case DirName as a tuple of
942 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000943
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 t = PyTuple_New(2);
945 if (t == NULL) {
946 goto fail;
947 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000948
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000949 v = PyUnicode_FromString("DirName");
950 if (v == NULL) {
951 Py_DECREF(t);
952 goto fail;
953 }
954 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000955
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000956 v = _create_tuple_for_X509_NAME (name->d.dirn);
957 if (v == NULL) {
958 Py_DECREF(t);
959 goto fail;
960 }
961 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200962 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000963
Christian Heimes824f7f32013-08-17 00:54:47 +0200964 case GEN_EMAIL:
965 case GEN_DNS:
966 case GEN_URI:
967 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
968 correctly, CVE-2013-4238 */
969 t = PyTuple_New(2);
970 if (t == NULL)
971 goto fail;
972 switch (gntype) {
973 case GEN_EMAIL:
974 v = PyUnicode_FromString("email");
975 as = name->d.rfc822Name;
976 break;
977 case GEN_DNS:
978 v = PyUnicode_FromString("DNS");
979 as = name->d.dNSName;
980 break;
981 case GEN_URI:
982 v = PyUnicode_FromString("URI");
983 as = name->d.uniformResourceIdentifier;
984 break;
985 }
986 if (v == NULL) {
987 Py_DECREF(t);
988 goto fail;
989 }
990 PyTuple_SET_ITEM(t, 0, v);
991 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
992 ASN1_STRING_length(as));
993 if (v == NULL) {
994 Py_DECREF(t);
995 goto fail;
996 }
997 PyTuple_SET_ITEM(t, 1, v);
998 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000999
Christian Heimes1c03abd2016-09-06 23:25:35 +02001000 case GEN_RID:
1001 t = PyTuple_New(2);
1002 if (t == NULL)
1003 goto fail;
1004
1005 v = PyUnicode_FromString("Registered ID");
1006 if (v == NULL) {
1007 Py_DECREF(t);
1008 goto fail;
1009 }
1010 PyTuple_SET_ITEM(t, 0, v);
1011
1012 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1013 if (len < 0) {
1014 Py_DECREF(t);
1015 _setSSLError(NULL, 0, __FILE__, __LINE__);
1016 goto fail;
1017 } else if (len >= (int)sizeof(buf)) {
1018 v = PyUnicode_FromString("<INVALID>");
1019 } else {
1020 v = PyUnicode_FromStringAndSize(buf, len);
1021 }
1022 if (v == NULL) {
1023 Py_DECREF(t);
1024 goto fail;
1025 }
1026 PyTuple_SET_ITEM(t, 1, v);
1027 break;
1028
Christian Heimes824f7f32013-08-17 00:54:47 +02001029 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001030 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001031 switch (gntype) {
1032 /* check for new general name type */
1033 case GEN_OTHERNAME:
1034 case GEN_X400:
1035 case GEN_EDIPARTY:
1036 case GEN_IPADD:
1037 case GEN_RID:
1038 break;
1039 default:
1040 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1041 "Unknown general name type %d",
1042 gntype) == -1) {
1043 goto fail;
1044 }
1045 break;
1046 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001047 (void) BIO_reset(biobuf);
1048 GENERAL_NAME_print(biobuf, name);
1049 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1050 if (len < 0) {
1051 _setSSLError(NULL, 0, __FILE__, __LINE__);
1052 goto fail;
1053 }
1054 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001055 if (vptr == NULL) {
1056 PyErr_Format(PyExc_ValueError,
1057 "Invalid value %.200s",
1058 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001060 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001061 t = PyTuple_New(2);
1062 if (t == NULL)
1063 goto fail;
1064 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1065 if (v == NULL) {
1066 Py_DECREF(t);
1067 goto fail;
1068 }
1069 PyTuple_SET_ITEM(t, 0, v);
1070 v = PyUnicode_FromStringAndSize((vptr + 1),
1071 (len - (vptr - buf + 1)));
1072 if (v == NULL) {
1073 Py_DECREF(t);
1074 goto fail;
1075 }
1076 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001077 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001078 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001079
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001080 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001081
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001082 if (PyList_Append(peer_alt_names, t) < 0) {
1083 Py_DECREF(t);
1084 goto fail;
1085 }
1086 Py_DECREF(t);
1087 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001088 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001089 }
1090 BIO_free(biobuf);
1091 if (peer_alt_names != Py_None) {
1092 v = PyList_AsTuple(peer_alt_names);
1093 Py_DECREF(peer_alt_names);
1094 return v;
1095 } else {
1096 return peer_alt_names;
1097 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001098
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001099
1100 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 if (biobuf != NULL)
1102 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001103
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001104 if (peer_alt_names != Py_None) {
1105 Py_XDECREF(peer_alt_names);
1106 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001107
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001108 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001109}
1110
1111static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001112_get_aia_uri(X509 *certificate, int nid) {
1113 PyObject *lst = NULL, *ostr = NULL;
1114 int i, result;
1115 AUTHORITY_INFO_ACCESS *info;
1116
1117 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001118 if (info == NULL)
1119 return Py_None;
1120 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1121 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001122 return Py_None;
1123 }
1124
1125 if ((lst = PyList_New(0)) == NULL) {
1126 goto fail;
1127 }
1128
1129 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1130 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1131 ASN1_IA5STRING *uri;
1132
1133 if ((OBJ_obj2nid(ad->method) != nid) ||
1134 (ad->location->type != GEN_URI)) {
1135 continue;
1136 }
1137 uri = ad->location->d.uniformResourceIdentifier;
1138 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1139 uri->length);
1140 if (ostr == NULL) {
1141 goto fail;
1142 }
1143 result = PyList_Append(lst, ostr);
1144 Py_DECREF(ostr);
1145 if (result < 0) {
1146 goto fail;
1147 }
1148 }
1149 AUTHORITY_INFO_ACCESS_free(info);
1150
1151 /* convert to tuple or None */
1152 if (PyList_Size(lst) == 0) {
1153 Py_DECREF(lst);
1154 return Py_None;
1155 } else {
1156 PyObject *tup;
1157 tup = PyList_AsTuple(lst);
1158 Py_DECREF(lst);
1159 return tup;
1160 }
1161
1162 fail:
1163 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001164 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001165 return NULL;
1166}
1167
1168static PyObject *
1169_get_crl_dp(X509 *certificate) {
1170 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001171 int i, j;
1172 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001173
Christian Heimes598894f2016-09-05 23:19:05 +02001174 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001175
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001176 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001177 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001178
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001179 lst = PyList_New(0);
1180 if (lst == NULL)
1181 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001182
1183 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1184 DIST_POINT *dp;
1185 STACK_OF(GENERAL_NAME) *gns;
1186
1187 dp = sk_DIST_POINT_value(dps, i);
1188 gns = dp->distpoint->name.fullname;
1189
1190 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1191 GENERAL_NAME *gn;
1192 ASN1_IA5STRING *uri;
1193 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001194 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001195
1196 gn = sk_GENERAL_NAME_value(gns, j);
1197 if (gn->type != GEN_URI) {
1198 continue;
1199 }
1200 uri = gn->d.uniformResourceIdentifier;
1201 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1202 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001203 if (ouri == NULL)
1204 goto done;
1205
1206 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001207 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001208 if (err < 0)
1209 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001210 }
1211 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001212
1213 /* Convert to tuple. */
1214 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1215
1216 done:
1217 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001218 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001219 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001220}
1221
1222static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001223_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001224
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001225 PyObject *retval = NULL;
1226 BIO *biobuf = NULL;
1227 PyObject *peer;
1228 PyObject *peer_alt_names = NULL;
1229 PyObject *issuer;
1230 PyObject *version;
1231 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001232 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001233 ASN1_INTEGER *serialNumber;
1234 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001235 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001236 ASN1_TIME *notBefore, *notAfter;
1237 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001238
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001239 retval = PyDict_New();
1240 if (retval == NULL)
1241 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001242
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 peer = _create_tuple_for_X509_NAME(
1244 X509_get_subject_name(certificate));
1245 if (peer == NULL)
1246 goto fail0;
1247 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1248 Py_DECREF(peer);
1249 goto fail0;
1250 }
1251 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001252
Antoine Pitroufb046912010-11-09 20:21:19 +00001253 issuer = _create_tuple_for_X509_NAME(
1254 X509_get_issuer_name(certificate));
1255 if (issuer == NULL)
1256 goto fail0;
1257 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001258 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001259 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001260 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001261 Py_DECREF(issuer);
1262
1263 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001264 if (version == NULL)
1265 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001266 if (PyDict_SetItemString(retval, "version", version) < 0) {
1267 Py_DECREF(version);
1268 goto fail0;
1269 }
1270 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001271
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001272 /* get a memory buffer */
1273 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001274
Antoine Pitroufb046912010-11-09 20:21:19 +00001275 (void) BIO_reset(biobuf);
1276 serialNumber = X509_get_serialNumber(certificate);
1277 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1278 i2a_ASN1_INTEGER(biobuf, serialNumber);
1279 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1280 if (len < 0) {
1281 _setSSLError(NULL, 0, __FILE__, __LINE__);
1282 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001283 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001284 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1285 if (sn_obj == NULL)
1286 goto fail1;
1287 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1288 Py_DECREF(sn_obj);
1289 goto fail1;
1290 }
1291 Py_DECREF(sn_obj);
1292
1293 (void) BIO_reset(biobuf);
1294 notBefore = X509_get_notBefore(certificate);
1295 ASN1_TIME_print(biobuf, notBefore);
1296 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1297 if (len < 0) {
1298 _setSSLError(NULL, 0, __FILE__, __LINE__);
1299 goto fail1;
1300 }
1301 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1302 if (pnotBefore == NULL)
1303 goto fail1;
1304 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1305 Py_DECREF(pnotBefore);
1306 goto fail1;
1307 }
1308 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001309
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001310 (void) BIO_reset(biobuf);
1311 notAfter = X509_get_notAfter(certificate);
1312 ASN1_TIME_print(biobuf, notAfter);
1313 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1314 if (len < 0) {
1315 _setSSLError(NULL, 0, __FILE__, __LINE__);
1316 goto fail1;
1317 }
1318 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1319 if (pnotAfter == NULL)
1320 goto fail1;
1321 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1322 Py_DECREF(pnotAfter);
1323 goto fail1;
1324 }
1325 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001326
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001327 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001328
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 peer_alt_names = _get_peer_alt_names(certificate);
1330 if (peer_alt_names == NULL)
1331 goto fail1;
1332 else if (peer_alt_names != Py_None) {
1333 if (PyDict_SetItemString(retval, "subjectAltName",
1334 peer_alt_names) < 0) {
1335 Py_DECREF(peer_alt_names);
1336 goto fail1;
1337 }
1338 Py_DECREF(peer_alt_names);
1339 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001340
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001341 /* Authority Information Access: OCSP URIs */
1342 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1343 if (obj == NULL) {
1344 goto fail1;
1345 } else if (obj != Py_None) {
1346 result = PyDict_SetItemString(retval, "OCSP", obj);
1347 Py_DECREF(obj);
1348 if (result < 0) {
1349 goto fail1;
1350 }
1351 }
1352
1353 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1354 if (obj == NULL) {
1355 goto fail1;
1356 } else if (obj != Py_None) {
1357 result = PyDict_SetItemString(retval, "caIssuers", obj);
1358 Py_DECREF(obj);
1359 if (result < 0) {
1360 goto fail1;
1361 }
1362 }
1363
1364 /* CDP (CRL distribution points) */
1365 obj = _get_crl_dp(certificate);
1366 if (obj == NULL) {
1367 goto fail1;
1368 } else if (obj != Py_None) {
1369 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1370 Py_DECREF(obj);
1371 if (result < 0) {
1372 goto fail1;
1373 }
1374 }
1375
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001376 BIO_free(biobuf);
1377 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001378
1379 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001380 if (biobuf != NULL)
1381 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001382 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001383 Py_XDECREF(retval);
1384 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001385}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001386
Christian Heimes9a5395a2013-06-17 15:44:12 +02001387static PyObject *
1388_certificate_to_der(X509 *certificate)
1389{
1390 unsigned char *bytes_buf = NULL;
1391 int len;
1392 PyObject *retval;
1393
1394 bytes_buf = NULL;
1395 len = i2d_X509(certificate, &bytes_buf);
1396 if (len < 0) {
1397 _setSSLError(NULL, 0, __FILE__, __LINE__);
1398 return NULL;
1399 }
1400 /* this is actually an immutable bytes sequence */
1401 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1402 OPENSSL_free(bytes_buf);
1403 return retval;
1404}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001405
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001406/*[clinic input]
1407_ssl._test_decode_cert
1408 path: object(converter="PyUnicode_FSConverter")
1409 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001410
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001411[clinic start generated code]*/
1412
1413static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001414_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1415/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001416{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001417 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001418 X509 *x=NULL;
1419 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001420
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001421 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1422 PyErr_SetString(PySSLErrorObject,
1423 "Can't malloc memory to read file");
1424 goto fail0;
1425 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001426
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001427 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001428 PyErr_SetString(PySSLErrorObject,
1429 "Can't open file");
1430 goto fail0;
1431 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001432
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001433 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1434 if (x == NULL) {
1435 PyErr_SetString(PySSLErrorObject,
1436 "Error decoding PEM-encoded file");
1437 goto fail0;
1438 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001439
Antoine Pitroufb046912010-11-09 20:21:19 +00001440 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001441 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001442
1443 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001444 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001445 if (cert != NULL) BIO_free(cert);
1446 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001447}
1448
1449
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001450/*[clinic input]
1451_ssl._SSLSocket.peer_certificate
1452 der as binary_mode: bool = False
1453 /
1454
1455Returns the certificate for the peer.
1456
1457If no certificate was provided, returns None. If a certificate was
1458provided, but not validated, returns an empty dictionary. Otherwise
1459returns a dict containing information about the peer certificate.
1460
1461If the optional argument is True, returns a DER-encoded copy of the
1462peer certificate, or None if no certificate was provided. This will
1463return the certificate even if it wasn't validated.
1464[clinic start generated code]*/
1465
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001466static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001467_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1468/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001469{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001470 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001471 X509 *peer_cert;
1472 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001473
Christian Heimes66dc33b2017-05-23 16:02:02 -07001474 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001475 PyErr_SetString(PyExc_ValueError,
1476 "handshake not done yet");
1477 return NULL;
1478 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001479 peer_cert = SSL_get_peer_certificate(self->ssl);
1480 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001481 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001482
Antoine Pitrou721738f2012-08-15 23:20:39 +02001483 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001484 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001485 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001486 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001487 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001488 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001489 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001490 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001491 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001492 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001493 X509_free(peer_cert);
1494 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001495}
1496
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001497static PyObject *
1498cipher_to_tuple(const SSL_CIPHER *cipher)
1499{
1500 const char *cipher_name, *cipher_protocol;
1501 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001502 if (retval == NULL)
1503 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001504
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001505 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001506 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001507 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001508 PyTuple_SET_ITEM(retval, 0, Py_None);
1509 } else {
1510 v = PyUnicode_FromString(cipher_name);
1511 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001512 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001513 PyTuple_SET_ITEM(retval, 0, v);
1514 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001515
1516 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001517 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001518 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001519 PyTuple_SET_ITEM(retval, 1, Py_None);
1520 } else {
1521 v = PyUnicode_FromString(cipher_protocol);
1522 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001523 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 PyTuple_SET_ITEM(retval, 1, v);
1525 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001526
1527 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001529 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001530 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001531
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001532 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001533
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001534 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001535 Py_DECREF(retval);
1536 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001537}
1538
Christian Heimes25bfcd52016-09-06 00:04:45 +02001539#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1540static PyObject *
1541cipher_to_dict(const SSL_CIPHER *cipher)
1542{
1543 const char *cipher_name, *cipher_protocol;
1544
1545 unsigned long cipher_id;
1546 int alg_bits, strength_bits, len;
1547 char buf[512] = {0};
1548#if OPENSSL_VERSION_1_1
1549 int aead, nid;
1550 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1551#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001552
1553 /* can be NULL */
1554 cipher_name = SSL_CIPHER_get_name(cipher);
1555 cipher_protocol = SSL_CIPHER_get_version(cipher);
1556 cipher_id = SSL_CIPHER_get_id(cipher);
1557 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1558 len = strlen(buf);
1559 if (len > 1 && buf[len-1] == '\n')
1560 buf[len-1] = '\0';
1561 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1562
1563#if OPENSSL_VERSION_1_1
1564 aead = SSL_CIPHER_is_aead(cipher);
1565 nid = SSL_CIPHER_get_cipher_nid(cipher);
1566 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1567 nid = SSL_CIPHER_get_digest_nid(cipher);
1568 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1569 nid = SSL_CIPHER_get_kx_nid(cipher);
1570 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1571 nid = SSL_CIPHER_get_auth_nid(cipher);
1572 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1573#endif
1574
Victor Stinner410b9882016-09-12 12:00:23 +02001575 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001576 "{sksssssssisi"
1577#if OPENSSL_VERSION_1_1
1578 "sOssssssss"
1579#endif
1580 "}",
1581 "id", cipher_id,
1582 "name", cipher_name,
1583 "protocol", cipher_protocol,
1584 "description", buf,
1585 "strength_bits", strength_bits,
1586 "alg_bits", alg_bits
1587#if OPENSSL_VERSION_1_1
1588 ,"aead", aead ? Py_True : Py_False,
1589 "symmetric", skcipher,
1590 "digest", digest,
1591 "kea", kx,
1592 "auth", auth
1593#endif
1594 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001595}
1596#endif
1597
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001598/*[clinic input]
1599_ssl._SSLSocket.shared_ciphers
1600[clinic start generated code]*/
1601
1602static PyObject *
1603_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1604/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001605{
1606 STACK_OF(SSL_CIPHER) *ciphers;
1607 int i;
1608 PyObject *res;
1609
Christian Heimes598894f2016-09-05 23:19:05 +02001610 ciphers = SSL_get_ciphers(self->ssl);
1611 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001612 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001613 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1614 if (!res)
1615 return NULL;
1616 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1617 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1618 if (!tup) {
1619 Py_DECREF(res);
1620 return NULL;
1621 }
1622 PyList_SET_ITEM(res, i, tup);
1623 }
1624 return res;
1625}
1626
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001627/*[clinic input]
1628_ssl._SSLSocket.cipher
1629[clinic start generated code]*/
1630
1631static PyObject *
1632_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1633/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001634{
1635 const SSL_CIPHER *current;
1636
1637 if (self->ssl == NULL)
1638 Py_RETURN_NONE;
1639 current = SSL_get_current_cipher(self->ssl);
1640 if (current == NULL)
1641 Py_RETURN_NONE;
1642 return cipher_to_tuple(current);
1643}
1644
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001645/*[clinic input]
1646_ssl._SSLSocket.version
1647[clinic start generated code]*/
1648
1649static PyObject *
1650_ssl__SSLSocket_version_impl(PySSLSocket *self)
1651/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001652{
1653 const char *version;
1654
1655 if (self->ssl == NULL)
1656 Py_RETURN_NONE;
1657 version = SSL_get_version(self->ssl);
1658 if (!strcmp(version, "unknown"))
1659 Py_RETURN_NONE;
1660 return PyUnicode_FromString(version);
1661}
1662
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001663#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001664/*[clinic input]
1665_ssl._SSLSocket.selected_npn_protocol
1666[clinic start generated code]*/
1667
1668static PyObject *
1669_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1670/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1671{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001672 const unsigned char *out;
1673 unsigned int outlen;
1674
Victor Stinner4569cd52013-06-23 14:58:43 +02001675 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001676 &out, &outlen);
1677
1678 if (out == NULL)
1679 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001680 return PyUnicode_FromStringAndSize((char *)out, outlen);
1681}
1682#endif
1683
1684#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001685/*[clinic input]
1686_ssl._SSLSocket.selected_alpn_protocol
1687[clinic start generated code]*/
1688
1689static PyObject *
1690_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1691/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1692{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001693 const unsigned char *out;
1694 unsigned int outlen;
1695
1696 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1697
1698 if (out == NULL)
1699 Py_RETURN_NONE;
1700 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001701}
1702#endif
1703
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001704/*[clinic input]
1705_ssl._SSLSocket.compression
1706[clinic start generated code]*/
1707
1708static PyObject *
1709_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1710/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1711{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001712#ifdef OPENSSL_NO_COMP
1713 Py_RETURN_NONE;
1714#else
1715 const COMP_METHOD *comp_method;
1716 const char *short_name;
1717
1718 if (self->ssl == NULL)
1719 Py_RETURN_NONE;
1720 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001721 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001722 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001723 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001724 if (short_name == NULL)
1725 Py_RETURN_NONE;
1726 return PyUnicode_DecodeFSDefault(short_name);
1727#endif
1728}
1729
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001730static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1731 Py_INCREF(self->ctx);
1732 return self->ctx;
1733}
1734
1735static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1736 void *closure) {
1737
1738 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001739#if !HAVE_SNI
1740 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1741 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001742 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001743#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001744 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001745 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001746 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001747#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001748 } else {
1749 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1750 return -1;
1751 }
1752
1753 return 0;
1754}
1755
1756PyDoc_STRVAR(PySSL_set_context_doc,
1757"_setter_context(ctx)\n\
1758\
1759This changes the context associated with the SSLSocket. This is typically\n\
1760used from within a callback function set by the set_servername_callback\n\
1761on the SSLContext to change the certificate information associated with the\n\
1762SSLSocket before the cryptographic exchange handshake messages\n");
1763
1764
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001765static PyObject *
1766PySSL_get_server_side(PySSLSocket *self, void *c)
1767{
1768 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1769}
1770
1771PyDoc_STRVAR(PySSL_get_server_side_doc,
1772"Whether this is a server-side socket.");
1773
1774static PyObject *
1775PySSL_get_server_hostname(PySSLSocket *self, void *c)
1776{
1777 if (self->server_hostname == NULL)
1778 Py_RETURN_NONE;
1779 Py_INCREF(self->server_hostname);
1780 return self->server_hostname;
1781}
1782
1783PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1784"The currently set server hostname (for SNI).");
1785
1786static PyObject *
1787PySSL_get_owner(PySSLSocket *self, void *c)
1788{
1789 PyObject *owner;
1790
1791 if (self->owner == NULL)
1792 Py_RETURN_NONE;
1793
1794 owner = PyWeakref_GetObject(self->owner);
1795 Py_INCREF(owner);
1796 return owner;
1797}
1798
1799static int
1800PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1801{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001802 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001803 if (self->owner == NULL)
1804 return -1;
1805 return 0;
1806}
1807
1808PyDoc_STRVAR(PySSL_get_owner_doc,
1809"The Python-level owner of this object.\
1810Passed as \"self\" in servername callback.");
1811
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001812
Antoine Pitrou152efa22010-05-16 18:19:27 +00001813static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001814{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001815 if (self->ssl)
1816 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001817 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001818 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001819 Py_XDECREF(self->server_hostname);
1820 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001821 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001822}
1823
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001824/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001825 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001826 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001827 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001828
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001829static int
Victor Stinner14690702015-04-06 22:46:13 +02001830PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001831{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001832 int rc;
1833#ifdef HAVE_POLL
1834 struct pollfd pollfd;
1835 _PyTime_t ms;
1836#else
1837 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001838 fd_set fds;
1839 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001840#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001841
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001842 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001843 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001844 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001845 else if (timeout < 0) {
1846 if (s->sock_timeout > 0)
1847 return SOCKET_HAS_TIMED_OUT;
1848 else
1849 return SOCKET_IS_BLOCKING;
1850 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001851
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001852 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001853 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001854 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001855
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 /* Prefer poll, if available, since you can poll() any fd
1857 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001858#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001859 pollfd.fd = s->sock_fd;
1860 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001861
Victor Stinner14690702015-04-06 22:46:13 +02001862 /* timeout is in seconds, poll() uses milliseconds */
1863 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001864 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001865
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001866 PySSL_BEGIN_ALLOW_THREADS
1867 rc = poll(&pollfd, 1, (int)ms);
1868 PySSL_END_ALLOW_THREADS
1869#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001870 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001871 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001872 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001873
Victor Stinner14690702015-04-06 22:46:13 +02001874 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001875
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001876 FD_ZERO(&fds);
1877 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001878
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001879 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001880 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001881 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001882 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001883 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001884 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001885 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001886 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001887#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001888
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001889 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1890 (when we are able to write or when there's something to read) */
1891 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001892}
1893
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001894/*[clinic input]
1895_ssl._SSLSocket.write
1896 b: Py_buffer
1897 /
1898
1899Writes the bytes-like object b into the SSL object.
1900
1901Returns the number of bytes written.
1902[clinic start generated code]*/
1903
1904static PyObject *
1905_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1906/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001907{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001908 int len;
1909 int sockstate;
1910 int err;
1911 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001912 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001913 _PyTime_t timeout, deadline = 0;
1914 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001915
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001916 if (sock != NULL) {
1917 if (((PyObject*)sock) == Py_None) {
1918 _setSSLError("Underlying socket connection gone",
1919 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1920 return NULL;
1921 }
1922 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001923 }
1924
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001925 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001926 PyErr_Format(PyExc_OverflowError,
1927 "string longer than %d bytes", INT_MAX);
1928 goto error;
1929 }
1930
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001931 if (sock != NULL) {
1932 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001933 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001934 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1935 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1936 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001937
Victor Stinner14690702015-04-06 22:46:13 +02001938 timeout = GET_SOCKET_TIMEOUT(sock);
1939 has_timeout = (timeout > 0);
1940 if (has_timeout)
1941 deadline = _PyTime_GetMonotonicClock() + timeout;
1942
1943 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001944 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001945 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001946 "The write operation timed out");
1947 goto error;
1948 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1949 PyErr_SetString(PySSLErrorObject,
1950 "Underlying socket has been closed.");
1951 goto error;
1952 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1953 PyErr_SetString(PySSLErrorObject,
1954 "Underlying socket too large for select().");
1955 goto error;
1956 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001957
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001958 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001959 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001960 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001961 err = SSL_get_error(self->ssl, len);
1962 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001963
1964 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001965 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001966
Victor Stinner14690702015-04-06 22:46:13 +02001967 if (has_timeout)
1968 timeout = deadline - _PyTime_GetMonotonicClock();
1969
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001970 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001971 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001972 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001973 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001974 } else {
1975 sockstate = SOCKET_OPERATION_OK;
1976 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001977
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001978 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001979 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001980 "The write operation timed out");
1981 goto error;
1982 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1983 PyErr_SetString(PySSLErrorObject,
1984 "Underlying socket has been closed.");
1985 goto error;
1986 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1987 break;
1988 }
1989 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001990
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001991 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001992 if (len > 0)
1993 return PyLong_FromLong(len);
1994 else
1995 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001996
1997error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001998 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001999 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002000}
2001
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002002/*[clinic input]
2003_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002004
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002005Returns the number of already decrypted bytes available for read, pending on the connection.
2006[clinic start generated code]*/
2007
2008static PyObject *
2009_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2010/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002011{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002012 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002013
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002014 PySSL_BEGIN_ALLOW_THREADS
2015 count = SSL_pending(self->ssl);
2016 PySSL_END_ALLOW_THREADS
2017 if (count < 0)
2018 return PySSL_SetError(self, count, __FILE__, __LINE__);
2019 else
2020 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002021}
2022
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002023/*[clinic input]
2024_ssl._SSLSocket.read
2025 size as len: int
2026 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002027 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002028 ]
2029 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002030
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002031Read up to size bytes from the SSL socket.
2032[clinic start generated code]*/
2033
2034static PyObject *
2035_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2036 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002037/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002038{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002039 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002040 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002041 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002042 int sockstate;
2043 int err;
2044 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002045 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002046 _PyTime_t timeout, deadline = 0;
2047 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002048
Martin Panter5503d472016-03-27 05:35:19 +00002049 if (!group_right_1 && len < 0) {
2050 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2051 return NULL;
2052 }
2053
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002054 if (sock != NULL) {
2055 if (((PyObject*)sock) == Py_None) {
2056 _setSSLError("Underlying socket connection gone",
2057 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2058 return NULL;
2059 }
2060 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002061 }
2062
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002063 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002064 dest = PyBytes_FromStringAndSize(NULL, len);
2065 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002066 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002067 if (len == 0) {
2068 Py_XDECREF(sock);
2069 return dest;
2070 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002071 mem = PyBytes_AS_STRING(dest);
2072 }
2073 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002074 mem = buffer->buf;
2075 if (len <= 0 || len > buffer->len) {
2076 len = (int) buffer->len;
2077 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002078 PyErr_SetString(PyExc_OverflowError,
2079 "maximum length can't fit in a C 'int'");
2080 goto error;
2081 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002082 if (len == 0) {
2083 count = 0;
2084 goto done;
2085 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002086 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002087 }
2088
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002089 if (sock != NULL) {
2090 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002091 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002092 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2093 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2094 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002095
Victor Stinner14690702015-04-06 22:46:13 +02002096 timeout = GET_SOCKET_TIMEOUT(sock);
2097 has_timeout = (timeout > 0);
2098 if (has_timeout)
2099 deadline = _PyTime_GetMonotonicClock() + timeout;
2100
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002101 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002102 PySSL_BEGIN_ALLOW_THREADS
2103 count = SSL_read(self->ssl, mem, len);
2104 err = SSL_get_error(self->ssl, count);
2105 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002106
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002107 if (PyErr_CheckSignals())
2108 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002109
Victor Stinner14690702015-04-06 22:46:13 +02002110 if (has_timeout)
2111 timeout = deadline - _PyTime_GetMonotonicClock();
2112
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002113 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002114 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002115 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002116 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002117 } else if (err == SSL_ERROR_ZERO_RETURN &&
2118 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002119 {
2120 count = 0;
2121 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002122 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002123 else
2124 sockstate = SOCKET_OPERATION_OK;
2125
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002126 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002127 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002128 "The read operation timed out");
2129 goto error;
2130 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2131 break;
2132 }
2133 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002134
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002135 if (count <= 0) {
2136 PySSL_SetError(self, count, __FILE__, __LINE__);
2137 goto error;
2138 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002139
2140done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002141 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002142 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002143 _PyBytes_Resize(&dest, count);
2144 return dest;
2145 }
2146 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002147 return PyLong_FromLong(count);
2148 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002149
2150error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002151 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002152 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002153 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002154 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002155}
2156
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002157/*[clinic input]
2158_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002159
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002160Does the SSL shutdown handshake with the remote end.
2161
2162Returns the underlying socket object.
2163[clinic start generated code]*/
2164
2165static PyObject *
2166_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2167/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002168{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002169 int err, ssl_err, sockstate, nonblocking;
2170 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002171 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002172 _PyTime_t timeout, deadline = 0;
2173 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002174
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002175 if (sock != NULL) {
2176 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002177 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002178 _setSSLError("Underlying socket connection gone",
2179 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2180 return NULL;
2181 }
2182 Py_INCREF(sock);
2183
2184 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002185 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002186 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2187 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002188 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002189
Victor Stinner14690702015-04-06 22:46:13 +02002190 timeout = GET_SOCKET_TIMEOUT(sock);
2191 has_timeout = (timeout > 0);
2192 if (has_timeout)
2193 deadline = _PyTime_GetMonotonicClock() + timeout;
2194
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002195 while (1) {
2196 PySSL_BEGIN_ALLOW_THREADS
2197 /* Disable read-ahead so that unwrap can work correctly.
2198 * Otherwise OpenSSL might read in too much data,
2199 * eating clear text data that happens to be
2200 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002201 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002202 * function is used and the shutdown_seen_zero != 0
2203 * condition is met.
2204 */
2205 if (self->shutdown_seen_zero)
2206 SSL_set_read_ahead(self->ssl, 0);
2207 err = SSL_shutdown(self->ssl);
2208 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002209
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002210 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2211 if (err > 0)
2212 break;
2213 if (err == 0) {
2214 /* Don't loop endlessly; instead preserve legacy
2215 behaviour of trying SSL_shutdown() only twice.
2216 This looks necessary for OpenSSL < 0.9.8m */
2217 if (++zeros > 1)
2218 break;
2219 /* Shutdown was sent, now try receiving */
2220 self->shutdown_seen_zero = 1;
2221 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002222 }
2223
Victor Stinner14690702015-04-06 22:46:13 +02002224 if (has_timeout)
2225 timeout = deadline - _PyTime_GetMonotonicClock();
2226
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002227 /* Possibly retry shutdown until timeout or failure */
2228 ssl_err = SSL_get_error(self->ssl, err);
2229 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002230 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002231 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002232 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002233 else
2234 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002235
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002236 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2237 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002238 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002239 "The read operation timed out");
2240 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002241 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002242 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002243 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002244 }
2245 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2246 PyErr_SetString(PySSLErrorObject,
2247 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002248 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002249 }
2250 else if (sockstate != SOCKET_OPERATION_OK)
2251 /* Retain the SSL error code */
2252 break;
2253 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002254
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002255 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002256 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002257 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002258 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002259 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002260 /* It's already INCREF'ed */
2261 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002262 else
2263 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002264
2265error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002266 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002267 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002268}
2269
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002270/*[clinic input]
2271_ssl._SSLSocket.tls_unique_cb
2272
2273Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2274
2275If the TLS handshake is not yet complete, None is returned.
2276[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002277
Antoine Pitroud6494802011-07-21 01:11:30 +02002278static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002279_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2280/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002281{
2282 PyObject *retval = NULL;
2283 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002284 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002285
2286 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2287 /* if session is resumed XOR we are the client */
2288 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2289 }
2290 else {
2291 /* if a new session XOR we are the server */
2292 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2293 }
2294
2295 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002296 if (len == 0)
2297 Py_RETURN_NONE;
2298
2299 retval = PyBytes_FromStringAndSize(buf, len);
2300
2301 return retval;
2302}
2303
Christian Heimes99a65702016-09-10 23:44:53 +02002304#ifdef OPENSSL_VERSION_1_1
2305
2306static SSL_SESSION*
2307_ssl_session_dup(SSL_SESSION *session) {
2308 SSL_SESSION *newsession = NULL;
2309 int slen;
2310 unsigned char *senc = NULL, *p;
2311 const unsigned char *const_p;
2312
2313 if (session == NULL) {
2314 PyErr_SetString(PyExc_ValueError, "Invalid session");
2315 goto error;
2316 }
2317
2318 /* get length */
2319 slen = i2d_SSL_SESSION(session, NULL);
2320 if (slen == 0 || slen > 0xFF00) {
2321 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2322 goto error;
2323 }
2324 if ((senc = PyMem_Malloc(slen)) == NULL) {
2325 PyErr_NoMemory();
2326 goto error;
2327 }
2328 p = senc;
2329 if (!i2d_SSL_SESSION(session, &p)) {
2330 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2331 goto error;
2332 }
2333 const_p = senc;
2334 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2335 if (session == NULL) {
2336 goto error;
2337 }
2338 PyMem_Free(senc);
2339 return newsession;
2340 error:
2341 if (senc != NULL) {
2342 PyMem_Free(senc);
2343 }
2344 return NULL;
2345}
2346#endif
2347
2348static PyObject *
2349PySSL_get_session(PySSLSocket *self, void *closure) {
2350 /* get_session can return sessions from a server-side connection,
2351 * it does not check for handshake done or client socket. */
2352 PySSLSession *pysess;
2353 SSL_SESSION *session;
2354
2355#ifdef OPENSSL_VERSION_1_1
2356 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2357 * https://github.com/openssl/openssl/issues/1550 */
2358 session = SSL_get0_session(self->ssl); /* borrowed reference */
2359 if (session == NULL) {
2360 Py_RETURN_NONE;
2361 }
2362 if ((session = _ssl_session_dup(session)) == NULL) {
2363 return NULL;
2364 }
2365#else
2366 session = SSL_get1_session(self->ssl);
2367 if (session == NULL) {
2368 Py_RETURN_NONE;
2369 }
2370#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002371 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002372 if (pysess == NULL) {
2373 SSL_SESSION_free(session);
2374 return NULL;
2375 }
2376
2377 assert(self->ctx);
2378 pysess->ctx = self->ctx;
2379 Py_INCREF(pysess->ctx);
2380 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002381 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002382 return (PyObject *)pysess;
2383}
2384
2385static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2386 void *closure)
2387 {
2388 PySSLSession *pysess;
2389#ifdef OPENSSL_VERSION_1_1
2390 SSL_SESSION *session;
2391#endif
2392 int result;
2393
2394 if (!PySSLSession_Check(value)) {
2395 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2396 return -1;
2397 }
2398 pysess = (PySSLSession *)value;
2399
2400 if (self->ctx->ctx != pysess->ctx->ctx) {
2401 PyErr_SetString(PyExc_ValueError,
2402 "Session refers to a different SSLContext.");
2403 return -1;
2404 }
2405 if (self->socket_type != PY_SSL_CLIENT) {
2406 PyErr_SetString(PyExc_ValueError,
2407 "Cannot set session for server-side SSLSocket.");
2408 return -1;
2409 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002410 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002411 PyErr_SetString(PyExc_ValueError,
2412 "Cannot set session after handshake.");
2413 return -1;
2414 }
2415#ifdef OPENSSL_VERSION_1_1
2416 /* duplicate session */
2417 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2418 return -1;
2419 }
2420 result = SSL_set_session(self->ssl, session);
2421 /* free duplicate, SSL_set_session() bumps ref count */
2422 SSL_SESSION_free(session);
2423#else
2424 result = SSL_set_session(self->ssl, pysess->session);
2425#endif
2426 if (result == 0) {
2427 _setSSLError(NULL, 0, __FILE__, __LINE__);
2428 return -1;
2429 }
2430 return 0;
2431}
2432
2433PyDoc_STRVAR(PySSL_set_session_doc,
2434"_setter_session(session)\n\
2435\
2436Get / set SSLSession.");
2437
2438static PyObject *
2439PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2440 if (SSL_session_reused(self->ssl)) {
2441 Py_RETURN_TRUE;
2442 } else {
2443 Py_RETURN_FALSE;
2444 }
2445}
2446
2447PyDoc_STRVAR(PySSL_get_session_reused_doc,
2448"Was the client session reused during handshake?");
2449
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002450static PyGetSetDef ssl_getsetlist[] = {
2451 {"context", (getter) PySSL_get_context,
2452 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002453 {"server_side", (getter) PySSL_get_server_side, NULL,
2454 PySSL_get_server_side_doc},
2455 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2456 PySSL_get_server_hostname_doc},
2457 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2458 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002459 {"session", (getter) PySSL_get_session,
2460 (setter) PySSL_set_session, PySSL_set_session_doc},
2461 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2462 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002463 {NULL}, /* sentinel */
2464};
2465
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002466static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002467 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2468 _SSL__SSLSOCKET_WRITE_METHODDEF
2469 _SSL__SSLSOCKET_READ_METHODDEF
2470 _SSL__SSLSOCKET_PENDING_METHODDEF
2471 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2472 _SSL__SSLSOCKET_CIPHER_METHODDEF
2473 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2474 _SSL__SSLSOCKET_VERSION_METHODDEF
2475 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2476 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2477 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2478 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2479 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002480 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002481};
2482
Antoine Pitrou152efa22010-05-16 18:19:27 +00002483static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002484 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002485 "_ssl._SSLSocket", /*tp_name*/
2486 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002487 0, /*tp_itemsize*/
2488 /* methods */
2489 (destructor)PySSL_dealloc, /*tp_dealloc*/
2490 0, /*tp_print*/
2491 0, /*tp_getattr*/
2492 0, /*tp_setattr*/
2493 0, /*tp_reserved*/
2494 0, /*tp_repr*/
2495 0, /*tp_as_number*/
2496 0, /*tp_as_sequence*/
2497 0, /*tp_as_mapping*/
2498 0, /*tp_hash*/
2499 0, /*tp_call*/
2500 0, /*tp_str*/
2501 0, /*tp_getattro*/
2502 0, /*tp_setattro*/
2503 0, /*tp_as_buffer*/
2504 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2505 0, /*tp_doc*/
2506 0, /*tp_traverse*/
2507 0, /*tp_clear*/
2508 0, /*tp_richcompare*/
2509 0, /*tp_weaklistoffset*/
2510 0, /*tp_iter*/
2511 0, /*tp_iternext*/
2512 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002513 0, /*tp_members*/
2514 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002515};
2516
Antoine Pitrou152efa22010-05-16 18:19:27 +00002517
2518/*
2519 * _SSLContext objects
2520 */
2521
Christian Heimes5fe668c2016-09-12 00:01:11 +02002522static int
2523_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2524{
2525 int mode;
2526 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2527
2528 switch(n) {
2529 case PY_SSL_CERT_NONE:
2530 mode = SSL_VERIFY_NONE;
2531 break;
2532 case PY_SSL_CERT_OPTIONAL:
2533 mode = SSL_VERIFY_PEER;
2534 break;
2535 case PY_SSL_CERT_REQUIRED:
2536 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2537 break;
2538 default:
2539 PyErr_SetString(PyExc_ValueError,
2540 "invalid value for verify_mode");
2541 return -1;
2542 }
2543 /* keep current verify cb */
2544 verify_cb = SSL_CTX_get_verify_callback(ctx);
2545 SSL_CTX_set_verify(ctx, mode, verify_cb);
2546 return 0;
2547}
2548
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002549/*[clinic input]
2550@classmethod
2551_ssl._SSLContext.__new__
2552 protocol as proto_version: int
2553 /
2554[clinic start generated code]*/
2555
Antoine Pitrou152efa22010-05-16 18:19:27 +00002556static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002557_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2558/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002559{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002560 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002561 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002562 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002563 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002564#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002565 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002566#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002567
Antoine Pitrou152efa22010-05-16 18:19:27 +00002568 PySSL_BEGIN_ALLOW_THREADS
2569 if (proto_version == PY_SSL_VERSION_TLS1)
2570 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002571#if HAVE_TLSv1_2
2572 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2573 ctx = SSL_CTX_new(TLSv1_1_method());
2574 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2575 ctx = SSL_CTX_new(TLSv1_2_method());
2576#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002577#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002578 else if (proto_version == PY_SSL_VERSION_SSL3)
2579 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002580#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002581#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002582 else if (proto_version == PY_SSL_VERSION_SSL2)
2583 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002584#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002585 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002586 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002587 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2588 ctx = SSL_CTX_new(TLS_client_method());
2589 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2590 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002591 else
2592 proto_version = -1;
2593 PySSL_END_ALLOW_THREADS
2594
2595 if (proto_version == -1) {
2596 PyErr_SetString(PyExc_ValueError,
2597 "invalid protocol version");
2598 return NULL;
2599 }
2600 if (ctx == NULL) {
2601 PyErr_SetString(PySSLErrorObject,
2602 "failed to allocate SSL context");
2603 return NULL;
2604 }
2605
2606 assert(type != NULL && type->tp_alloc != NULL);
2607 self = (PySSLContext *) type->tp_alloc(type, 0);
2608 if (self == NULL) {
2609 SSL_CTX_free(ctx);
2610 return NULL;
2611 }
2612 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002613#ifdef OPENSSL_NPN_NEGOTIATED
2614 self->npn_protocols = NULL;
2615#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002616#ifdef HAVE_ALPN
2617 self->alpn_protocols = NULL;
2618#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002619#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002620 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002621#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002622 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002623 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2624 self->check_hostname = 1;
2625 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2626 Py_DECREF(self);
2627 return NULL;
2628 }
2629 } else {
2630 self->check_hostname = 0;
2631 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2632 Py_DECREF(self);
2633 return NULL;
2634 }
2635 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002636 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002637 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2638 if (proto_version != PY_SSL_VERSION_SSL2)
2639 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002640 if (proto_version != PY_SSL_VERSION_SSL3)
2641 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002642 /* Minimal security flags for server and client side context.
2643 * Client sockets ignore server-side parameters. */
2644#ifdef SSL_OP_NO_COMPRESSION
2645 options |= SSL_OP_NO_COMPRESSION;
2646#endif
2647#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2648 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2649#endif
2650#ifdef SSL_OP_SINGLE_DH_USE
2651 options |= SSL_OP_SINGLE_DH_USE;
2652#endif
2653#ifdef SSL_OP_SINGLE_ECDH_USE
2654 options |= SSL_OP_SINGLE_ECDH_USE;
2655#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002656 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002657
Christian Heimes358cfd42016-09-10 22:43:48 +02002658 /* A bare minimum cipher list without completly broken cipher suites.
2659 * It's far from perfect but gives users a better head start. */
2660 if (proto_version != PY_SSL_VERSION_SSL2) {
2661 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2662 } else {
2663 /* SSLv2 needs MD5 */
2664 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2665 }
2666 if (result == 0) {
2667 Py_DECREF(self);
2668 ERR_clear_error();
2669 PyErr_SetString(PySSLErrorObject,
2670 "No cipher can be selected.");
2671 return NULL;
2672 }
2673
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002674#if defined(SSL_MODE_RELEASE_BUFFERS)
2675 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2676 usage for no cost at all. However, don't do this for OpenSSL versions
2677 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2678 2014-0198. I can't find exactly which beta fixed this CVE, so be
2679 conservative and assume it wasn't fixed until release. We do this check
2680 at runtime to avoid problems from the dynamic linker.
2681 See #25672 for more on this. */
2682 libver = SSLeay();
2683 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2684 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2685 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2686 }
2687#endif
2688
2689
Donald Stufft8ae264c2017-03-02 11:45:29 -05002690#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002691 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2692 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002693 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2694 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002695#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002696 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2697#else
2698 {
2699 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2700 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2701 EC_KEY_free(key);
2702 }
2703#endif
2704#endif
2705
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002706#define SID_CTX "Python"
2707 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2708 sizeof(SID_CTX));
2709#undef SID_CTX
2710
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002711#ifdef X509_V_FLAG_TRUSTED_FIRST
2712 {
2713 /* Improve trust chain building when cross-signed intermediate
2714 certificates are present. See https://bugs.python.org/issue23476. */
2715 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2716 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2717 }
2718#endif
2719
Antoine Pitrou152efa22010-05-16 18:19:27 +00002720 return (PyObject *)self;
2721}
2722
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002723static int
2724context_traverse(PySSLContext *self, visitproc visit, void *arg)
2725{
2726#ifndef OPENSSL_NO_TLSEXT
2727 Py_VISIT(self->set_hostname);
2728#endif
2729 return 0;
2730}
2731
2732static int
2733context_clear(PySSLContext *self)
2734{
2735#ifndef OPENSSL_NO_TLSEXT
2736 Py_CLEAR(self->set_hostname);
2737#endif
2738 return 0;
2739}
2740
Antoine Pitrou152efa22010-05-16 18:19:27 +00002741static void
2742context_dealloc(PySSLContext *self)
2743{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002744 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002745 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002746#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002747 PyMem_FREE(self->npn_protocols);
2748#endif
2749#ifdef HAVE_ALPN
2750 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002751#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002752 Py_TYPE(self)->tp_free(self);
2753}
2754
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002755/*[clinic input]
2756_ssl._SSLContext.set_ciphers
2757 cipherlist: str
2758 /
2759[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002760
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002761static PyObject *
2762_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2763/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2764{
2765 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002766 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002767 /* Clearing the error queue is necessary on some OpenSSL versions,
2768 otherwise the error will be reported again when another SSL call
2769 is done. */
2770 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002771 PyErr_SetString(PySSLErrorObject,
2772 "No cipher can be selected.");
2773 return NULL;
2774 }
2775 Py_RETURN_NONE;
2776}
2777
Christian Heimes25bfcd52016-09-06 00:04:45 +02002778#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2779/*[clinic input]
2780_ssl._SSLContext.get_ciphers
2781[clinic start generated code]*/
2782
2783static PyObject *
2784_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2785/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2786{
2787 SSL *ssl = NULL;
2788 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002789 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002790 int i=0;
2791 PyObject *result = NULL, *dct;
2792
2793 ssl = SSL_new(self->ctx);
2794 if (ssl == NULL) {
2795 _setSSLError(NULL, 0, __FILE__, __LINE__);
2796 goto exit;
2797 }
2798 sk = SSL_get_ciphers(ssl);
2799
2800 result = PyList_New(sk_SSL_CIPHER_num(sk));
2801 if (result == NULL) {
2802 goto exit;
2803 }
2804
2805 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2806 cipher = sk_SSL_CIPHER_value(sk, i);
2807 dct = cipher_to_dict(cipher);
2808 if (dct == NULL) {
2809 Py_CLEAR(result);
2810 goto exit;
2811 }
2812 PyList_SET_ITEM(result, i, dct);
2813 }
2814
2815 exit:
2816 if (ssl != NULL)
2817 SSL_free(ssl);
2818 return result;
2819
2820}
2821#endif
2822
2823
Benjamin Petersonc54de472015-01-28 12:06:39 -05002824#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002825static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002826do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2827 const unsigned char *server_protocols, unsigned int server_protocols_len,
2828 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002829{
Benjamin Peterson88615022015-01-23 17:30:26 -05002830 int ret;
2831 if (client_protocols == NULL) {
2832 client_protocols = (unsigned char *)"";
2833 client_protocols_len = 0;
2834 }
2835 if (server_protocols == NULL) {
2836 server_protocols = (unsigned char *)"";
2837 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002838 }
2839
Benjamin Peterson88615022015-01-23 17:30:26 -05002840 ret = SSL_select_next_proto(out, outlen,
2841 server_protocols, server_protocols_len,
2842 client_protocols, client_protocols_len);
2843 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2844 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002845
2846 return SSL_TLSEXT_ERR_OK;
2847}
2848
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002849/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2850static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002851_advertiseNPN_cb(SSL *s,
2852 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002853 void *args)
2854{
2855 PySSLContext *ssl_ctx = (PySSLContext *) args;
2856
2857 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002858 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002859 *len = 0;
2860 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002861 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002862 *len = ssl_ctx->npn_protocols_len;
2863 }
2864
2865 return SSL_TLSEXT_ERR_OK;
2866}
2867/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2868static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002869_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002870 unsigned char **out, unsigned char *outlen,
2871 const unsigned char *server, unsigned int server_len,
2872 void *args)
2873{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002874 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002875 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002876 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002877}
2878#endif
2879
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002880/*[clinic input]
2881_ssl._SSLContext._set_npn_protocols
2882 protos: Py_buffer
2883 /
2884[clinic start generated code]*/
2885
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002886static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002887_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2888 Py_buffer *protos)
2889/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002890{
2891#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002892 PyMem_Free(self->npn_protocols);
2893 self->npn_protocols = PyMem_Malloc(protos->len);
2894 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002895 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002896 memcpy(self->npn_protocols, protos->buf, protos->len);
2897 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002898
2899 /* set both server and client callbacks, because the context can
2900 * be used to create both types of sockets */
2901 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2902 _advertiseNPN_cb,
2903 self);
2904 SSL_CTX_set_next_proto_select_cb(self->ctx,
2905 _selectNPN_cb,
2906 self);
2907
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002908 Py_RETURN_NONE;
2909#else
2910 PyErr_SetString(PyExc_NotImplementedError,
2911 "The NPN extension requires OpenSSL 1.0.1 or later.");
2912 return NULL;
2913#endif
2914}
2915
Benjamin Petersoncca27322015-01-23 16:35:37 -05002916#ifdef HAVE_ALPN
2917static int
2918_selectALPN_cb(SSL *s,
2919 const unsigned char **out, unsigned char *outlen,
2920 const unsigned char *client_protocols, unsigned int client_protocols_len,
2921 void *args)
2922{
2923 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002924 return do_protocol_selection(1, (unsigned char **)out, outlen,
2925 ctx->alpn_protocols, ctx->alpn_protocols_len,
2926 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002927}
2928#endif
2929
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002930/*[clinic input]
2931_ssl._SSLContext._set_alpn_protocols
2932 protos: Py_buffer
2933 /
2934[clinic start generated code]*/
2935
Benjamin Petersoncca27322015-01-23 16:35:37 -05002936static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002937_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2938 Py_buffer *protos)
2939/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002940{
2941#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002942 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002943 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002944 if (!self->alpn_protocols)
2945 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002946 memcpy(self->alpn_protocols, protos->buf, protos->len);
2947 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002948
2949 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2950 return PyErr_NoMemory();
2951 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2952
Benjamin Petersoncca27322015-01-23 16:35:37 -05002953 Py_RETURN_NONE;
2954#else
2955 PyErr_SetString(PyExc_NotImplementedError,
2956 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2957 return NULL;
2958#endif
2959}
2960
Antoine Pitrou152efa22010-05-16 18:19:27 +00002961static PyObject *
2962get_verify_mode(PySSLContext *self, void *c)
2963{
2964 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2965 case SSL_VERIFY_NONE:
2966 return PyLong_FromLong(PY_SSL_CERT_NONE);
2967 case SSL_VERIFY_PEER:
2968 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2969 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2970 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2971 }
2972 PyErr_SetString(PySSLErrorObject,
2973 "invalid return value from SSL_CTX_get_verify_mode");
2974 return NULL;
2975}
2976
2977static int
2978set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2979{
Christian Heimes5fe668c2016-09-12 00:01:11 +02002980 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002981 if (!PyArg_Parse(arg, "i", &n))
2982 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02002983 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01002984 PyErr_SetString(PyExc_ValueError,
2985 "Cannot set verify_mode to CERT_NONE when "
2986 "check_hostname is enabled.");
2987 return -1;
2988 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02002989 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002990}
2991
2992static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002993get_verify_flags(PySSLContext *self, void *c)
2994{
2995 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02002996 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01002997 unsigned long flags;
2998
2999 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003000 param = X509_STORE_get0_param(store);
3001 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003002 return PyLong_FromUnsignedLong(flags);
3003}
3004
3005static int
3006set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3007{
3008 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003009 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003010 unsigned long new_flags, flags, set, clear;
3011
3012 if (!PyArg_Parse(arg, "k", &new_flags))
3013 return -1;
3014 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003015 param = X509_STORE_get0_param(store);
3016 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003017 clear = flags & ~new_flags;
3018 set = ~flags & new_flags;
3019 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003020 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003021 _setSSLError(NULL, 0, __FILE__, __LINE__);
3022 return -1;
3023 }
3024 }
3025 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003026 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003027 _setSSLError(NULL, 0, __FILE__, __LINE__);
3028 return -1;
3029 }
3030 }
3031 return 0;
3032}
3033
3034static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003035get_options(PySSLContext *self, void *c)
3036{
3037 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3038}
3039
3040static int
3041set_options(PySSLContext *self, PyObject *arg, void *c)
3042{
3043 long new_opts, opts, set, clear;
3044 if (!PyArg_Parse(arg, "l", &new_opts))
3045 return -1;
3046 opts = SSL_CTX_get_options(self->ctx);
3047 clear = opts & ~new_opts;
3048 set = ~opts & new_opts;
3049 if (clear) {
3050#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3051 SSL_CTX_clear_options(self->ctx, clear);
3052#else
3053 PyErr_SetString(PyExc_ValueError,
3054 "can't clear options before OpenSSL 0.9.8m");
3055 return -1;
3056#endif
3057 }
3058 if (set)
3059 SSL_CTX_set_options(self->ctx, set);
3060 return 0;
3061}
3062
Christian Heimes1aa9a752013-12-02 02:41:19 +01003063static PyObject *
3064get_check_hostname(PySSLContext *self, void *c)
3065{
3066 return PyBool_FromLong(self->check_hostname);
3067}
3068
3069static int
3070set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3071{
3072 int check_hostname;
3073 if (!PyArg_Parse(arg, "p", &check_hostname))
3074 return -1;
3075 if (check_hostname &&
3076 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3077 PyErr_SetString(PyExc_ValueError,
3078 "check_hostname needs a SSL context with either "
3079 "CERT_OPTIONAL or CERT_REQUIRED");
3080 return -1;
3081 }
3082 self->check_hostname = check_hostname;
3083 return 0;
3084}
3085
3086
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003087typedef struct {
3088 PyThreadState *thread_state;
3089 PyObject *callable;
3090 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003091 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003092 int error;
3093} _PySSLPasswordInfo;
3094
3095static int
3096_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3097 const char *bad_type_error)
3098{
3099 /* Set the password and size fields of a _PySSLPasswordInfo struct
3100 from a unicode, bytes, or byte array object.
3101 The password field will be dynamically allocated and must be freed
3102 by the caller */
3103 PyObject *password_bytes = NULL;
3104 const char *data = NULL;
3105 Py_ssize_t size;
3106
3107 if (PyUnicode_Check(password)) {
3108 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3109 if (!password_bytes) {
3110 goto error;
3111 }
3112 data = PyBytes_AS_STRING(password_bytes);
3113 size = PyBytes_GET_SIZE(password_bytes);
3114 } else if (PyBytes_Check(password)) {
3115 data = PyBytes_AS_STRING(password);
3116 size = PyBytes_GET_SIZE(password);
3117 } else if (PyByteArray_Check(password)) {
3118 data = PyByteArray_AS_STRING(password);
3119 size = PyByteArray_GET_SIZE(password);
3120 } else {
3121 PyErr_SetString(PyExc_TypeError, bad_type_error);
3122 goto error;
3123 }
3124
Victor Stinner9ee02032013-06-23 15:08:23 +02003125 if (size > (Py_ssize_t)INT_MAX) {
3126 PyErr_Format(PyExc_ValueError,
3127 "password cannot be longer than %d bytes", INT_MAX);
3128 goto error;
3129 }
3130
Victor Stinner11ebff22013-07-07 17:07:52 +02003131 PyMem_Free(pw_info->password);
3132 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003133 if (!pw_info->password) {
3134 PyErr_SetString(PyExc_MemoryError,
3135 "unable to allocate password buffer");
3136 goto error;
3137 }
3138 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003139 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003140
3141 Py_XDECREF(password_bytes);
3142 return 1;
3143
3144error:
3145 Py_XDECREF(password_bytes);
3146 return 0;
3147}
3148
3149static int
3150_password_callback(char *buf, int size, int rwflag, void *userdata)
3151{
3152 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3153 PyObject *fn_ret = NULL;
3154
3155 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3156
3157 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003158 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003159 if (!fn_ret) {
3160 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3161 core python API, so we could use it to add a frame here */
3162 goto error;
3163 }
3164
3165 if (!_pwinfo_set(pw_info, fn_ret,
3166 "password callback must return a string")) {
3167 goto error;
3168 }
3169 Py_CLEAR(fn_ret);
3170 }
3171
3172 if (pw_info->size > size) {
3173 PyErr_Format(PyExc_ValueError,
3174 "password cannot be longer than %d bytes", size);
3175 goto error;
3176 }
3177
3178 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3179 memcpy(buf, pw_info->password, pw_info->size);
3180 return pw_info->size;
3181
3182error:
3183 Py_XDECREF(fn_ret);
3184 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3185 pw_info->error = 1;
3186 return -1;
3187}
3188
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003189/*[clinic input]
3190_ssl._SSLContext.load_cert_chain
3191 certfile: object
3192 keyfile: object = NULL
3193 password: object = NULL
3194
3195[clinic start generated code]*/
3196
Antoine Pitroub5218772010-05-21 09:56:06 +00003197static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003198_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3199 PyObject *keyfile, PyObject *password)
3200/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003201{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003202 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003203 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3204 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003205 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003206 int r;
3207
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003208 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003209 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003210 if (keyfile == Py_None)
3211 keyfile = NULL;
3212 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3213 PyErr_SetString(PyExc_TypeError,
3214 "certfile should be a valid filesystem path");
3215 return NULL;
3216 }
3217 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3218 PyErr_SetString(PyExc_TypeError,
3219 "keyfile should be a valid filesystem path");
3220 goto error;
3221 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003222 if (password && password != Py_None) {
3223 if (PyCallable_Check(password)) {
3224 pw_info.callable = password;
3225 } else if (!_pwinfo_set(&pw_info, password,
3226 "password should be a string or callable")) {
3227 goto error;
3228 }
3229 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3230 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3231 }
3232 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003233 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3234 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003235 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003236 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003237 if (pw_info.error) {
3238 ERR_clear_error();
3239 /* the password callback has already set the error information */
3240 }
3241 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003242 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003243 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003244 }
3245 else {
3246 _setSSLError(NULL, 0, __FILE__, __LINE__);
3247 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003248 goto error;
3249 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003250 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003251 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003252 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3253 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003254 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3255 Py_CLEAR(keyfile_bytes);
3256 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003257 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003258 if (pw_info.error) {
3259 ERR_clear_error();
3260 /* the password callback has already set the error information */
3261 }
3262 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003263 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003264 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003265 }
3266 else {
3267 _setSSLError(NULL, 0, __FILE__, __LINE__);
3268 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003269 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003270 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003271 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003272 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003273 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003274 if (r != 1) {
3275 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003276 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003277 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003278 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3279 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003280 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003281 Py_RETURN_NONE;
3282
3283error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003284 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3285 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003286 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003287 Py_XDECREF(keyfile_bytes);
3288 Py_XDECREF(certfile_bytes);
3289 return NULL;
3290}
3291
Christian Heimesefff7062013-11-21 03:35:02 +01003292/* internal helper function, returns -1 on error
3293 */
3294static int
3295_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3296 int filetype)
3297{
3298 BIO *biobuf = NULL;
3299 X509_STORE *store;
3300 int retval = 0, err, loaded = 0;
3301
3302 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3303
3304 if (len <= 0) {
3305 PyErr_SetString(PyExc_ValueError,
3306 "Empty certificate data");
3307 return -1;
3308 } else if (len > INT_MAX) {
3309 PyErr_SetString(PyExc_OverflowError,
3310 "Certificate data is too long.");
3311 return -1;
3312 }
3313
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003314 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003315 if (biobuf == NULL) {
3316 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3317 return -1;
3318 }
3319
3320 store = SSL_CTX_get_cert_store(self->ctx);
3321 assert(store != NULL);
3322
3323 while (1) {
3324 X509 *cert = NULL;
3325 int r;
3326
3327 if (filetype == SSL_FILETYPE_ASN1) {
3328 cert = d2i_X509_bio(biobuf, NULL);
3329 } else {
3330 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003331 SSL_CTX_get_default_passwd_cb(self->ctx),
3332 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3333 );
Christian Heimesefff7062013-11-21 03:35:02 +01003334 }
3335 if (cert == NULL) {
3336 break;
3337 }
3338 r = X509_STORE_add_cert(store, cert);
3339 X509_free(cert);
3340 if (!r) {
3341 err = ERR_peek_last_error();
3342 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3343 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3344 /* cert already in hash table, not an error */
3345 ERR_clear_error();
3346 } else {
3347 break;
3348 }
3349 }
3350 loaded++;
3351 }
3352
3353 err = ERR_peek_last_error();
3354 if ((filetype == SSL_FILETYPE_ASN1) &&
3355 (loaded > 0) &&
3356 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3357 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3358 /* EOF ASN1 file, not an error */
3359 ERR_clear_error();
3360 retval = 0;
3361 } else if ((filetype == SSL_FILETYPE_PEM) &&
3362 (loaded > 0) &&
3363 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3364 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3365 /* EOF PEM file, not an error */
3366 ERR_clear_error();
3367 retval = 0;
3368 } else {
3369 _setSSLError(NULL, 0, __FILE__, __LINE__);
3370 retval = -1;
3371 }
3372
3373 BIO_free(biobuf);
3374 return retval;
3375}
3376
3377
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003378/*[clinic input]
3379_ssl._SSLContext.load_verify_locations
3380 cafile: object = NULL
3381 capath: object = NULL
3382 cadata: object = NULL
3383
3384[clinic start generated code]*/
3385
Antoine Pitrou152efa22010-05-16 18:19:27 +00003386static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003387_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3388 PyObject *cafile,
3389 PyObject *capath,
3390 PyObject *cadata)
3391/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003392{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003393 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3394 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003395 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003396
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003397 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003398 if (cafile == Py_None)
3399 cafile = NULL;
3400 if (capath == Py_None)
3401 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003402 if (cadata == Py_None)
3403 cadata = NULL;
3404
3405 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003406 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003407 "cafile, capath and cadata cannot be all omitted");
3408 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003409 }
3410 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3411 PyErr_SetString(PyExc_TypeError,
3412 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003413 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003414 }
3415 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003416 PyErr_SetString(PyExc_TypeError,
3417 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003418 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003419 }
Christian Heimesefff7062013-11-21 03:35:02 +01003420
3421 /* validata cadata type and load cadata */
3422 if (cadata) {
3423 Py_buffer buf;
3424 PyObject *cadata_ascii = NULL;
3425
3426 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3427 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3428 PyBuffer_Release(&buf);
3429 PyErr_SetString(PyExc_TypeError,
3430 "cadata should be a contiguous buffer with "
3431 "a single dimension");
3432 goto error;
3433 }
3434 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3435 PyBuffer_Release(&buf);
3436 if (r == -1) {
3437 goto error;
3438 }
3439 } else {
3440 PyErr_Clear();
3441 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3442 if (cadata_ascii == NULL) {
3443 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003444 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003445 "bytes-like object");
3446 goto error;
3447 }
3448 r = _add_ca_certs(self,
3449 PyBytes_AS_STRING(cadata_ascii),
3450 PyBytes_GET_SIZE(cadata_ascii),
3451 SSL_FILETYPE_PEM);
3452 Py_DECREF(cadata_ascii);
3453 if (r == -1) {
3454 goto error;
3455 }
3456 }
3457 }
3458
3459 /* load cafile or capath */
3460 if (cafile || capath) {
3461 if (cafile)
3462 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3463 if (capath)
3464 capath_buf = PyBytes_AS_STRING(capath_bytes);
3465 PySSL_BEGIN_ALLOW_THREADS
3466 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3467 PySSL_END_ALLOW_THREADS
3468 if (r != 1) {
3469 ok = 0;
3470 if (errno != 0) {
3471 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003472 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003473 }
3474 else {
3475 _setSSLError(NULL, 0, __FILE__, __LINE__);
3476 }
3477 goto error;
3478 }
3479 }
3480 goto end;
3481
3482 error:
3483 ok = 0;
3484 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003485 Py_XDECREF(cafile_bytes);
3486 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003487 if (ok) {
3488 Py_RETURN_NONE;
3489 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003490 return NULL;
3491 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003492}
3493
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003494/*[clinic input]
3495_ssl._SSLContext.load_dh_params
3496 path as filepath: object
3497 /
3498
3499[clinic start generated code]*/
3500
Antoine Pitrou152efa22010-05-16 18:19:27 +00003501static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003502_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3503/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003504{
3505 FILE *f;
3506 DH *dh;
3507
Victor Stinnerdaf45552013-08-28 00:53:59 +02003508 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003509 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003510 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003511
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003512 errno = 0;
3513 PySSL_BEGIN_ALLOW_THREADS
3514 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003515 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003516 PySSL_END_ALLOW_THREADS
3517 if (dh == NULL) {
3518 if (errno != 0) {
3519 ERR_clear_error();
3520 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3521 }
3522 else {
3523 _setSSLError(NULL, 0, __FILE__, __LINE__);
3524 }
3525 return NULL;
3526 }
3527 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3528 _setSSLError(NULL, 0, __FILE__, __LINE__);
3529 DH_free(dh);
3530 Py_RETURN_NONE;
3531}
3532
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003533/*[clinic input]
3534_ssl._SSLContext._wrap_socket
3535 sock: object(subclass_of="PySocketModule.Sock_Type")
3536 server_side: int
3537 server_hostname as hostname_obj: object = None
3538
3539[clinic start generated code]*/
3540
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003541static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003542_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3543 int server_side, PyObject *hostname_obj)
3544/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003545{
Antoine Pitroud5323212010-10-22 18:19:07 +00003546 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003547 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003548
Antoine Pitroud5323212010-10-22 18:19:07 +00003549 /* server_hostname is either None (or absent), or to be encoded
3550 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003551 if (hostname_obj != Py_None) {
3552 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003553 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003554 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003555
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003556 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3557 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003558 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003559 if (hostname != NULL)
3560 PyMem_Free(hostname);
3561 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003562}
3563
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003564/*[clinic input]
3565_ssl._SSLContext._wrap_bio
3566 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3567 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3568 server_side: int
3569 server_hostname as hostname_obj: object = None
3570
3571[clinic start generated code]*/
3572
Antoine Pitroub0182c82010-10-12 20:09:02 +00003573static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003574_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3575 PySSLMemoryBIO *outgoing, int server_side,
3576 PyObject *hostname_obj)
3577/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003578{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003579 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003580 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003581
3582 /* server_hostname is either None (or absent), or to be encoded
3583 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003584 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003585 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3586 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003587 }
3588
3589 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3590 incoming, outgoing);
3591
3592 PyMem_Free(hostname);
3593 return res;
3594}
3595
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003596/*[clinic input]
3597_ssl._SSLContext.session_stats
3598[clinic start generated code]*/
3599
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003600static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003601_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3602/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003603{
3604 int r;
3605 PyObject *value, *stats = PyDict_New();
3606 if (!stats)
3607 return NULL;
3608
3609#define ADD_STATS(SSL_NAME, KEY_NAME) \
3610 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3611 if (value == NULL) \
3612 goto error; \
3613 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3614 Py_DECREF(value); \
3615 if (r < 0) \
3616 goto error;
3617
3618 ADD_STATS(number, "number");
3619 ADD_STATS(connect, "connect");
3620 ADD_STATS(connect_good, "connect_good");
3621 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3622 ADD_STATS(accept, "accept");
3623 ADD_STATS(accept_good, "accept_good");
3624 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3625 ADD_STATS(accept, "accept");
3626 ADD_STATS(hits, "hits");
3627 ADD_STATS(misses, "misses");
3628 ADD_STATS(timeouts, "timeouts");
3629 ADD_STATS(cache_full, "cache_full");
3630
3631#undef ADD_STATS
3632
3633 return stats;
3634
3635error:
3636 Py_DECREF(stats);
3637 return NULL;
3638}
3639
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003640/*[clinic input]
3641_ssl._SSLContext.set_default_verify_paths
3642[clinic start generated code]*/
3643
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003644static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003645_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3646/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003647{
3648 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3649 _setSSLError(NULL, 0, __FILE__, __LINE__);
3650 return NULL;
3651 }
3652 Py_RETURN_NONE;
3653}
3654
Antoine Pitrou501da612011-12-21 09:27:41 +01003655#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003656/*[clinic input]
3657_ssl._SSLContext.set_ecdh_curve
3658 name: object
3659 /
3660
3661[clinic start generated code]*/
3662
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003663static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003664_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3665/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003666{
3667 PyObject *name_bytes;
3668 int nid;
3669 EC_KEY *key;
3670
3671 if (!PyUnicode_FSConverter(name, &name_bytes))
3672 return NULL;
3673 assert(PyBytes_Check(name_bytes));
3674 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3675 Py_DECREF(name_bytes);
3676 if (nid == 0) {
3677 PyErr_Format(PyExc_ValueError,
3678 "unknown elliptic curve name %R", name);
3679 return NULL;
3680 }
3681 key = EC_KEY_new_by_curve_name(nid);
3682 if (key == NULL) {
3683 _setSSLError(NULL, 0, __FILE__, __LINE__);
3684 return NULL;
3685 }
3686 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3687 EC_KEY_free(key);
3688 Py_RETURN_NONE;
3689}
Antoine Pitrou501da612011-12-21 09:27:41 +01003690#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003691
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003692#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003693static int
3694_servername_callback(SSL *s, int *al, void *args)
3695{
3696 int ret;
3697 PySSLContext *ssl_ctx = (PySSLContext *) args;
3698 PySSLSocket *ssl;
3699 PyObject *servername_o;
3700 PyObject *servername_idna;
3701 PyObject *result;
3702 /* The high-level ssl.SSLSocket object */
3703 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003704 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003705#ifdef WITH_THREAD
3706 PyGILState_STATE gstate = PyGILState_Ensure();
3707#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003708
3709 if (ssl_ctx->set_hostname == NULL) {
3710 /* remove race condition in this the call back while if removing the
3711 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003712#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003713 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003714#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003715 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003716 }
3717
3718 ssl = SSL_get_app_data(s);
3719 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003720
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003721 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003722 * SSL connection and that has a .context attribute that can be changed to
3723 * identify the requested hostname. Since the official API is the Python
3724 * level API we want to pass the callback a Python level object rather than
3725 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3726 * SSLObject) that will be passed. Otherwise if there's a socket then that
3727 * will be passed. If both do not exist only then the C-level object is
3728 * passed. */
3729 if (ssl->owner)
3730 ssl_socket = PyWeakref_GetObject(ssl->owner);
3731 else if (ssl->Socket)
3732 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3733 else
3734 ssl_socket = (PyObject *) ssl;
3735
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003736 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003737 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003738 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003739
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003740 if (servername == NULL) {
3741 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3742 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003743 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003744 else {
3745 servername_o = PyBytes_FromString(servername);
3746 if (servername_o == NULL) {
3747 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3748 goto error;
3749 }
3750 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3751 if (servername_idna == NULL) {
3752 PyErr_WriteUnraisable(servername_o);
3753 Py_DECREF(servername_o);
3754 goto error;
3755 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003756 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003757 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3758 servername_idna, ssl_ctx, NULL);
3759 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003760 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003761 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003762
3763 if (result == NULL) {
3764 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3765 *al = SSL_AD_HANDSHAKE_FAILURE;
3766 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3767 }
3768 else {
3769 if (result != Py_None) {
3770 *al = (int) PyLong_AsLong(result);
3771 if (PyErr_Occurred()) {
3772 PyErr_WriteUnraisable(result);
3773 *al = SSL_AD_INTERNAL_ERROR;
3774 }
3775 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3776 }
3777 else {
3778 ret = SSL_TLSEXT_ERR_OK;
3779 }
3780 Py_DECREF(result);
3781 }
3782
Stefan Krah20d60802013-01-17 17:07:17 +01003783#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003784 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003785#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003786 return ret;
3787
3788error:
3789 Py_DECREF(ssl_socket);
3790 *al = SSL_AD_INTERNAL_ERROR;
3791 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003792#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003793 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003794#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003795 return ret;
3796}
Antoine Pitroua5963382013-03-30 16:39:00 +01003797#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003798
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003799/*[clinic input]
3800_ssl._SSLContext.set_servername_callback
3801 method as cb: object
3802 /
3803
3804Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3805
3806If the argument is None then the callback is disabled. The method is called
3807with the SSLSocket, the server name as a string, and the SSLContext object.
3808See RFC 6066 for details of the SNI extension.
3809[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003810
3811static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003812_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3813/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003814{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003815#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003816 Py_CLEAR(self->set_hostname);
3817 if (cb == Py_None) {
3818 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3819 }
3820 else {
3821 if (!PyCallable_Check(cb)) {
3822 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3823 PyErr_SetString(PyExc_TypeError,
3824 "not a callable object");
3825 return NULL;
3826 }
3827 Py_INCREF(cb);
3828 self->set_hostname = cb;
3829 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3830 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3831 }
3832 Py_RETURN_NONE;
3833#else
3834 PyErr_SetString(PyExc_NotImplementedError,
3835 "The TLS extension servername callback, "
3836 "SSL_CTX_set_tlsext_servername_callback, "
3837 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003838 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003839#endif
3840}
3841
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003842/*[clinic input]
3843_ssl._SSLContext.cert_store_stats
3844
3845Returns quantities of loaded X.509 certificates.
3846
3847X.509 certificates with a CA extension and certificate revocation lists
3848inside the context's cert store.
3849
3850NOTE: Certificates in a capath directory aren't loaded unless they have
3851been used at least once.
3852[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003853
3854static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003855_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3856/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003857{
3858 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003859 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003860 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003861 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003862
3863 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003864 objs = X509_STORE_get0_objects(store);
3865 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3866 obj = sk_X509_OBJECT_value(objs, i);
3867 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003868 case X509_LU_X509:
3869 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003870 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003871 ca++;
3872 }
3873 break;
3874 case X509_LU_CRL:
3875 crl++;
3876 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003877 default:
3878 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3879 * As far as I can tell they are internal states and never
3880 * stored in a cert store */
3881 break;
3882 }
3883 }
3884 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3885 "x509_ca", ca);
3886}
3887
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003888/*[clinic input]
3889_ssl._SSLContext.get_ca_certs
3890 binary_form: bool = False
3891
3892Returns a list of dicts with information of loaded CA certs.
3893
3894If the optional argument is True, returns a DER-encoded copy of the CA
3895certificate.
3896
3897NOTE: Certificates in a capath directory aren't loaded unless they have
3898been used at least once.
3899[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003900
3901static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003902_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3903/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003904{
3905 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003906 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003907 PyObject *ci = NULL, *rlist = NULL;
3908 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003909
3910 if ((rlist = PyList_New(0)) == NULL) {
3911 return NULL;
3912 }
3913
3914 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003915 objs = X509_STORE_get0_objects(store);
3916 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003917 X509_OBJECT *obj;
3918 X509 *cert;
3919
Christian Heimes598894f2016-09-05 23:19:05 +02003920 obj = sk_X509_OBJECT_value(objs, i);
3921 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003922 /* not a x509 cert */
3923 continue;
3924 }
3925 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003926 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003927 if (!X509_check_ca(cert)) {
3928 continue;
3929 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003930 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003931 ci = _certificate_to_der(cert);
3932 } else {
3933 ci = _decode_certificate(cert);
3934 }
3935 if (ci == NULL) {
3936 goto error;
3937 }
3938 if (PyList_Append(rlist, ci) == -1) {
3939 goto error;
3940 }
3941 Py_CLEAR(ci);
3942 }
3943 return rlist;
3944
3945 error:
3946 Py_XDECREF(ci);
3947 Py_XDECREF(rlist);
3948 return NULL;
3949}
3950
3951
Antoine Pitrou152efa22010-05-16 18:19:27 +00003952static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003953 {"check_hostname", (getter) get_check_hostname,
3954 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003955 {"options", (getter) get_options,
3956 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003957 {"verify_flags", (getter) get_verify_flags,
3958 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003959 {"verify_mode", (getter) get_verify_mode,
3960 (setter) set_verify_mode, NULL},
3961 {NULL}, /* sentinel */
3962};
3963
3964static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003965 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
3966 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
3967 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
3968 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
3969 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
3970 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
3971 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
3972 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
3973 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
3974 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
3975 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
3976 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
3977 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
3978 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02003979 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00003980 {NULL, NULL} /* sentinel */
3981};
3982
3983static PyTypeObject PySSLContext_Type = {
3984 PyVarObject_HEAD_INIT(NULL, 0)
3985 "_ssl._SSLContext", /*tp_name*/
3986 sizeof(PySSLContext), /*tp_basicsize*/
3987 0, /*tp_itemsize*/
3988 (destructor)context_dealloc, /*tp_dealloc*/
3989 0, /*tp_print*/
3990 0, /*tp_getattr*/
3991 0, /*tp_setattr*/
3992 0, /*tp_reserved*/
3993 0, /*tp_repr*/
3994 0, /*tp_as_number*/
3995 0, /*tp_as_sequence*/
3996 0, /*tp_as_mapping*/
3997 0, /*tp_hash*/
3998 0, /*tp_call*/
3999 0, /*tp_str*/
4000 0, /*tp_getattro*/
4001 0, /*tp_setattro*/
4002 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004003 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004004 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004005 (traverseproc) context_traverse, /*tp_traverse*/
4006 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004007 0, /*tp_richcompare*/
4008 0, /*tp_weaklistoffset*/
4009 0, /*tp_iter*/
4010 0, /*tp_iternext*/
4011 context_methods, /*tp_methods*/
4012 0, /*tp_members*/
4013 context_getsetlist, /*tp_getset*/
4014 0, /*tp_base*/
4015 0, /*tp_dict*/
4016 0, /*tp_descr_get*/
4017 0, /*tp_descr_set*/
4018 0, /*tp_dictoffset*/
4019 0, /*tp_init*/
4020 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004021 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004022};
4023
4024
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004025/*
4026 * MemoryBIO objects
4027 */
4028
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004029/*[clinic input]
4030@classmethod
4031_ssl.MemoryBIO.__new__
4032
4033[clinic start generated code]*/
4034
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004035static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004036_ssl_MemoryBIO_impl(PyTypeObject *type)
4037/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004038{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004039 BIO *bio;
4040 PySSLMemoryBIO *self;
4041
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004042 bio = BIO_new(BIO_s_mem());
4043 if (bio == NULL) {
4044 PyErr_SetString(PySSLErrorObject,
4045 "failed to allocate BIO");
4046 return NULL;
4047 }
4048 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4049 * just that no data is currently available. The SSL routines should retry
4050 * the read, which we can achieve by calling BIO_set_retry_read(). */
4051 BIO_set_retry_read(bio);
4052 BIO_set_mem_eof_return(bio, -1);
4053
4054 assert(type != NULL && type->tp_alloc != NULL);
4055 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4056 if (self == NULL) {
4057 BIO_free(bio);
4058 return NULL;
4059 }
4060 self->bio = bio;
4061 self->eof_written = 0;
4062
4063 return (PyObject *) self;
4064}
4065
4066static void
4067memory_bio_dealloc(PySSLMemoryBIO *self)
4068{
4069 BIO_free(self->bio);
4070 Py_TYPE(self)->tp_free(self);
4071}
4072
4073static PyObject *
4074memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4075{
4076 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
4077}
4078
4079PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4080"The number of bytes pending in the memory BIO.");
4081
4082static PyObject *
4083memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4084{
4085 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4086 && self->eof_written);
4087}
4088
4089PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4090"Whether the memory BIO is at EOF.");
4091
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004092/*[clinic input]
4093_ssl.MemoryBIO.read
4094 size as len: int = -1
4095 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004096
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004097Read up to size bytes from the memory BIO.
4098
4099If size is not specified, read the entire buffer.
4100If the return value is an empty bytes instance, this means either
4101EOF or that no data is available. Use the "eof" property to
4102distinguish between the two.
4103[clinic start generated code]*/
4104
4105static PyObject *
4106_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4107/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4108{
4109 int avail, nbytes;
4110 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004111
4112 avail = BIO_ctrl_pending(self->bio);
4113 if ((len < 0) || (len > avail))
4114 len = avail;
4115
4116 result = PyBytes_FromStringAndSize(NULL, len);
4117 if ((result == NULL) || (len == 0))
4118 return result;
4119
4120 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4121 /* There should never be any short reads but check anyway. */
4122 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4123 Py_DECREF(result);
4124 return NULL;
4125 }
4126
4127 return result;
4128}
4129
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004130/*[clinic input]
4131_ssl.MemoryBIO.write
4132 b: Py_buffer
4133 /
4134
4135Writes the bytes b into the memory BIO.
4136
4137Returns the number of bytes written.
4138[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004139
4140static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004141_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4142/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004143{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004144 int nbytes;
4145
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004146 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004147 PyErr_Format(PyExc_OverflowError,
4148 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004149 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004150 }
4151
4152 if (self->eof_written) {
4153 PyErr_SetString(PySSLErrorObject,
4154 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004155 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004156 }
4157
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004158 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004159 if (nbytes < 0) {
4160 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004161 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004162 }
4163
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004164 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004165}
4166
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004167/*[clinic input]
4168_ssl.MemoryBIO.write_eof
4169
4170Write an EOF marker to the memory BIO.
4171
4172When all data has been read, the "eof" property will be True.
4173[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004174
4175static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004176_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4177/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004178{
4179 self->eof_written = 1;
4180 /* After an EOF is written, a zero return from read() should be a real EOF
4181 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4182 BIO_clear_retry_flags(self->bio);
4183 BIO_set_mem_eof_return(self->bio, 0);
4184
4185 Py_RETURN_NONE;
4186}
4187
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004188static PyGetSetDef memory_bio_getsetlist[] = {
4189 {"pending", (getter) memory_bio_get_pending, NULL,
4190 PySSL_memory_bio_pending_doc},
4191 {"eof", (getter) memory_bio_get_eof, NULL,
4192 PySSL_memory_bio_eof_doc},
4193 {NULL}, /* sentinel */
4194};
4195
4196static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004197 _SSL_MEMORYBIO_READ_METHODDEF
4198 _SSL_MEMORYBIO_WRITE_METHODDEF
4199 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004200 {NULL, NULL} /* sentinel */
4201};
4202
4203static PyTypeObject PySSLMemoryBIO_Type = {
4204 PyVarObject_HEAD_INIT(NULL, 0)
4205 "_ssl.MemoryBIO", /*tp_name*/
4206 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4207 0, /*tp_itemsize*/
4208 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4209 0, /*tp_print*/
4210 0, /*tp_getattr*/
4211 0, /*tp_setattr*/
4212 0, /*tp_reserved*/
4213 0, /*tp_repr*/
4214 0, /*tp_as_number*/
4215 0, /*tp_as_sequence*/
4216 0, /*tp_as_mapping*/
4217 0, /*tp_hash*/
4218 0, /*tp_call*/
4219 0, /*tp_str*/
4220 0, /*tp_getattro*/
4221 0, /*tp_setattro*/
4222 0, /*tp_as_buffer*/
4223 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4224 0, /*tp_doc*/
4225 0, /*tp_traverse*/
4226 0, /*tp_clear*/
4227 0, /*tp_richcompare*/
4228 0, /*tp_weaklistoffset*/
4229 0, /*tp_iter*/
4230 0, /*tp_iternext*/
4231 memory_bio_methods, /*tp_methods*/
4232 0, /*tp_members*/
4233 memory_bio_getsetlist, /*tp_getset*/
4234 0, /*tp_base*/
4235 0, /*tp_dict*/
4236 0, /*tp_descr_get*/
4237 0, /*tp_descr_set*/
4238 0, /*tp_dictoffset*/
4239 0, /*tp_init*/
4240 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004241 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004242};
4243
Antoine Pitrou152efa22010-05-16 18:19:27 +00004244
Christian Heimes99a65702016-09-10 23:44:53 +02004245/*
4246 * SSL Session object
4247 */
4248
4249static void
4250PySSLSession_dealloc(PySSLSession *self)
4251{
Christian Heimesa5d07652016-09-24 10:48:05 +02004252 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004253 Py_XDECREF(self->ctx);
4254 if (self->session != NULL) {
4255 SSL_SESSION_free(self->session);
4256 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004257 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004258}
4259
4260static PyObject *
4261PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4262{
4263 int result;
4264
4265 if (left == NULL || right == NULL) {
4266 PyErr_BadInternalCall();
4267 return NULL;
4268 }
4269
4270 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4271 Py_RETURN_NOTIMPLEMENTED;
4272 }
4273
4274 if (left == right) {
4275 result = 0;
4276 } else {
4277 const unsigned char *left_id, *right_id;
4278 unsigned int left_len, right_len;
4279 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4280 &left_len);
4281 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4282 &right_len);
4283 if (left_len == right_len) {
4284 result = memcmp(left_id, right_id, left_len);
4285 } else {
4286 result = 1;
4287 }
4288 }
4289
4290 switch (op) {
4291 case Py_EQ:
4292 if (result == 0) {
4293 Py_RETURN_TRUE;
4294 } else {
4295 Py_RETURN_FALSE;
4296 }
4297 break;
4298 case Py_NE:
4299 if (result != 0) {
4300 Py_RETURN_TRUE;
4301 } else {
4302 Py_RETURN_FALSE;
4303 }
4304 break;
4305 case Py_LT:
4306 case Py_LE:
4307 case Py_GT:
4308 case Py_GE:
4309 Py_RETURN_NOTIMPLEMENTED;
4310 break;
4311 default:
4312 PyErr_BadArgument();
4313 return NULL;
4314 }
4315}
4316
4317static int
4318PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4319{
4320 Py_VISIT(self->ctx);
4321 return 0;
4322}
4323
4324static int
4325PySSLSession_clear(PySSLSession *self)
4326{
4327 Py_CLEAR(self->ctx);
4328 return 0;
4329}
4330
4331
4332static PyObject *
4333PySSLSession_get_time(PySSLSession *self, void *closure) {
4334 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4335}
4336
4337PyDoc_STRVAR(PySSLSession_get_time_doc,
4338"Session creation time (seconds since epoch).");
4339
4340
4341static PyObject *
4342PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4343 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4344}
4345
4346PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4347"Session timeout (delta in seconds).");
4348
4349
4350static PyObject *
4351PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4352 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4353 return PyLong_FromUnsignedLong(hint);
4354}
4355
4356PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4357"Ticket life time hint.");
4358
4359
4360static PyObject *
4361PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4362 const unsigned char *id;
4363 unsigned int len;
4364 id = SSL_SESSION_get_id(self->session, &len);
4365 return PyBytes_FromStringAndSize((const char *)id, len);
4366}
4367
4368PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4369"Session id");
4370
4371
4372static PyObject *
4373PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4374 if (SSL_SESSION_has_ticket(self->session)) {
4375 Py_RETURN_TRUE;
4376 } else {
4377 Py_RETURN_FALSE;
4378 }
4379}
4380
4381PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4382"Does the session contain a ticket?");
4383
4384
4385static PyGetSetDef PySSLSession_getsetlist[] = {
4386 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4387 PySSLSession_get_has_ticket_doc},
4388 {"id", (getter) PySSLSession_get_session_id, NULL,
4389 PySSLSession_get_session_id_doc},
4390 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4391 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4392 {"time", (getter) PySSLSession_get_time, NULL,
4393 PySSLSession_get_time_doc},
4394 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4395 PySSLSession_get_timeout_doc},
4396 {NULL}, /* sentinel */
4397};
4398
4399static PyTypeObject PySSLSession_Type = {
4400 PyVarObject_HEAD_INIT(NULL, 0)
4401 "_ssl.Session", /*tp_name*/
4402 sizeof(PySSLSession), /*tp_basicsize*/
4403 0, /*tp_itemsize*/
4404 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4405 0, /*tp_print*/
4406 0, /*tp_getattr*/
4407 0, /*tp_setattr*/
4408 0, /*tp_reserved*/
4409 0, /*tp_repr*/
4410 0, /*tp_as_number*/
4411 0, /*tp_as_sequence*/
4412 0, /*tp_as_mapping*/
4413 0, /*tp_hash*/
4414 0, /*tp_call*/
4415 0, /*tp_str*/
4416 0, /*tp_getattro*/
4417 0, /*tp_setattro*/
4418 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004419 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004420 0, /*tp_doc*/
4421 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4422 (inquiry)PySSLSession_clear, /*tp_clear*/
4423 PySSLSession_richcompare, /*tp_richcompare*/
4424 0, /*tp_weaklistoffset*/
4425 0, /*tp_iter*/
4426 0, /*tp_iternext*/
4427 0, /*tp_methods*/
4428 0, /*tp_members*/
4429 PySSLSession_getsetlist, /*tp_getset*/
4430};
4431
4432
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004433/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004434/*[clinic input]
4435_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004436 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004437 entropy: double
4438 /
4439
4440Mix string into the OpenSSL PRNG state.
4441
4442entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304443string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004444[clinic start generated code]*/
4445
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004446static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004447_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004448/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004449{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004450 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004451 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004452
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004453 buf = (const char *)view->buf;
4454 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004455 do {
4456 written = Py_MIN(len, INT_MAX);
4457 RAND_add(buf, (int)written, entropy);
4458 buf += written;
4459 len -= written;
4460 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004461 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004462}
4463
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004464static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004465PySSL_RAND(int len, int pseudo)
4466{
4467 int ok;
4468 PyObject *bytes;
4469 unsigned long err;
4470 const char *errstr;
4471 PyObject *v;
4472
Victor Stinner1e81a392013-12-19 16:47:04 +01004473 if (len < 0) {
4474 PyErr_SetString(PyExc_ValueError, "num must be positive");
4475 return NULL;
4476 }
4477
Victor Stinner99c8b162011-05-24 12:05:19 +02004478 bytes = PyBytes_FromStringAndSize(NULL, len);
4479 if (bytes == NULL)
4480 return NULL;
4481 if (pseudo) {
4482 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4483 if (ok == 0 || ok == 1)
4484 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4485 }
4486 else {
4487 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4488 if (ok == 1)
4489 return bytes;
4490 }
4491 Py_DECREF(bytes);
4492
4493 err = ERR_get_error();
4494 errstr = ERR_reason_error_string(err);
4495 v = Py_BuildValue("(ks)", err, errstr);
4496 if (v != NULL) {
4497 PyErr_SetObject(PySSLErrorObject, v);
4498 Py_DECREF(v);
4499 }
4500 return NULL;
4501}
4502
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004503/*[clinic input]
4504_ssl.RAND_bytes
4505 n: int
4506 /
4507
4508Generate n cryptographically strong pseudo-random bytes.
4509[clinic start generated code]*/
4510
Victor Stinner99c8b162011-05-24 12:05:19 +02004511static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004512_ssl_RAND_bytes_impl(PyObject *module, int n)
4513/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004514{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004515 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004516}
4517
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004518/*[clinic input]
4519_ssl.RAND_pseudo_bytes
4520 n: int
4521 /
4522
4523Generate n pseudo-random bytes.
4524
4525Return a pair (bytes, is_cryptographic). is_cryptographic is True
4526if the bytes generated are cryptographically strong.
4527[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004528
4529static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004530_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4531/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004532{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004533 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004534}
4535
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004536/*[clinic input]
4537_ssl.RAND_status
4538
4539Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4540
4541It is necessary to seed the PRNG with RAND_add() on some platforms before
4542using the ssl() function.
4543[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004544
4545static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004546_ssl_RAND_status_impl(PyObject *module)
4547/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004548{
Christian Heimes217cfd12007-12-02 14:31:20 +00004549 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004550}
4551
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004552#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004553/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004554/*[clinic input]
4555_ssl.RAND_egd
4556 path: object(converter="PyUnicode_FSConverter")
4557 /
4558
4559Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4560
4561Returns number of bytes read. Raises SSLError if connection to EGD
4562fails or if it does not provide enough data to seed PRNG.
4563[clinic start generated code]*/
4564
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004565static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004566_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4567/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004568{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004569 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004570 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004571 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004572 PyErr_SetString(PySSLErrorObject,
4573 "EGD connection failed or EGD did not return "
4574 "enough data to seed the PRNG");
4575 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004576 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004577 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004578}
Christian Heimesa5d07652016-09-24 10:48:05 +02004579/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004580#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004581
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004582
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004583
4584/*[clinic input]
4585_ssl.get_default_verify_paths
4586
4587Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4588
4589The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4590[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004591
4592static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004593_ssl_get_default_verify_paths_impl(PyObject *module)
4594/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004595{
4596 PyObject *ofile_env = NULL;
4597 PyObject *ofile = NULL;
4598 PyObject *odir_env = NULL;
4599 PyObject *odir = NULL;
4600
Benjamin Petersond113c962015-07-18 10:59:13 -07004601#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004602 const char *tmp = (info); \
4603 target = NULL; \
4604 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4605 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4606 target = PyBytes_FromString(tmp); } \
4607 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004608 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004609
Benjamin Petersond113c962015-07-18 10:59:13 -07004610 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4611 CONVERT(X509_get_default_cert_file(), ofile);
4612 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4613 CONVERT(X509_get_default_cert_dir(), odir);
4614#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004615
Christian Heimes200bb1b2013-06-14 15:14:29 +02004616 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004617
4618 error:
4619 Py_XDECREF(ofile_env);
4620 Py_XDECREF(ofile);
4621 Py_XDECREF(odir_env);
4622 Py_XDECREF(odir);
4623 return NULL;
4624}
4625
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004626static PyObject*
4627asn1obj2py(ASN1_OBJECT *obj)
4628{
4629 int nid;
4630 const char *ln, *sn;
4631 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004632 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004633
4634 nid = OBJ_obj2nid(obj);
4635 if (nid == NID_undef) {
4636 PyErr_Format(PyExc_ValueError, "Unknown object");
4637 return NULL;
4638 }
4639 sn = OBJ_nid2sn(nid);
4640 ln = OBJ_nid2ln(nid);
4641 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4642 if (buflen < 0) {
4643 _setSSLError(NULL, 0, __FILE__, __LINE__);
4644 return NULL;
4645 }
4646 if (buflen) {
4647 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4648 } else {
4649 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4650 }
4651}
4652
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004653/*[clinic input]
4654_ssl.txt2obj
4655 txt: str
4656 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004657
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004658Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4659
4660By default objects are looked up by OID. With name=True short and
4661long name are also matched.
4662[clinic start generated code]*/
4663
4664static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004665_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4666/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004667{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004668 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004669 ASN1_OBJECT *obj;
4670
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004671 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4672 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004673 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004674 return NULL;
4675 }
4676 result = asn1obj2py(obj);
4677 ASN1_OBJECT_free(obj);
4678 return result;
4679}
4680
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004681/*[clinic input]
4682_ssl.nid2obj
4683 nid: int
4684 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004685
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004686Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4687[clinic start generated code]*/
4688
4689static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004690_ssl_nid2obj_impl(PyObject *module, int nid)
4691/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004692{
4693 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004694 ASN1_OBJECT *obj;
4695
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004696 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004697 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004698 return NULL;
4699 }
4700 obj = OBJ_nid2obj(nid);
4701 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004702 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004703 return NULL;
4704 }
4705 result = asn1obj2py(obj);
4706 ASN1_OBJECT_free(obj);
4707 return result;
4708}
4709
Christian Heimes46bebee2013-06-09 19:03:31 +02004710#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004711
4712static PyObject*
4713certEncodingType(DWORD encodingType)
4714{
4715 static PyObject *x509_asn = NULL;
4716 static PyObject *pkcs_7_asn = NULL;
4717
4718 if (x509_asn == NULL) {
4719 x509_asn = PyUnicode_InternFromString("x509_asn");
4720 if (x509_asn == NULL)
4721 return NULL;
4722 }
4723 if (pkcs_7_asn == NULL) {
4724 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4725 if (pkcs_7_asn == NULL)
4726 return NULL;
4727 }
4728 switch(encodingType) {
4729 case X509_ASN_ENCODING:
4730 Py_INCREF(x509_asn);
4731 return x509_asn;
4732 case PKCS_7_ASN_ENCODING:
4733 Py_INCREF(pkcs_7_asn);
4734 return pkcs_7_asn;
4735 default:
4736 return PyLong_FromLong(encodingType);
4737 }
4738}
4739
4740static PyObject*
4741parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4742{
4743 CERT_ENHKEY_USAGE *usage;
4744 DWORD size, error, i;
4745 PyObject *retval;
4746
4747 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4748 error = GetLastError();
4749 if (error == CRYPT_E_NOT_FOUND) {
4750 Py_RETURN_TRUE;
4751 }
4752 return PyErr_SetFromWindowsErr(error);
4753 }
4754
4755 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4756 if (usage == NULL) {
4757 return PyErr_NoMemory();
4758 }
4759
4760 /* Now get the actual enhanced usage property */
4761 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4762 PyMem_Free(usage);
4763 error = GetLastError();
4764 if (error == CRYPT_E_NOT_FOUND) {
4765 Py_RETURN_TRUE;
4766 }
4767 return PyErr_SetFromWindowsErr(error);
4768 }
4769 retval = PySet_New(NULL);
4770 if (retval == NULL) {
4771 goto error;
4772 }
4773 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4774 if (usage->rgpszUsageIdentifier[i]) {
4775 PyObject *oid;
4776 int err;
4777 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4778 if (oid == NULL) {
4779 Py_CLEAR(retval);
4780 goto error;
4781 }
4782 err = PySet_Add(retval, oid);
4783 Py_DECREF(oid);
4784 if (err == -1) {
4785 Py_CLEAR(retval);
4786 goto error;
4787 }
4788 }
4789 }
4790 error:
4791 PyMem_Free(usage);
4792 return retval;
4793}
4794
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004795/*[clinic input]
4796_ssl.enum_certificates
4797 store_name: str
4798
4799Retrieve certificates from Windows' cert store.
4800
4801store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4802more cert storages, too. The function returns a list of (bytes,
4803encoding_type, trust) tuples. The encoding_type flag can be interpreted
4804with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4805a set of OIDs or the boolean True.
4806[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004807
Christian Heimes46bebee2013-06-09 19:03:31 +02004808static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004809_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4810/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004811{
Christian Heimes46bebee2013-06-09 19:03:31 +02004812 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004813 PCCERT_CONTEXT pCertCtx = NULL;
4814 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004815 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004816
Christian Heimes44109d72013-11-22 01:51:30 +01004817 result = PyList_New(0);
4818 if (result == NULL) {
4819 return NULL;
4820 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004821 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4822 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4823 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004824 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004825 Py_DECREF(result);
4826 return PyErr_SetFromWindowsErr(GetLastError());
4827 }
4828
Christian Heimes44109d72013-11-22 01:51:30 +01004829 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4830 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4831 pCertCtx->cbCertEncoded);
4832 if (!cert) {
4833 Py_CLEAR(result);
4834 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004835 }
Christian Heimes44109d72013-11-22 01:51:30 +01004836 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4837 Py_CLEAR(result);
4838 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004839 }
Christian Heimes44109d72013-11-22 01:51:30 +01004840 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4841 if (keyusage == Py_True) {
4842 Py_DECREF(keyusage);
4843 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004844 }
Christian Heimes44109d72013-11-22 01:51:30 +01004845 if (keyusage == NULL) {
4846 Py_CLEAR(result);
4847 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004848 }
Christian Heimes44109d72013-11-22 01:51:30 +01004849 if ((tup = PyTuple_New(3)) == NULL) {
4850 Py_CLEAR(result);
4851 break;
4852 }
4853 PyTuple_SET_ITEM(tup, 0, cert);
4854 cert = NULL;
4855 PyTuple_SET_ITEM(tup, 1, enc);
4856 enc = NULL;
4857 PyTuple_SET_ITEM(tup, 2, keyusage);
4858 keyusage = NULL;
4859 if (PyList_Append(result, tup) < 0) {
4860 Py_CLEAR(result);
4861 break;
4862 }
4863 Py_CLEAR(tup);
4864 }
4865 if (pCertCtx) {
4866 /* loop ended with an error, need to clean up context manually */
4867 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004868 }
4869
4870 /* In error cases cert, enc and tup may not be NULL */
4871 Py_XDECREF(cert);
4872 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004873 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004874 Py_XDECREF(tup);
4875
4876 if (!CertCloseStore(hStore, 0)) {
4877 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004878 Py_XDECREF(result);
4879 return PyErr_SetFromWindowsErr(GetLastError());
4880 }
4881 return result;
4882}
4883
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004884/*[clinic input]
4885_ssl.enum_crls
4886 store_name: str
4887
4888Retrieve CRLs from Windows' cert store.
4889
4890store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4891more cert storages, too. The function returns a list of (bytes,
4892encoding_type) tuples. The encoding_type flag can be interpreted with
4893X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4894[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004895
4896static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004897_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4898/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004899{
Christian Heimes44109d72013-11-22 01:51:30 +01004900 HCERTSTORE hStore = NULL;
4901 PCCRL_CONTEXT pCrlCtx = NULL;
4902 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4903 PyObject *result = NULL;
4904
Christian Heimes44109d72013-11-22 01:51:30 +01004905 result = PyList_New(0);
4906 if (result == NULL) {
4907 return NULL;
4908 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004909 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4910 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4911 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004912 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004913 Py_DECREF(result);
4914 return PyErr_SetFromWindowsErr(GetLastError());
4915 }
Christian Heimes44109d72013-11-22 01:51:30 +01004916
4917 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4918 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4919 pCrlCtx->cbCrlEncoded);
4920 if (!crl) {
4921 Py_CLEAR(result);
4922 break;
4923 }
4924 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4925 Py_CLEAR(result);
4926 break;
4927 }
4928 if ((tup = PyTuple_New(2)) == NULL) {
4929 Py_CLEAR(result);
4930 break;
4931 }
4932 PyTuple_SET_ITEM(tup, 0, crl);
4933 crl = NULL;
4934 PyTuple_SET_ITEM(tup, 1, enc);
4935 enc = NULL;
4936
4937 if (PyList_Append(result, tup) < 0) {
4938 Py_CLEAR(result);
4939 break;
4940 }
4941 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004942 }
Christian Heimes44109d72013-11-22 01:51:30 +01004943 if (pCrlCtx) {
4944 /* loop ended with an error, need to clean up context manually */
4945 CertFreeCRLContext(pCrlCtx);
4946 }
4947
4948 /* In error cases cert, enc and tup may not be NULL */
4949 Py_XDECREF(crl);
4950 Py_XDECREF(enc);
4951 Py_XDECREF(tup);
4952
4953 if (!CertCloseStore(hStore, 0)) {
4954 /* This error case might shadow another exception.*/
4955 Py_XDECREF(result);
4956 return PyErr_SetFromWindowsErr(GetLastError());
4957 }
4958 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004959}
Christian Heimes44109d72013-11-22 01:51:30 +01004960
4961#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004962
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004963/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004964static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004965 _SSL__TEST_DECODE_CERT_METHODDEF
4966 _SSL_RAND_ADD_METHODDEF
4967 _SSL_RAND_BYTES_METHODDEF
4968 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4969 _SSL_RAND_EGD_METHODDEF
4970 _SSL_RAND_STATUS_METHODDEF
4971 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
4972 _SSL_ENUM_CERTIFICATES_METHODDEF
4973 _SSL_ENUM_CRLS_METHODDEF
4974 _SSL_TXT2OBJ_METHODDEF
4975 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004976 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004977};
4978
4979
Christian Heimes598894f2016-09-05 23:19:05 +02004980#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004981
4982/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02004983 * of the Python C thread library
4984 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
4985 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004986
4987static PyThread_type_lock *_ssl_locks = NULL;
4988
Christian Heimes4d98ca92013-08-19 17:36:29 +02004989#if OPENSSL_VERSION_NUMBER >= 0x10000000
4990/* use new CRYPTO_THREADID API. */
4991static void
4992_ssl_threadid_callback(CRYPTO_THREADID *id)
4993{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02004994 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02004995}
4996#else
4997/* deprecated CRYPTO_set_id_callback() API. */
4998static unsigned long
4999_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005000 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005001}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005002#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005003
Bill Janssen6e027db2007-11-15 22:23:56 +00005004static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005005 (int mode, int n, const char *file, int line) {
5006 /* this function is needed to perform locking on shared data
5007 structures. (Note that OpenSSL uses a number of global data
5008 structures that will be implicitly shared whenever multiple
5009 threads use OpenSSL.) Multi-threaded applications will
5010 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005011
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005012 locking_function() must be able to handle up to
5013 CRYPTO_num_locks() different mutex locks. It sets the n-th
5014 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005015
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005016 file and line are the file number of the function setting the
5017 lock. They can be useful for debugging.
5018 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005019
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005020 if ((_ssl_locks == NULL) ||
5021 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5022 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005023
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005024 if (mode & CRYPTO_LOCK) {
5025 PyThread_acquire_lock(_ssl_locks[n], 1);
5026 } else {
5027 PyThread_release_lock(_ssl_locks[n]);
5028 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005029}
5030
5031static int _setup_ssl_threads(void) {
5032
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005033 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005034
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005035 if (_ssl_locks == NULL) {
5036 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005037 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5038 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005039 if (_ssl_locks == NULL) {
5040 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005041 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005042 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005043 for (i = 0; i < _ssl_locks_count; i++) {
5044 _ssl_locks[i] = PyThread_allocate_lock();
5045 if (_ssl_locks[i] == NULL) {
5046 unsigned int j;
5047 for (j = 0; j < i; j++) {
5048 PyThread_free_lock(_ssl_locks[j]);
5049 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005050 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005051 return 0;
5052 }
5053 }
5054 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005055#if OPENSSL_VERSION_NUMBER >= 0x10000000
5056 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5057#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005058 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005059#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005060 }
5061 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005062}
5063
Christian Heimes598894f2016-09-05 23:19:05 +02005064#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005065
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005066PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005067"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005068for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005069
Martin v. Löwis1a214512008-06-11 05:26:20 +00005070
5071static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005072 PyModuleDef_HEAD_INIT,
5073 "_ssl",
5074 module_doc,
5075 -1,
5076 PySSL_methods,
5077 NULL,
5078 NULL,
5079 NULL,
5080 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005081};
5082
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005083
5084static void
5085parse_openssl_version(unsigned long libver,
5086 unsigned int *major, unsigned int *minor,
5087 unsigned int *fix, unsigned int *patch,
5088 unsigned int *status)
5089{
5090 *status = libver & 0xF;
5091 libver >>= 4;
5092 *patch = libver & 0xFF;
5093 libver >>= 8;
5094 *fix = libver & 0xFF;
5095 libver >>= 8;
5096 *minor = libver & 0xFF;
5097 libver >>= 8;
5098 *major = libver & 0xFF;
5099}
5100
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005101PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005102PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005103{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005104 PyObject *m, *d, *r;
5105 unsigned long libver;
5106 unsigned int major, minor, fix, patch, status;
5107 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005108 struct py_ssl_error_code *errcode;
5109 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005110
Antoine Pitrou152efa22010-05-16 18:19:27 +00005111 if (PyType_Ready(&PySSLContext_Type) < 0)
5112 return NULL;
5113 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005114 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005115 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5116 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005117 if (PyType_Ready(&PySSLSession_Type) < 0)
5118 return NULL;
5119
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005120
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005121 m = PyModule_Create(&_sslmodule);
5122 if (m == NULL)
5123 return NULL;
5124 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005125
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005126 /* Load _socket module and its C API */
5127 socket_api = PySocketModule_ImportModuleAndAPI();
5128 if (!socket_api)
5129 return NULL;
5130 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005131
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005132 /* Init OpenSSL */
5133 SSL_load_error_strings();
5134 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005135#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02005136#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005137 /* note that this will start threading if not already started */
5138 if (!_setup_ssl_threads()) {
5139 return NULL;
5140 }
Christian Heimes598894f2016-09-05 23:19:05 +02005141#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5142 /* OpenSSL 1.1.0 builtin thread support is enabled */
5143 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005144#endif
Christian Heimes598894f2016-09-05 23:19:05 +02005145#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005146 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005147
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005148 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005149 sslerror_type_slots[0].pfunc = PyExc_OSError;
5150 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005151 if (PySSLErrorObject == NULL)
5152 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005153
Antoine Pitrou41032a62011-10-27 23:56:55 +02005154 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5155 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5156 PySSLErrorObject, NULL);
5157 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5158 "ssl.SSLWantReadError", SSLWantReadError_doc,
5159 PySSLErrorObject, NULL);
5160 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5161 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5162 PySSLErrorObject, NULL);
5163 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5164 "ssl.SSLSyscallError", SSLSyscallError_doc,
5165 PySSLErrorObject, NULL);
5166 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5167 "ssl.SSLEOFError", SSLEOFError_doc,
5168 PySSLErrorObject, NULL);
5169 if (PySSLZeroReturnErrorObject == NULL
5170 || PySSLWantReadErrorObject == NULL
5171 || PySSLWantWriteErrorObject == NULL
5172 || PySSLSyscallErrorObject == NULL
5173 || PySSLEOFErrorObject == NULL)
5174 return NULL;
5175 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5176 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5177 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5178 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5179 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5180 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005181 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005182 if (PyDict_SetItemString(d, "_SSLContext",
5183 (PyObject *)&PySSLContext_Type) != 0)
5184 return NULL;
5185 if (PyDict_SetItemString(d, "_SSLSocket",
5186 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005187 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005188 if (PyDict_SetItemString(d, "MemoryBIO",
5189 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5190 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005191 if (PyDict_SetItemString(d, "SSLSession",
5192 (PyObject *)&PySSLSession_Type) != 0)
5193 return NULL;
5194
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005195 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5196 PY_SSL_ERROR_ZERO_RETURN);
5197 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5198 PY_SSL_ERROR_WANT_READ);
5199 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5200 PY_SSL_ERROR_WANT_WRITE);
5201 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5202 PY_SSL_ERROR_WANT_X509_LOOKUP);
5203 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5204 PY_SSL_ERROR_SYSCALL);
5205 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5206 PY_SSL_ERROR_SSL);
5207 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5208 PY_SSL_ERROR_WANT_CONNECT);
5209 /* non ssl.h errorcodes */
5210 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5211 PY_SSL_ERROR_EOF);
5212 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5213 PY_SSL_ERROR_INVALID_ERROR_CODE);
5214 /* cert requirements */
5215 PyModule_AddIntConstant(m, "CERT_NONE",
5216 PY_SSL_CERT_NONE);
5217 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5218 PY_SSL_CERT_OPTIONAL);
5219 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5220 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005221 /* CRL verification for verification_flags */
5222 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5223 0);
5224 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5225 X509_V_FLAG_CRL_CHECK);
5226 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5227 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5228 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5229 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005230#ifdef X509_V_FLAG_TRUSTED_FIRST
5231 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5232 X509_V_FLAG_TRUSTED_FIRST);
5233#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005234
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005235 /* Alert Descriptions from ssl.h */
5236 /* note RESERVED constants no longer intended for use have been removed */
5237 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5238
5239#define ADD_AD_CONSTANT(s) \
5240 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5241 SSL_AD_##s)
5242
5243 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5244 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5245 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5246 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5247 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5248 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5249 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5250 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5251 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5252 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5253 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5254 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5255 ADD_AD_CONSTANT(UNKNOWN_CA);
5256 ADD_AD_CONSTANT(ACCESS_DENIED);
5257 ADD_AD_CONSTANT(DECODE_ERROR);
5258 ADD_AD_CONSTANT(DECRYPT_ERROR);
5259 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5260 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5261 ADD_AD_CONSTANT(INTERNAL_ERROR);
5262 ADD_AD_CONSTANT(USER_CANCELLED);
5263 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005264 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005265#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5266 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5267#endif
5268#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5269 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5270#endif
5271#ifdef SSL_AD_UNRECOGNIZED_NAME
5272 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5273#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005274#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5275 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5276#endif
5277#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5278 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5279#endif
5280#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5281 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5282#endif
5283
5284#undef ADD_AD_CONSTANT
5285
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005286 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005287#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005288 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5289 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005290#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005291#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005292 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5293 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005294#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005295 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005296 PY_SSL_VERSION_TLS);
5297 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5298 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005299 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5300 PY_SSL_VERSION_TLS_CLIENT);
5301 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5302 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005303 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5304 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005305#if HAVE_TLSv1_2
5306 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5307 PY_SSL_VERSION_TLS1_1);
5308 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5309 PY_SSL_VERSION_TLS1_2);
5310#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005311
Antoine Pitroub5218772010-05-21 09:56:06 +00005312 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005313 PyModule_AddIntConstant(m, "OP_ALL",
5314 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005315 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5316 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5317 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005318#if HAVE_TLSv1_2
5319 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5320 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5321#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005322 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5323 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005324 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005325 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005326#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005327 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005328#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005329#ifdef SSL_OP_NO_COMPRESSION
5330 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5331 SSL_OP_NO_COMPRESSION);
5332#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005333
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005334#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005335 r = Py_True;
5336#else
5337 r = Py_False;
5338#endif
5339 Py_INCREF(r);
5340 PyModule_AddObject(m, "HAS_SNI", r);
5341
Antoine Pitroud6494802011-07-21 01:11:30 +02005342 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005343 Py_INCREF(r);
5344 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5345
Antoine Pitrou501da612011-12-21 09:27:41 +01005346#ifdef OPENSSL_NO_ECDH
5347 r = Py_False;
5348#else
5349 r = Py_True;
5350#endif
5351 Py_INCREF(r);
5352 PyModule_AddObject(m, "HAS_ECDH", r);
5353
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005354#ifdef OPENSSL_NPN_NEGOTIATED
5355 r = Py_True;
5356#else
5357 r = Py_False;
5358#endif
5359 Py_INCREF(r);
5360 PyModule_AddObject(m, "HAS_NPN", r);
5361
Benjamin Petersoncca27322015-01-23 16:35:37 -05005362#ifdef HAVE_ALPN
5363 r = Py_True;
5364#else
5365 r = Py_False;
5366#endif
5367 Py_INCREF(r);
5368 PyModule_AddObject(m, "HAS_ALPN", r);
5369
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005370 /* Mappings for error codes */
5371 err_codes_to_names = PyDict_New();
5372 err_names_to_codes = PyDict_New();
5373 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5374 return NULL;
5375 errcode = error_codes;
5376 while (errcode->mnemonic != NULL) {
5377 PyObject *mnemo, *key;
5378 mnemo = PyUnicode_FromString(errcode->mnemonic);
5379 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5380 if (mnemo == NULL || key == NULL)
5381 return NULL;
5382 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5383 return NULL;
5384 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5385 return NULL;
5386 Py_DECREF(key);
5387 Py_DECREF(mnemo);
5388 errcode++;
5389 }
5390 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5391 return NULL;
5392 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5393 return NULL;
5394
5395 lib_codes_to_names = PyDict_New();
5396 if (lib_codes_to_names == NULL)
5397 return NULL;
5398 libcode = library_codes;
5399 while (libcode->library != NULL) {
5400 PyObject *mnemo, *key;
5401 key = PyLong_FromLong(libcode->code);
5402 mnemo = PyUnicode_FromString(libcode->library);
5403 if (key == NULL || mnemo == NULL)
5404 return NULL;
5405 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5406 return NULL;
5407 Py_DECREF(key);
5408 Py_DECREF(mnemo);
5409 libcode++;
5410 }
5411 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5412 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005413
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005414 /* OpenSSL version */
5415 /* SSLeay() gives us the version of the library linked against,
5416 which could be different from the headers version.
5417 */
5418 libver = SSLeay();
5419 r = PyLong_FromUnsignedLong(libver);
5420 if (r == NULL)
5421 return NULL;
5422 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5423 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005424 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005425 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5426 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5427 return NULL;
5428 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5429 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5430 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005431
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005432 libver = OPENSSL_VERSION_NUMBER;
5433 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5434 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5435 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5436 return NULL;
5437
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005438 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005439}