blob: 0fb0d8862c89548bd46af4ad2c67a22be31db29a [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#ifdef WITH_THREAD
22#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020023
Christian Heimesf77b4b22013-08-21 13:26:05 +020024
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020025#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
26 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
27#define PySSL_END_ALLOW_THREADS_S(save) \
28 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000029#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000030 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020031 PySSL_BEGIN_ALLOW_THREADS_S(_save);
32#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
33#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
34#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000035
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000036#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000037
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020038#define PySSL_BEGIN_ALLOW_THREADS_S(save)
39#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000040#define PySSL_BEGIN_ALLOW_THREADS
41#define PySSL_BLOCK_THREADS
42#define PySSL_UNBLOCK_THREADS
43#define PySSL_END_ALLOW_THREADS
44
45#endif
46
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010047/* Include symbols from _socket module */
48#include "socketmodule.h"
49
50static PySocketModule_APIObject PySocketModule;
51
52#if defined(HAVE_POLL_H)
53#include <poll.h>
54#elif defined(HAVE_SYS_POLL_H)
55#include <sys/poll.h>
56#endif
57
Christian Heimes598894f2016-09-05 23:19:05 +020058/* Don't warn about deprecated functions */
59#ifdef __GNUC__
60#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
61#endif
62#ifdef __clang__
63#pragma clang diagnostic ignored "-Wdeprecated-declarations"
64#endif
65
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010066/* Include OpenSSL header files */
67#include "openssl/rsa.h"
68#include "openssl/crypto.h"
69#include "openssl/x509.h"
70#include "openssl/x509v3.h"
71#include "openssl/pem.h"
72#include "openssl/ssl.h"
73#include "openssl/err.h"
74#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020075#include "openssl/bio.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010076
77/* SSL error object */
78static PyObject *PySSLErrorObject;
79static PyObject *PySSLZeroReturnErrorObject;
80static PyObject *PySSLWantReadErrorObject;
81static PyObject *PySSLWantWriteErrorObject;
82static PyObject *PySSLSyscallErrorObject;
83static PyObject *PySSLEOFErrorObject;
84
85/* Error mappings */
86static PyObject *err_codes_to_names;
87static PyObject *err_names_to_codes;
88static PyObject *lib_codes_to_names;
89
90struct py_ssl_error_code {
91 const char *mnemonic;
92 int library, reason;
93};
94struct py_ssl_library_code {
95 const char *library;
96 int code;
97};
98
99/* Include generated data (error codes) */
100#include "_ssl_data.h"
101
Christian Heimes598894f2016-09-05 23:19:05 +0200102#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
103# define OPENSSL_VERSION_1_1 1
104#endif
105
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100106/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
107 http://www.openssl.org/news/changelog.html
108 */
109#if OPENSSL_VERSION_NUMBER >= 0x10001000L
110# define HAVE_TLSv1_2 1
111#else
112# define HAVE_TLSv1_2 0
113#endif
114
Christian Heimes470fba12013-11-28 15:12:15 +0100115/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100116 * This includes the SSL_set_SSL_CTX() function.
117 */
118#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
119# define HAVE_SNI 1
120#else
121# define HAVE_SNI 0
122#endif
123
Benjamin Petersond3308222015-09-27 00:09:02 -0700124#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Benjamin Petersoncca27322015-01-23 16:35:37 -0500125# define HAVE_ALPN
126#endif
127
Victor Stinner524714e2016-07-22 17:43:59 +0200128#ifndef INVALID_SOCKET /* MS defines this */
129#define INVALID_SOCKET (-1)
130#endif
131
Christian Heimes598894f2016-09-05 23:19:05 +0200132#ifdef OPENSSL_VERSION_1_1
133/* OpenSSL 1.1.0+ */
134#ifndef OPENSSL_NO_SSL2
135#define OPENSSL_NO_SSL2
136#endif
137#else /* OpenSSL < 1.1.0 */
138#if defined(WITH_THREAD)
139#define HAVE_OPENSSL_CRYPTO_LOCK
140#endif
141
142#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200143#define TLS_client_method SSLv23_client_method
144#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200145
146static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
147{
148 return ne->set;
149}
150
151#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200152/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200153static int COMP_get_type(const COMP_METHOD *meth)
154{
155 return meth->type;
156}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200157/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200158#endif
159
160static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
161{
162 return ctx->default_passwd_callback;
163}
164
165static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
166{
167 return ctx->default_passwd_callback_userdata;
168}
169
170static int X509_OBJECT_get_type(X509_OBJECT *x)
171{
172 return x->type;
173}
174
175static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
176{
177 return x->data.x509;
178}
179
180static int BIO_up_ref(BIO *b)
181{
182 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
183 return 1;
184}
185
186static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
187 return store->objs;
188}
189
190static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
191{
192 return store->param;
193}
Christian Heimes99a65702016-09-10 23:44:53 +0200194
195static int
196SSL_SESSION_has_ticket(const SSL_SESSION *s)
197{
198 return (s->tlsext_ticklen > 0) ? 1 : 0;
199}
200
201static unsigned long
202SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
203{
204 return s->tlsext_tick_lifetime_hint;
205}
206
Christian Heimes598894f2016-09-05 23:19:05 +0200207#endif /* OpenSSL < 1.1.0 or LibreSSL */
208
209
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000210enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000211 /* these mirror ssl.h */
212 PY_SSL_ERROR_NONE,
213 PY_SSL_ERROR_SSL,
214 PY_SSL_ERROR_WANT_READ,
215 PY_SSL_ERROR_WANT_WRITE,
216 PY_SSL_ERROR_WANT_X509_LOOKUP,
217 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
218 PY_SSL_ERROR_ZERO_RETURN,
219 PY_SSL_ERROR_WANT_CONNECT,
220 /* start of non ssl.h errorcodes */
221 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
222 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
223 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000224};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000225
Thomas Woutersed03b412007-08-28 21:37:11 +0000226enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000227 PY_SSL_CLIENT,
228 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000229};
230
231enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000232 PY_SSL_CERT_NONE,
233 PY_SSL_CERT_OPTIONAL,
234 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000235};
236
237enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000238 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200239 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200240 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100241#if HAVE_TLSv1_2
242 PY_SSL_VERSION_TLS1,
243 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200244 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100245#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200246 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000247#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200248 PY_SSL_VERSION_TLS_CLIENT=0x10,
249 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100250};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200251
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000252#ifdef WITH_THREAD
253
254/* serves as a flag to see whether we've initialized the SSL thread support. */
255/* 0 means no, greater than 0 means yes */
256
257static unsigned int _ssl_locks_count = 0;
258
259#endif /* def WITH_THREAD */
260
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000261/* SSL socket object */
262
263#define X509_NAME_MAXLEN 256
264
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000265/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
266 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
267 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
268#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000269# define HAVE_SSL_CTX_CLEAR_OPTIONS
270#else
271# undef HAVE_SSL_CTX_CLEAR_OPTIONS
272#endif
273
Antoine Pitroud6494802011-07-21 01:11:30 +0200274/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
275 * older SSL, but let's be safe */
276#define PySSL_CB_MAXLEN 128
277
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100278
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000279typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000280 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000281 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100282#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -0500283 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100284 int npn_protocols_len;
285#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500286#ifdef HAVE_ALPN
287 unsigned char *alpn_protocols;
288 int alpn_protocols_len;
289#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100290#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200291 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100292#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100293 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000294} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000295
Antoine Pitrou152efa22010-05-16 18:19:27 +0000296typedef struct {
297 PyObject_HEAD
298 PyObject *Socket; /* weakref to socket on which we're layered */
299 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100300 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200301 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200302 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200303 PyObject *owner; /* Python level "owner" passed to servername callback */
304 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000305} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000306
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200307typedef struct {
308 PyObject_HEAD
309 BIO *bio;
310 int eof_written;
311} PySSLMemoryBIO;
312
Christian Heimes99a65702016-09-10 23:44:53 +0200313typedef struct {
314 PyObject_HEAD
315 SSL_SESSION *session;
316 PySSLContext *ctx;
317} PySSLSession;
318
Antoine Pitrou152efa22010-05-16 18:19:27 +0000319static PyTypeObject PySSLContext_Type;
320static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200321static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200322static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000323
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300324/*[clinic input]
325module _ssl
326class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
327class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
328class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200329class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300330[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200331/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300332
333#include "clinic/_ssl.c.h"
334
Victor Stinner14690702015-04-06 22:46:13 +0200335static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000336
Christian Heimes99a65702016-09-10 23:44:53 +0200337
Antoine Pitrou152efa22010-05-16 18:19:27 +0000338#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
339#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200340#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200341#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000342
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000343typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000344 SOCKET_IS_NONBLOCKING,
345 SOCKET_IS_BLOCKING,
346 SOCKET_HAS_TIMED_OUT,
347 SOCKET_HAS_BEEN_CLOSED,
348 SOCKET_TOO_LARGE_FOR_SELECT,
349 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000350} timeout_state;
351
Thomas Woutersed03b412007-08-28 21:37:11 +0000352/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000353#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200354#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000355
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200356/* Get the socket from a PySSLSocket, if it has one */
357#define GET_SOCKET(obj) ((obj)->Socket ? \
358 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200359
Victor Stinner14690702015-04-06 22:46:13 +0200360/* If sock is NULL, use a timeout of 0 second */
361#define GET_SOCKET_TIMEOUT(sock) \
362 ((sock != NULL) ? (sock)->sock_timeout : 0)
363
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200364/*
365 * SSL errors.
366 */
367
368PyDoc_STRVAR(SSLError_doc,
369"An error occurred in the SSL implementation.");
370
371PyDoc_STRVAR(SSLZeroReturnError_doc,
372"SSL/TLS session closed cleanly.");
373
374PyDoc_STRVAR(SSLWantReadError_doc,
375"Non-blocking SSL socket needs to read more data\n"
376"before the requested operation can be completed.");
377
378PyDoc_STRVAR(SSLWantWriteError_doc,
379"Non-blocking SSL socket needs to write more data\n"
380"before the requested operation can be completed.");
381
382PyDoc_STRVAR(SSLSyscallError_doc,
383"System error when attempting SSL operation.");
384
385PyDoc_STRVAR(SSLEOFError_doc,
386"SSL/TLS connection terminated abruptly.");
387
388static PyObject *
389SSLError_str(PyOSErrorObject *self)
390{
391 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
392 Py_INCREF(self->strerror);
393 return self->strerror;
394 }
395 else
396 return PyObject_Str(self->args);
397}
398
399static PyType_Slot sslerror_type_slots[] = {
400 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
401 {Py_tp_doc, SSLError_doc},
402 {Py_tp_str, SSLError_str},
403 {0, 0},
404};
405
406static PyType_Spec sslerror_type_spec = {
407 "ssl.SSLError",
408 sizeof(PyOSErrorObject),
409 0,
410 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
411 sslerror_type_slots
412};
413
414static void
415fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
416 int lineno, unsigned long errcode)
417{
418 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
419 PyObject *init_value, *msg, *key;
420 _Py_IDENTIFIER(reason);
421 _Py_IDENTIFIER(library);
422
423 if (errcode != 0) {
424 int lib, reason;
425
426 lib = ERR_GET_LIB(errcode);
427 reason = ERR_GET_REASON(errcode);
428 key = Py_BuildValue("ii", lib, reason);
429 if (key == NULL)
430 goto fail;
431 reason_obj = PyDict_GetItem(err_codes_to_names, key);
432 Py_DECREF(key);
433 if (reason_obj == NULL) {
434 /* XXX if reason < 100, it might reflect a library number (!!) */
435 PyErr_Clear();
436 }
437 key = PyLong_FromLong(lib);
438 if (key == NULL)
439 goto fail;
440 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
441 Py_DECREF(key);
442 if (lib_obj == NULL) {
443 PyErr_Clear();
444 }
445 if (errstr == NULL)
446 errstr = ERR_reason_error_string(errcode);
447 }
448 if (errstr == NULL)
449 errstr = "unknown error";
450
451 if (reason_obj && lib_obj)
452 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
453 lib_obj, reason_obj, errstr, lineno);
454 else if (lib_obj)
455 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
456 lib_obj, errstr, lineno);
457 else
458 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200459 if (msg == NULL)
460 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100461
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200462 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100463 if (init_value == NULL)
464 goto fail;
465
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200466 err_value = PyObject_CallObject(type, init_value);
467 Py_DECREF(init_value);
468 if (err_value == NULL)
469 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100470
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200471 if (reason_obj == NULL)
472 reason_obj = Py_None;
473 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
474 goto fail;
475 if (lib_obj == NULL)
476 lib_obj = Py_None;
477 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
478 goto fail;
479 PyErr_SetObject(type, err_value);
480fail:
481 Py_XDECREF(err_value);
482}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000483
484static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200485PySSL_SetError(PySSLSocket *obj, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000486{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200487 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200488 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000489 int err;
490 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200491 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000492
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000493 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200494 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000495
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000496 if (obj->ssl != NULL) {
497 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000498
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000499 switch (err) {
500 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200501 errstr = "TLS/SSL connection has been closed (EOF)";
502 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000503 p = PY_SSL_ERROR_ZERO_RETURN;
504 break;
505 case SSL_ERROR_WANT_READ:
506 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200507 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000508 p = PY_SSL_ERROR_WANT_READ;
509 break;
510 case SSL_ERROR_WANT_WRITE:
511 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200512 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000513 errstr = "The operation did not complete (write)";
514 break;
515 case SSL_ERROR_WANT_X509_LOOKUP:
516 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000517 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 break;
519 case SSL_ERROR_WANT_CONNECT:
520 p = PY_SSL_ERROR_WANT_CONNECT;
521 errstr = "The operation did not complete (connect)";
522 break;
523 case SSL_ERROR_SYSCALL:
524 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000525 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200526 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000527 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000528 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200529 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000530 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200531 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000532 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000533 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000534 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200535 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000536 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200537 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000538 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000539 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200540 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000541 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000542 }
543 } else {
544 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000545 }
546 break;
547 }
548 case SSL_ERROR_SSL:
549 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000550 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200551 if (e == 0)
552 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000553 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000554 break;
555 }
556 default:
557 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
558 errstr = "Invalid error code";
559 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000560 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200561 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000562 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000563 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000564}
565
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000566static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200567_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000568
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200569 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000570 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200571 else
572 errcode = 0;
573 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000574 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000575 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000576}
577
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200578/*
579 * SSL objects
580 */
581
Antoine Pitrou152efa22010-05-16 18:19:27 +0000582static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100583newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000584 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200585 char *server_hostname,
586 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000587{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000588 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100589 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200590 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000591
Antoine Pitrou152efa22010-05-16 18:19:27 +0000592 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000593 if (self == NULL)
594 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000596 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000597 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100598 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200599 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200600 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700601 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200602 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700603 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
604 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200605 if (hostname == NULL) {
606 Py_DECREF(self);
607 return NULL;
608 }
609 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700610 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200611
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100612 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000613
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000614 /* Make sure the SSL error state is initialized */
615 (void) ERR_get_state();
616 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000619 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000620 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200621 SSL_set_app_data(self->ssl, self);
622 if (sock) {
623 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
624 } else {
625 /* BIOs are reference counted and SSL_set_bio borrows our reference.
626 * To prevent a double free in memory_bio_dealloc() we need to take an
627 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200628 BIO_up_ref(inbio->bio);
629 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200630 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
631 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200632 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000633#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200634 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000635#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200636 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000637
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100638#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000639 if (server_hostname != NULL)
640 SSL_set_tlsext_host_name(self->ssl, server_hostname);
641#endif
642
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000643 /* If the socket is in non-blocking mode or timeout mode, set the BIO
644 * to non-blocking mode (blocking is the default)
645 */
Victor Stinnere2452312015-03-28 03:00:46 +0100646 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000647 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
648 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
649 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000650
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000651 PySSL_BEGIN_ALLOW_THREADS
652 if (socket_type == PY_SSL_CLIENT)
653 SSL_set_connect_state(self->ssl);
654 else
655 SSL_set_accept_state(self->ssl);
656 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000657
Antoine Pitroud6494802011-07-21 01:11:30 +0200658 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200659 if (sock != NULL) {
660 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
661 if (self->Socket == NULL) {
662 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200663 return NULL;
664 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100665 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000667}
668
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000669/* SSL object methods */
670
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300671/*[clinic input]
672_ssl._SSLSocket.do_handshake
673[clinic start generated code]*/
674
675static PyObject *
676_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
677/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000678{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000679 int ret;
680 int err;
681 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200682 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200683 _PyTime_t timeout, deadline = 0;
684 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000685
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200686 if (sock) {
687 if (((PyObject*)sock) == Py_None) {
688 _setSSLError("Underlying socket connection gone",
689 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
690 return NULL;
691 }
692 Py_INCREF(sock);
693
694 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100695 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200696 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
697 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000698 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000699
Victor Stinner14690702015-04-06 22:46:13 +0200700 timeout = GET_SOCKET_TIMEOUT(sock);
701 has_timeout = (timeout > 0);
702 if (has_timeout)
703 deadline = _PyTime_GetMonotonicClock() + timeout;
704
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000705 /* Actually negotiate SSL connection */
706 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000708 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000709 ret = SSL_do_handshake(self->ssl);
710 err = SSL_get_error(self->ssl, ret);
711 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200712
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000713 if (PyErr_CheckSignals())
714 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200715
Victor Stinner14690702015-04-06 22:46:13 +0200716 if (has_timeout)
717 timeout = deadline - _PyTime_GetMonotonicClock();
718
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000719 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200720 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000721 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200722 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 } else {
724 sockstate = SOCKET_OPERATION_OK;
725 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200726
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000727 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000728 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000729 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000730 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000731 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
732 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000733 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000734 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
736 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000737 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000738 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000739 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
740 break;
741 }
742 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200743 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000744 if (ret < 1)
745 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000746
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200747 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000748
749error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200750 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000751 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000752}
753
Thomas Woutersed03b412007-08-28 21:37:11 +0000754static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000755_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000756
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000757 char namebuf[X509_NAME_MAXLEN];
758 int buflen;
759 PyObject *name_obj;
760 PyObject *value_obj;
761 PyObject *attr;
762 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000763
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000764 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
765 if (buflen < 0) {
766 _setSSLError(NULL, 0, __FILE__, __LINE__);
767 goto fail;
768 }
769 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
770 if (name_obj == NULL)
771 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000772
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000773 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
774 if (buflen < 0) {
775 _setSSLError(NULL, 0, __FILE__, __LINE__);
776 Py_DECREF(name_obj);
777 goto fail;
778 }
779 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000780 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000781 OPENSSL_free(valuebuf);
782 if (value_obj == NULL) {
783 Py_DECREF(name_obj);
784 goto fail;
785 }
786 attr = PyTuple_New(2);
787 if (attr == NULL) {
788 Py_DECREF(name_obj);
789 Py_DECREF(value_obj);
790 goto fail;
791 }
792 PyTuple_SET_ITEM(attr, 0, name_obj);
793 PyTuple_SET_ITEM(attr, 1, value_obj);
794 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000795
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000796 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000798}
799
800static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000801_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000802{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
804 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
805 PyObject *rdnt;
806 PyObject *attr = NULL; /* tuple to hold an attribute */
807 int entry_count = X509_NAME_entry_count(xname);
808 X509_NAME_ENTRY *entry;
809 ASN1_OBJECT *name;
810 ASN1_STRING *value;
811 int index_counter;
812 int rdn_level = -1;
813 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000814
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000815 dn = PyList_New(0);
816 if (dn == NULL)
817 return NULL;
818 /* now create another tuple to hold the top-level RDN */
819 rdn = PyList_New(0);
820 if (rdn == NULL)
821 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000822
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000823 for (index_counter = 0;
824 index_counter < entry_count;
825 index_counter++)
826 {
827 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000829 /* check to see if we've gotten to a new RDN */
830 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200831 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 /* yes, new RDN */
833 /* add old RDN to DN */
834 rdnt = PyList_AsTuple(rdn);
835 Py_DECREF(rdn);
836 if (rdnt == NULL)
837 goto fail0;
838 retcode = PyList_Append(dn, rdnt);
839 Py_DECREF(rdnt);
840 if (retcode < 0)
841 goto fail0;
842 /* create new RDN */
843 rdn = PyList_New(0);
844 if (rdn == NULL)
845 goto fail0;
846 }
847 }
Christian Heimes598894f2016-09-05 23:19:05 +0200848 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000849
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000850 /* now add this attribute to the current RDN */
851 name = X509_NAME_ENTRY_get_object(entry);
852 value = X509_NAME_ENTRY_get_data(entry);
853 attr = _create_tuple_for_attribute(name, value);
854 /*
855 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
856 entry->set,
857 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
858 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
859 */
860 if (attr == NULL)
861 goto fail1;
862 retcode = PyList_Append(rdn, attr);
863 Py_DECREF(attr);
864 if (retcode < 0)
865 goto fail1;
866 }
867 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100868 if (rdn != NULL) {
869 if (PyList_GET_SIZE(rdn) > 0) {
870 rdnt = PyList_AsTuple(rdn);
871 Py_DECREF(rdn);
872 if (rdnt == NULL)
873 goto fail0;
874 retcode = PyList_Append(dn, rdnt);
875 Py_DECREF(rdnt);
876 if (retcode < 0)
877 goto fail0;
878 }
879 else {
880 Py_DECREF(rdn);
881 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000882 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000883
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000884 /* convert list to tuple */
885 rdnt = PyList_AsTuple(dn);
886 Py_DECREF(dn);
887 if (rdnt == NULL)
888 return NULL;
889 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890
891 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000892 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000893
894 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000895 Py_XDECREF(dn);
896 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000897}
898
899static PyObject *
900_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000901
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 /* this code follows the procedure outlined in
903 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
904 function to extract the STACK_OF(GENERAL_NAME),
905 then iterates through the stack to add the
906 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000907
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000908 int i, j;
909 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200910 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000911 X509_EXTENSION *ext = NULL;
912 GENERAL_NAMES *names = NULL;
913 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000914 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000915 BIO *biobuf = NULL;
916 char buf[2048];
917 char *vptr;
918 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000919 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000920
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000921 if (certificate == NULL)
922 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000924 /* get a memory buffer */
925 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000926
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200927 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000928 while ((i = X509_get_ext_by_NID(
929 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000930
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 if (peer_alt_names == Py_None) {
932 peer_alt_names = PyList_New(0);
933 if (peer_alt_names == NULL)
934 goto fail;
935 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000936
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000937 /* now decode the altName */
938 ext = X509_get_ext(certificate, i);
939 if(!(method = X509V3_EXT_get(ext))) {
940 PyErr_SetString
941 (PySSLErrorObject,
942 ERRSTR("No method for internalizing subjectAltName!"));
943 goto fail;
944 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000945
Christian Heimes598894f2016-09-05 23:19:05 +0200946 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000947 if (method->it)
948 names = (GENERAL_NAMES*)
949 (ASN1_item_d2i(NULL,
950 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200951 X509_EXTENSION_get_data(ext)->length,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000952 ASN1_ITEM_ptr(method->it)));
953 else
954 names = (GENERAL_NAMES*)
955 (method->d2i(NULL,
956 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200957 X509_EXTENSION_get_data(ext)->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000958
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000960 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200961 int gntype;
962 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000963
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000964 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200965 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200966 switch (gntype) {
967 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000968 /* we special-case DirName as a tuple of
969 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000970
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000971 t = PyTuple_New(2);
972 if (t == NULL) {
973 goto fail;
974 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000975
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000976 v = PyUnicode_FromString("DirName");
977 if (v == NULL) {
978 Py_DECREF(t);
979 goto fail;
980 }
981 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000982
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000983 v = _create_tuple_for_X509_NAME (name->d.dirn);
984 if (v == NULL) {
985 Py_DECREF(t);
986 goto fail;
987 }
988 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200989 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000990
Christian Heimes824f7f32013-08-17 00:54:47 +0200991 case GEN_EMAIL:
992 case GEN_DNS:
993 case GEN_URI:
994 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
995 correctly, CVE-2013-4238 */
996 t = PyTuple_New(2);
997 if (t == NULL)
998 goto fail;
999 switch (gntype) {
1000 case GEN_EMAIL:
1001 v = PyUnicode_FromString("email");
1002 as = name->d.rfc822Name;
1003 break;
1004 case GEN_DNS:
1005 v = PyUnicode_FromString("DNS");
1006 as = name->d.dNSName;
1007 break;
1008 case GEN_URI:
1009 v = PyUnicode_FromString("URI");
1010 as = name->d.uniformResourceIdentifier;
1011 break;
1012 }
1013 if (v == NULL) {
1014 Py_DECREF(t);
1015 goto fail;
1016 }
1017 PyTuple_SET_ITEM(t, 0, v);
1018 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1019 ASN1_STRING_length(as));
1020 if (v == NULL) {
1021 Py_DECREF(t);
1022 goto fail;
1023 }
1024 PyTuple_SET_ITEM(t, 1, v);
1025 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001026
Christian Heimes1c03abd2016-09-06 23:25:35 +02001027 case GEN_RID:
1028 t = PyTuple_New(2);
1029 if (t == NULL)
1030 goto fail;
1031
1032 v = PyUnicode_FromString("Registered ID");
1033 if (v == NULL) {
1034 Py_DECREF(t);
1035 goto fail;
1036 }
1037 PyTuple_SET_ITEM(t, 0, v);
1038
1039 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1040 if (len < 0) {
1041 Py_DECREF(t);
1042 _setSSLError(NULL, 0, __FILE__, __LINE__);
1043 goto fail;
1044 } else if (len >= (int)sizeof(buf)) {
1045 v = PyUnicode_FromString("<INVALID>");
1046 } else {
1047 v = PyUnicode_FromStringAndSize(buf, len);
1048 }
1049 if (v == NULL) {
1050 Py_DECREF(t);
1051 goto fail;
1052 }
1053 PyTuple_SET_ITEM(t, 1, v);
1054 break;
1055
Christian Heimes824f7f32013-08-17 00:54:47 +02001056 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001058 switch (gntype) {
1059 /* check for new general name type */
1060 case GEN_OTHERNAME:
1061 case GEN_X400:
1062 case GEN_EDIPARTY:
1063 case GEN_IPADD:
1064 case GEN_RID:
1065 break;
1066 default:
1067 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1068 "Unknown general name type %d",
1069 gntype) == -1) {
1070 goto fail;
1071 }
1072 break;
1073 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001074 (void) BIO_reset(biobuf);
1075 GENERAL_NAME_print(biobuf, name);
1076 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1077 if (len < 0) {
1078 _setSSLError(NULL, 0, __FILE__, __LINE__);
1079 goto fail;
1080 }
1081 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001082 if (vptr == NULL) {
1083 PyErr_Format(PyExc_ValueError,
1084 "Invalid value %.200s",
1085 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001086 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001087 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001088 t = PyTuple_New(2);
1089 if (t == NULL)
1090 goto fail;
1091 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1092 if (v == NULL) {
1093 Py_DECREF(t);
1094 goto fail;
1095 }
1096 PyTuple_SET_ITEM(t, 0, v);
1097 v = PyUnicode_FromStringAndSize((vptr + 1),
1098 (len - (vptr - buf + 1)));
1099 if (v == NULL) {
1100 Py_DECREF(t);
1101 goto fail;
1102 }
1103 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001104 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001106
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001108
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 if (PyList_Append(peer_alt_names, t) < 0) {
1110 Py_DECREF(t);
1111 goto fail;
1112 }
1113 Py_DECREF(t);
1114 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001115 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001116 }
1117 BIO_free(biobuf);
1118 if (peer_alt_names != Py_None) {
1119 v = PyList_AsTuple(peer_alt_names);
1120 Py_DECREF(peer_alt_names);
1121 return v;
1122 } else {
1123 return peer_alt_names;
1124 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001125
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001126
1127 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001128 if (biobuf != NULL)
1129 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001130
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131 if (peer_alt_names != Py_None) {
1132 Py_XDECREF(peer_alt_names);
1133 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001134
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001135 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136}
1137
1138static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001139_get_aia_uri(X509 *certificate, int nid) {
1140 PyObject *lst = NULL, *ostr = NULL;
1141 int i, result;
1142 AUTHORITY_INFO_ACCESS *info;
1143
1144 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001145 if (info == NULL)
1146 return Py_None;
1147 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1148 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001149 return Py_None;
1150 }
1151
1152 if ((lst = PyList_New(0)) == NULL) {
1153 goto fail;
1154 }
1155
1156 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1157 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1158 ASN1_IA5STRING *uri;
1159
1160 if ((OBJ_obj2nid(ad->method) != nid) ||
1161 (ad->location->type != GEN_URI)) {
1162 continue;
1163 }
1164 uri = ad->location->d.uniformResourceIdentifier;
1165 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1166 uri->length);
1167 if (ostr == NULL) {
1168 goto fail;
1169 }
1170 result = PyList_Append(lst, ostr);
1171 Py_DECREF(ostr);
1172 if (result < 0) {
1173 goto fail;
1174 }
1175 }
1176 AUTHORITY_INFO_ACCESS_free(info);
1177
1178 /* convert to tuple or None */
1179 if (PyList_Size(lst) == 0) {
1180 Py_DECREF(lst);
1181 return Py_None;
1182 } else {
1183 PyObject *tup;
1184 tup = PyList_AsTuple(lst);
1185 Py_DECREF(lst);
1186 return tup;
1187 }
1188
1189 fail:
1190 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001191 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001192 return NULL;
1193}
1194
1195static PyObject *
1196_get_crl_dp(X509 *certificate) {
1197 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001198 int i, j;
1199 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001200
Christian Heimes598894f2016-09-05 23:19:05 +02001201 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001202
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001203 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001204 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001205
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001206 lst = PyList_New(0);
1207 if (lst == NULL)
1208 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001209
1210 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1211 DIST_POINT *dp;
1212 STACK_OF(GENERAL_NAME) *gns;
1213
1214 dp = sk_DIST_POINT_value(dps, i);
1215 gns = dp->distpoint->name.fullname;
1216
1217 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1218 GENERAL_NAME *gn;
1219 ASN1_IA5STRING *uri;
1220 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001221 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001222
1223 gn = sk_GENERAL_NAME_value(gns, j);
1224 if (gn->type != GEN_URI) {
1225 continue;
1226 }
1227 uri = gn->d.uniformResourceIdentifier;
1228 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1229 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001230 if (ouri == NULL)
1231 goto done;
1232
1233 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001234 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001235 if (err < 0)
1236 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001237 }
1238 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001239
1240 /* Convert to tuple. */
1241 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1242
1243 done:
1244 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001245 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001246 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001247}
1248
1249static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001250_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001251
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001252 PyObject *retval = NULL;
1253 BIO *biobuf = NULL;
1254 PyObject *peer;
1255 PyObject *peer_alt_names = NULL;
1256 PyObject *issuer;
1257 PyObject *version;
1258 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001259 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001260 ASN1_INTEGER *serialNumber;
1261 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001262 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 ASN1_TIME *notBefore, *notAfter;
1264 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001265
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001266 retval = PyDict_New();
1267 if (retval == NULL)
1268 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001269
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001270 peer = _create_tuple_for_X509_NAME(
1271 X509_get_subject_name(certificate));
1272 if (peer == NULL)
1273 goto fail0;
1274 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1275 Py_DECREF(peer);
1276 goto fail0;
1277 }
1278 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001279
Antoine Pitroufb046912010-11-09 20:21:19 +00001280 issuer = _create_tuple_for_X509_NAME(
1281 X509_get_issuer_name(certificate));
1282 if (issuer == NULL)
1283 goto fail0;
1284 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001285 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001286 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001288 Py_DECREF(issuer);
1289
1290 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001291 if (version == NULL)
1292 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001293 if (PyDict_SetItemString(retval, "version", version) < 0) {
1294 Py_DECREF(version);
1295 goto fail0;
1296 }
1297 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001298
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001299 /* get a memory buffer */
1300 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001301
Antoine Pitroufb046912010-11-09 20:21:19 +00001302 (void) BIO_reset(biobuf);
1303 serialNumber = X509_get_serialNumber(certificate);
1304 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1305 i2a_ASN1_INTEGER(biobuf, serialNumber);
1306 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1307 if (len < 0) {
1308 _setSSLError(NULL, 0, __FILE__, __LINE__);
1309 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001310 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001311 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1312 if (sn_obj == NULL)
1313 goto fail1;
1314 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1315 Py_DECREF(sn_obj);
1316 goto fail1;
1317 }
1318 Py_DECREF(sn_obj);
1319
1320 (void) BIO_reset(biobuf);
1321 notBefore = X509_get_notBefore(certificate);
1322 ASN1_TIME_print(biobuf, notBefore);
1323 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1324 if (len < 0) {
1325 _setSSLError(NULL, 0, __FILE__, __LINE__);
1326 goto fail1;
1327 }
1328 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1329 if (pnotBefore == NULL)
1330 goto fail1;
1331 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1332 Py_DECREF(pnotBefore);
1333 goto fail1;
1334 }
1335 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001336
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001337 (void) BIO_reset(biobuf);
1338 notAfter = X509_get_notAfter(certificate);
1339 ASN1_TIME_print(biobuf, notAfter);
1340 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1341 if (len < 0) {
1342 _setSSLError(NULL, 0, __FILE__, __LINE__);
1343 goto fail1;
1344 }
1345 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1346 if (pnotAfter == NULL)
1347 goto fail1;
1348 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1349 Py_DECREF(pnotAfter);
1350 goto fail1;
1351 }
1352 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001353
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001354 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001355
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001356 peer_alt_names = _get_peer_alt_names(certificate);
1357 if (peer_alt_names == NULL)
1358 goto fail1;
1359 else if (peer_alt_names != Py_None) {
1360 if (PyDict_SetItemString(retval, "subjectAltName",
1361 peer_alt_names) < 0) {
1362 Py_DECREF(peer_alt_names);
1363 goto fail1;
1364 }
1365 Py_DECREF(peer_alt_names);
1366 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001367
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001368 /* Authority Information Access: OCSP URIs */
1369 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1370 if (obj == NULL) {
1371 goto fail1;
1372 } else if (obj != Py_None) {
1373 result = PyDict_SetItemString(retval, "OCSP", obj);
1374 Py_DECREF(obj);
1375 if (result < 0) {
1376 goto fail1;
1377 }
1378 }
1379
1380 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1381 if (obj == NULL) {
1382 goto fail1;
1383 } else if (obj != Py_None) {
1384 result = PyDict_SetItemString(retval, "caIssuers", obj);
1385 Py_DECREF(obj);
1386 if (result < 0) {
1387 goto fail1;
1388 }
1389 }
1390
1391 /* CDP (CRL distribution points) */
1392 obj = _get_crl_dp(certificate);
1393 if (obj == NULL) {
1394 goto fail1;
1395 } else if (obj != Py_None) {
1396 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1397 Py_DECREF(obj);
1398 if (result < 0) {
1399 goto fail1;
1400 }
1401 }
1402
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001403 BIO_free(biobuf);
1404 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001405
1406 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001407 if (biobuf != NULL)
1408 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001409 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001410 Py_XDECREF(retval);
1411 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001412}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001413
Christian Heimes9a5395a2013-06-17 15:44:12 +02001414static PyObject *
1415_certificate_to_der(X509 *certificate)
1416{
1417 unsigned char *bytes_buf = NULL;
1418 int len;
1419 PyObject *retval;
1420
1421 bytes_buf = NULL;
1422 len = i2d_X509(certificate, &bytes_buf);
1423 if (len < 0) {
1424 _setSSLError(NULL, 0, __FILE__, __LINE__);
1425 return NULL;
1426 }
1427 /* this is actually an immutable bytes sequence */
1428 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1429 OPENSSL_free(bytes_buf);
1430 return retval;
1431}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001432
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001433/*[clinic input]
1434_ssl._test_decode_cert
1435 path: object(converter="PyUnicode_FSConverter")
1436 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001437
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001438[clinic start generated code]*/
1439
1440static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001441_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1442/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001443{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001444 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001445 X509 *x=NULL;
1446 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001447
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001448 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1449 PyErr_SetString(PySSLErrorObject,
1450 "Can't malloc memory to read file");
1451 goto fail0;
1452 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001453
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001454 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001455 PyErr_SetString(PySSLErrorObject,
1456 "Can't open file");
1457 goto fail0;
1458 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001459
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001460 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1461 if (x == NULL) {
1462 PyErr_SetString(PySSLErrorObject,
1463 "Error decoding PEM-encoded file");
1464 goto fail0;
1465 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001466
Antoine Pitroufb046912010-11-09 20:21:19 +00001467 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001468 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001469
1470 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001471 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001472 if (cert != NULL) BIO_free(cert);
1473 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001474}
1475
1476
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001477/*[clinic input]
1478_ssl._SSLSocket.peer_certificate
1479 der as binary_mode: bool = False
1480 /
1481
1482Returns the certificate for the peer.
1483
1484If no certificate was provided, returns None. If a certificate was
1485provided, but not validated, returns an empty dictionary. Otherwise
1486returns a dict containing information about the peer certificate.
1487
1488If the optional argument is True, returns a DER-encoded copy of the
1489peer certificate, or None if no certificate was provided. This will
1490return the certificate even if it wasn't validated.
1491[clinic start generated code]*/
1492
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001493static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001494_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1495/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001496{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001497 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001498 X509 *peer_cert;
1499 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001500
Christian Heimes66dc33b2017-05-23 16:02:02 -07001501 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001502 PyErr_SetString(PyExc_ValueError,
1503 "handshake not done yet");
1504 return NULL;
1505 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001506 peer_cert = SSL_get_peer_certificate(self->ssl);
1507 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001508 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001509
Antoine Pitrou721738f2012-08-15 23:20:39 +02001510 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001511 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001512 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001513 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001514 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001515 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001516 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001517 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001518 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001519 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001520 X509_free(peer_cert);
1521 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001522}
1523
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001524static PyObject *
1525cipher_to_tuple(const SSL_CIPHER *cipher)
1526{
1527 const char *cipher_name, *cipher_protocol;
1528 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001529 if (retval == NULL)
1530 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001531
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001532 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001533 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001534 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001535 PyTuple_SET_ITEM(retval, 0, Py_None);
1536 } else {
1537 v = PyUnicode_FromString(cipher_name);
1538 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001539 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001540 PyTuple_SET_ITEM(retval, 0, v);
1541 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001542
1543 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001544 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001545 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001546 PyTuple_SET_ITEM(retval, 1, Py_None);
1547 } else {
1548 v = PyUnicode_FromString(cipher_protocol);
1549 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001550 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001551 PyTuple_SET_ITEM(retval, 1, v);
1552 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001553
1554 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001555 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001556 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001557 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001558
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001559 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001560
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001561 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001562 Py_DECREF(retval);
1563 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001564}
1565
Christian Heimes25bfcd52016-09-06 00:04:45 +02001566#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1567static PyObject *
1568cipher_to_dict(const SSL_CIPHER *cipher)
1569{
1570 const char *cipher_name, *cipher_protocol;
1571
1572 unsigned long cipher_id;
1573 int alg_bits, strength_bits, len;
1574 char buf[512] = {0};
1575#if OPENSSL_VERSION_1_1
1576 int aead, nid;
1577 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1578#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001579
1580 /* can be NULL */
1581 cipher_name = SSL_CIPHER_get_name(cipher);
1582 cipher_protocol = SSL_CIPHER_get_version(cipher);
1583 cipher_id = SSL_CIPHER_get_id(cipher);
1584 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1585 len = strlen(buf);
1586 if (len > 1 && buf[len-1] == '\n')
1587 buf[len-1] = '\0';
1588 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1589
1590#if OPENSSL_VERSION_1_1
1591 aead = SSL_CIPHER_is_aead(cipher);
1592 nid = SSL_CIPHER_get_cipher_nid(cipher);
1593 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1594 nid = SSL_CIPHER_get_digest_nid(cipher);
1595 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1596 nid = SSL_CIPHER_get_kx_nid(cipher);
1597 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1598 nid = SSL_CIPHER_get_auth_nid(cipher);
1599 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1600#endif
1601
Victor Stinner410b9882016-09-12 12:00:23 +02001602 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001603 "{sksssssssisi"
1604#if OPENSSL_VERSION_1_1
1605 "sOssssssss"
1606#endif
1607 "}",
1608 "id", cipher_id,
1609 "name", cipher_name,
1610 "protocol", cipher_protocol,
1611 "description", buf,
1612 "strength_bits", strength_bits,
1613 "alg_bits", alg_bits
1614#if OPENSSL_VERSION_1_1
1615 ,"aead", aead ? Py_True : Py_False,
1616 "symmetric", skcipher,
1617 "digest", digest,
1618 "kea", kx,
1619 "auth", auth
1620#endif
1621 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001622}
1623#endif
1624
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001625/*[clinic input]
1626_ssl._SSLSocket.shared_ciphers
1627[clinic start generated code]*/
1628
1629static PyObject *
1630_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1631/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001632{
1633 STACK_OF(SSL_CIPHER) *ciphers;
1634 int i;
1635 PyObject *res;
1636
Christian Heimes598894f2016-09-05 23:19:05 +02001637 ciphers = SSL_get_ciphers(self->ssl);
1638 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001639 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001640 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1641 if (!res)
1642 return NULL;
1643 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1644 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1645 if (!tup) {
1646 Py_DECREF(res);
1647 return NULL;
1648 }
1649 PyList_SET_ITEM(res, i, tup);
1650 }
1651 return res;
1652}
1653
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001654/*[clinic input]
1655_ssl._SSLSocket.cipher
1656[clinic start generated code]*/
1657
1658static PyObject *
1659_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1660/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001661{
1662 const SSL_CIPHER *current;
1663
1664 if (self->ssl == NULL)
1665 Py_RETURN_NONE;
1666 current = SSL_get_current_cipher(self->ssl);
1667 if (current == NULL)
1668 Py_RETURN_NONE;
1669 return cipher_to_tuple(current);
1670}
1671
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001672/*[clinic input]
1673_ssl._SSLSocket.version
1674[clinic start generated code]*/
1675
1676static PyObject *
1677_ssl__SSLSocket_version_impl(PySSLSocket *self)
1678/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001679{
1680 const char *version;
1681
1682 if (self->ssl == NULL)
1683 Py_RETURN_NONE;
1684 version = SSL_get_version(self->ssl);
1685 if (!strcmp(version, "unknown"))
1686 Py_RETURN_NONE;
1687 return PyUnicode_FromString(version);
1688}
1689
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001690#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001691/*[clinic input]
1692_ssl._SSLSocket.selected_npn_protocol
1693[clinic start generated code]*/
1694
1695static PyObject *
1696_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1697/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1698{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001699 const unsigned char *out;
1700 unsigned int outlen;
1701
Victor Stinner4569cd52013-06-23 14:58:43 +02001702 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001703 &out, &outlen);
1704
1705 if (out == NULL)
1706 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001707 return PyUnicode_FromStringAndSize((char *)out, outlen);
1708}
1709#endif
1710
1711#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001712/*[clinic input]
1713_ssl._SSLSocket.selected_alpn_protocol
1714[clinic start generated code]*/
1715
1716static PyObject *
1717_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1718/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1719{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001720 const unsigned char *out;
1721 unsigned int outlen;
1722
1723 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1724
1725 if (out == NULL)
1726 Py_RETURN_NONE;
1727 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001728}
1729#endif
1730
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001731/*[clinic input]
1732_ssl._SSLSocket.compression
1733[clinic start generated code]*/
1734
1735static PyObject *
1736_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1737/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1738{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001739#ifdef OPENSSL_NO_COMP
1740 Py_RETURN_NONE;
1741#else
1742 const COMP_METHOD *comp_method;
1743 const char *short_name;
1744
1745 if (self->ssl == NULL)
1746 Py_RETURN_NONE;
1747 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001748 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001749 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001750 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001751 if (short_name == NULL)
1752 Py_RETURN_NONE;
1753 return PyUnicode_DecodeFSDefault(short_name);
1754#endif
1755}
1756
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001757static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1758 Py_INCREF(self->ctx);
1759 return self->ctx;
1760}
1761
1762static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1763 void *closure) {
1764
1765 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001766#if !HAVE_SNI
1767 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1768 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001769 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001770#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001771 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001772 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001773 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001774#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001775 } else {
1776 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1777 return -1;
1778 }
1779
1780 return 0;
1781}
1782
1783PyDoc_STRVAR(PySSL_set_context_doc,
1784"_setter_context(ctx)\n\
1785\
1786This changes the context associated with the SSLSocket. This is typically\n\
1787used from within a callback function set by the set_servername_callback\n\
1788on the SSLContext to change the certificate information associated with the\n\
1789SSLSocket before the cryptographic exchange handshake messages\n");
1790
1791
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001792static PyObject *
1793PySSL_get_server_side(PySSLSocket *self, void *c)
1794{
1795 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1796}
1797
1798PyDoc_STRVAR(PySSL_get_server_side_doc,
1799"Whether this is a server-side socket.");
1800
1801static PyObject *
1802PySSL_get_server_hostname(PySSLSocket *self, void *c)
1803{
1804 if (self->server_hostname == NULL)
1805 Py_RETURN_NONE;
1806 Py_INCREF(self->server_hostname);
1807 return self->server_hostname;
1808}
1809
1810PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1811"The currently set server hostname (for SNI).");
1812
1813static PyObject *
1814PySSL_get_owner(PySSLSocket *self, void *c)
1815{
1816 PyObject *owner;
1817
1818 if (self->owner == NULL)
1819 Py_RETURN_NONE;
1820
1821 owner = PyWeakref_GetObject(self->owner);
1822 Py_INCREF(owner);
1823 return owner;
1824}
1825
1826static int
1827PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1828{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001829 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001830 if (self->owner == NULL)
1831 return -1;
1832 return 0;
1833}
1834
1835PyDoc_STRVAR(PySSL_get_owner_doc,
1836"The Python-level owner of this object.\
1837Passed as \"self\" in servername callback.");
1838
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001839
Antoine Pitrou152efa22010-05-16 18:19:27 +00001840static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001841{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001842 if (self->ssl)
1843 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001844 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001845 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001846 Py_XDECREF(self->server_hostname);
1847 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001848 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001849}
1850
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001851/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001852 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001853 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001854 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001855
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001856static int
Victor Stinner14690702015-04-06 22:46:13 +02001857PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001858{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001859 int rc;
1860#ifdef HAVE_POLL
1861 struct pollfd pollfd;
1862 _PyTime_t ms;
1863#else
1864 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001865 fd_set fds;
1866 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001867#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001868
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001869 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001870 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001871 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001872 else if (timeout < 0) {
1873 if (s->sock_timeout > 0)
1874 return SOCKET_HAS_TIMED_OUT;
1875 else
1876 return SOCKET_IS_BLOCKING;
1877 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001878
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001879 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001880 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001881 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001882
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001883 /* Prefer poll, if available, since you can poll() any fd
1884 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001885#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001886 pollfd.fd = s->sock_fd;
1887 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001888
Victor Stinner14690702015-04-06 22:46:13 +02001889 /* timeout is in seconds, poll() uses milliseconds */
1890 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001891 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001892
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001893 PySSL_BEGIN_ALLOW_THREADS
1894 rc = poll(&pollfd, 1, (int)ms);
1895 PySSL_END_ALLOW_THREADS
1896#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001897 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001898 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001899 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001900
Victor Stinner14690702015-04-06 22:46:13 +02001901 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001902
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001903 FD_ZERO(&fds);
1904 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001905
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001906 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001907 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001908 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001909 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001910 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001911 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001912 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001913 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001914#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001915
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001916 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1917 (when we are able to write or when there's something to read) */
1918 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001919}
1920
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001921/*[clinic input]
1922_ssl._SSLSocket.write
1923 b: Py_buffer
1924 /
1925
1926Writes the bytes-like object b into the SSL object.
1927
1928Returns the number of bytes written.
1929[clinic start generated code]*/
1930
1931static PyObject *
1932_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1933/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001934{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001935 int len;
1936 int sockstate;
1937 int err;
1938 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001939 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001940 _PyTime_t timeout, deadline = 0;
1941 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001942
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001943 if (sock != NULL) {
1944 if (((PyObject*)sock) == Py_None) {
1945 _setSSLError("Underlying socket connection gone",
1946 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1947 return NULL;
1948 }
1949 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001950 }
1951
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001952 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001953 PyErr_Format(PyExc_OverflowError,
1954 "string longer than %d bytes", INT_MAX);
1955 goto error;
1956 }
1957
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001958 if (sock != NULL) {
1959 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001960 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001961 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1962 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1963 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001964
Victor Stinner14690702015-04-06 22:46:13 +02001965 timeout = GET_SOCKET_TIMEOUT(sock);
1966 has_timeout = (timeout > 0);
1967 if (has_timeout)
1968 deadline = _PyTime_GetMonotonicClock() + timeout;
1969
1970 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001971 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001972 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001973 "The write operation timed out");
1974 goto error;
1975 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1976 PyErr_SetString(PySSLErrorObject,
1977 "Underlying socket has been closed.");
1978 goto error;
1979 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1980 PyErr_SetString(PySSLErrorObject,
1981 "Underlying socket too large for select().");
1982 goto error;
1983 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001984
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001985 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001986 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001987 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001988 err = SSL_get_error(self->ssl, len);
1989 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001990
1991 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001992 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001993
Victor Stinner14690702015-04-06 22:46:13 +02001994 if (has_timeout)
1995 timeout = deadline - _PyTime_GetMonotonicClock();
1996
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001997 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001998 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001999 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002000 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002001 } else {
2002 sockstate = SOCKET_OPERATION_OK;
2003 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002004
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002005 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002006 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002007 "The write operation timed out");
2008 goto error;
2009 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2010 PyErr_SetString(PySSLErrorObject,
2011 "Underlying socket has been closed.");
2012 goto error;
2013 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2014 break;
2015 }
2016 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002017
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002018 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002019 if (len > 0)
2020 return PyLong_FromLong(len);
2021 else
2022 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002023
2024error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002025 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002026 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002027}
2028
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002029/*[clinic input]
2030_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002031
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002032Returns the number of already decrypted bytes available for read, pending on the connection.
2033[clinic start generated code]*/
2034
2035static PyObject *
2036_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2037/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002038{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002039 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002040
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002041 PySSL_BEGIN_ALLOW_THREADS
2042 count = SSL_pending(self->ssl);
2043 PySSL_END_ALLOW_THREADS
2044 if (count < 0)
2045 return PySSL_SetError(self, count, __FILE__, __LINE__);
2046 else
2047 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002048}
2049
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002050/*[clinic input]
2051_ssl._SSLSocket.read
2052 size as len: int
2053 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002054 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002055 ]
2056 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002057
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002058Read up to size bytes from the SSL socket.
2059[clinic start generated code]*/
2060
2061static PyObject *
2062_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2063 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002064/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002065{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002066 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002067 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002068 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002069 int sockstate;
2070 int err;
2071 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002072 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002073 _PyTime_t timeout, deadline = 0;
2074 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002075
Martin Panter5503d472016-03-27 05:35:19 +00002076 if (!group_right_1 && len < 0) {
2077 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2078 return NULL;
2079 }
2080
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002081 if (sock != NULL) {
2082 if (((PyObject*)sock) == Py_None) {
2083 _setSSLError("Underlying socket connection gone",
2084 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2085 return NULL;
2086 }
2087 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002088 }
2089
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002090 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002091 dest = PyBytes_FromStringAndSize(NULL, len);
2092 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002093 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002094 if (len == 0) {
2095 Py_XDECREF(sock);
2096 return dest;
2097 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002098 mem = PyBytes_AS_STRING(dest);
2099 }
2100 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002101 mem = buffer->buf;
2102 if (len <= 0 || len > buffer->len) {
2103 len = (int) buffer->len;
2104 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002105 PyErr_SetString(PyExc_OverflowError,
2106 "maximum length can't fit in a C 'int'");
2107 goto error;
2108 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002109 if (len == 0) {
2110 count = 0;
2111 goto done;
2112 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002113 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002114 }
2115
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002116 if (sock != NULL) {
2117 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002118 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002119 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2120 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2121 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002122
Victor Stinner14690702015-04-06 22:46:13 +02002123 timeout = GET_SOCKET_TIMEOUT(sock);
2124 has_timeout = (timeout > 0);
2125 if (has_timeout)
2126 deadline = _PyTime_GetMonotonicClock() + timeout;
2127
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002128 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002129 PySSL_BEGIN_ALLOW_THREADS
2130 count = SSL_read(self->ssl, mem, len);
2131 err = SSL_get_error(self->ssl, count);
2132 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002133
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002134 if (PyErr_CheckSignals())
2135 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002136
Victor Stinner14690702015-04-06 22:46:13 +02002137 if (has_timeout)
2138 timeout = deadline - _PyTime_GetMonotonicClock();
2139
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002140 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002141 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002142 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002143 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002144 } else if (err == SSL_ERROR_ZERO_RETURN &&
2145 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002146 {
2147 count = 0;
2148 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002149 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002150 else
2151 sockstate = SOCKET_OPERATION_OK;
2152
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002153 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002154 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002155 "The read operation timed out");
2156 goto error;
2157 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2158 break;
2159 }
2160 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002161
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002162 if (count <= 0) {
2163 PySSL_SetError(self, count, __FILE__, __LINE__);
2164 goto error;
2165 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002166
2167done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002168 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002169 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002170 _PyBytes_Resize(&dest, count);
2171 return dest;
2172 }
2173 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002174 return PyLong_FromLong(count);
2175 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002176
2177error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002178 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002179 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002180 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002181 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002182}
2183
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002184/*[clinic input]
2185_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002186
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002187Does the SSL shutdown handshake with the remote end.
2188
2189Returns the underlying socket object.
2190[clinic start generated code]*/
2191
2192static PyObject *
2193_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2194/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002195{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002196 int err, ssl_err, sockstate, nonblocking;
2197 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002198 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002199 _PyTime_t timeout, deadline = 0;
2200 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002201
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002202 if (sock != NULL) {
2203 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002204 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002205 _setSSLError("Underlying socket connection gone",
2206 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2207 return NULL;
2208 }
2209 Py_INCREF(sock);
2210
2211 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002212 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002213 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2214 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002215 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002216
Victor Stinner14690702015-04-06 22:46:13 +02002217 timeout = GET_SOCKET_TIMEOUT(sock);
2218 has_timeout = (timeout > 0);
2219 if (has_timeout)
2220 deadline = _PyTime_GetMonotonicClock() + timeout;
2221
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002222 while (1) {
2223 PySSL_BEGIN_ALLOW_THREADS
2224 /* Disable read-ahead so that unwrap can work correctly.
2225 * Otherwise OpenSSL might read in too much data,
2226 * eating clear text data that happens to be
2227 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002228 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002229 * function is used and the shutdown_seen_zero != 0
2230 * condition is met.
2231 */
2232 if (self->shutdown_seen_zero)
2233 SSL_set_read_ahead(self->ssl, 0);
2234 err = SSL_shutdown(self->ssl);
2235 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002236
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002237 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2238 if (err > 0)
2239 break;
2240 if (err == 0) {
2241 /* Don't loop endlessly; instead preserve legacy
2242 behaviour of trying SSL_shutdown() only twice.
2243 This looks necessary for OpenSSL < 0.9.8m */
2244 if (++zeros > 1)
2245 break;
2246 /* Shutdown was sent, now try receiving */
2247 self->shutdown_seen_zero = 1;
2248 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002249 }
2250
Victor Stinner14690702015-04-06 22:46:13 +02002251 if (has_timeout)
2252 timeout = deadline - _PyTime_GetMonotonicClock();
2253
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002254 /* Possibly retry shutdown until timeout or failure */
2255 ssl_err = SSL_get_error(self->ssl, err);
2256 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002257 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002258 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002259 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002260 else
2261 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002263 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2264 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002265 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002266 "The read operation timed out");
2267 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002268 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002269 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002270 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002271 }
2272 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2273 PyErr_SetString(PySSLErrorObject,
2274 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002275 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002276 }
2277 else if (sockstate != SOCKET_OPERATION_OK)
2278 /* Retain the SSL error code */
2279 break;
2280 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002281
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002282 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002283 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002284 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002285 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002286 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002287 /* It's already INCREF'ed */
2288 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002289 else
2290 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002291
2292error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002293 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002294 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002295}
2296
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002297/*[clinic input]
2298_ssl._SSLSocket.tls_unique_cb
2299
2300Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2301
2302If the TLS handshake is not yet complete, None is returned.
2303[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002304
Antoine Pitroud6494802011-07-21 01:11:30 +02002305static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002306_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2307/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002308{
2309 PyObject *retval = NULL;
2310 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002311 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002312
2313 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2314 /* if session is resumed XOR we are the client */
2315 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2316 }
2317 else {
2318 /* if a new session XOR we are the server */
2319 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2320 }
2321
2322 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002323 if (len == 0)
2324 Py_RETURN_NONE;
2325
2326 retval = PyBytes_FromStringAndSize(buf, len);
2327
2328 return retval;
2329}
2330
Christian Heimes99a65702016-09-10 23:44:53 +02002331#ifdef OPENSSL_VERSION_1_1
2332
2333static SSL_SESSION*
2334_ssl_session_dup(SSL_SESSION *session) {
2335 SSL_SESSION *newsession = NULL;
2336 int slen;
2337 unsigned char *senc = NULL, *p;
2338 const unsigned char *const_p;
2339
2340 if (session == NULL) {
2341 PyErr_SetString(PyExc_ValueError, "Invalid session");
2342 goto error;
2343 }
2344
2345 /* get length */
2346 slen = i2d_SSL_SESSION(session, NULL);
2347 if (slen == 0 || slen > 0xFF00) {
2348 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2349 goto error;
2350 }
2351 if ((senc = PyMem_Malloc(slen)) == NULL) {
2352 PyErr_NoMemory();
2353 goto error;
2354 }
2355 p = senc;
2356 if (!i2d_SSL_SESSION(session, &p)) {
2357 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2358 goto error;
2359 }
2360 const_p = senc;
2361 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2362 if (session == NULL) {
2363 goto error;
2364 }
2365 PyMem_Free(senc);
2366 return newsession;
2367 error:
2368 if (senc != NULL) {
2369 PyMem_Free(senc);
2370 }
2371 return NULL;
2372}
2373#endif
2374
2375static PyObject *
2376PySSL_get_session(PySSLSocket *self, void *closure) {
2377 /* get_session can return sessions from a server-side connection,
2378 * it does not check for handshake done or client socket. */
2379 PySSLSession *pysess;
2380 SSL_SESSION *session;
2381
2382#ifdef OPENSSL_VERSION_1_1
2383 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2384 * https://github.com/openssl/openssl/issues/1550 */
2385 session = SSL_get0_session(self->ssl); /* borrowed reference */
2386 if (session == NULL) {
2387 Py_RETURN_NONE;
2388 }
2389 if ((session = _ssl_session_dup(session)) == NULL) {
2390 return NULL;
2391 }
2392#else
2393 session = SSL_get1_session(self->ssl);
2394 if (session == NULL) {
2395 Py_RETURN_NONE;
2396 }
2397#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002398 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002399 if (pysess == NULL) {
2400 SSL_SESSION_free(session);
2401 return NULL;
2402 }
2403
2404 assert(self->ctx);
2405 pysess->ctx = self->ctx;
2406 Py_INCREF(pysess->ctx);
2407 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002408 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002409 return (PyObject *)pysess;
2410}
2411
2412static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2413 void *closure)
2414 {
2415 PySSLSession *pysess;
2416#ifdef OPENSSL_VERSION_1_1
2417 SSL_SESSION *session;
2418#endif
2419 int result;
2420
2421 if (!PySSLSession_Check(value)) {
2422 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2423 return -1;
2424 }
2425 pysess = (PySSLSession *)value;
2426
2427 if (self->ctx->ctx != pysess->ctx->ctx) {
2428 PyErr_SetString(PyExc_ValueError,
2429 "Session refers to a different SSLContext.");
2430 return -1;
2431 }
2432 if (self->socket_type != PY_SSL_CLIENT) {
2433 PyErr_SetString(PyExc_ValueError,
2434 "Cannot set session for server-side SSLSocket.");
2435 return -1;
2436 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002437 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002438 PyErr_SetString(PyExc_ValueError,
2439 "Cannot set session after handshake.");
2440 return -1;
2441 }
2442#ifdef OPENSSL_VERSION_1_1
2443 /* duplicate session */
2444 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2445 return -1;
2446 }
2447 result = SSL_set_session(self->ssl, session);
2448 /* free duplicate, SSL_set_session() bumps ref count */
2449 SSL_SESSION_free(session);
2450#else
2451 result = SSL_set_session(self->ssl, pysess->session);
2452#endif
2453 if (result == 0) {
2454 _setSSLError(NULL, 0, __FILE__, __LINE__);
2455 return -1;
2456 }
2457 return 0;
2458}
2459
2460PyDoc_STRVAR(PySSL_set_session_doc,
2461"_setter_session(session)\n\
2462\
2463Get / set SSLSession.");
2464
2465static PyObject *
2466PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2467 if (SSL_session_reused(self->ssl)) {
2468 Py_RETURN_TRUE;
2469 } else {
2470 Py_RETURN_FALSE;
2471 }
2472}
2473
2474PyDoc_STRVAR(PySSL_get_session_reused_doc,
2475"Was the client session reused during handshake?");
2476
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002477static PyGetSetDef ssl_getsetlist[] = {
2478 {"context", (getter) PySSL_get_context,
2479 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002480 {"server_side", (getter) PySSL_get_server_side, NULL,
2481 PySSL_get_server_side_doc},
2482 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2483 PySSL_get_server_hostname_doc},
2484 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2485 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002486 {"session", (getter) PySSL_get_session,
2487 (setter) PySSL_set_session, PySSL_set_session_doc},
2488 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2489 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002490 {NULL}, /* sentinel */
2491};
2492
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002493static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002494 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2495 _SSL__SSLSOCKET_WRITE_METHODDEF
2496 _SSL__SSLSOCKET_READ_METHODDEF
2497 _SSL__SSLSOCKET_PENDING_METHODDEF
2498 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2499 _SSL__SSLSOCKET_CIPHER_METHODDEF
2500 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2501 _SSL__SSLSOCKET_VERSION_METHODDEF
2502 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2503 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2504 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2505 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2506 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002507 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002508};
2509
Antoine Pitrou152efa22010-05-16 18:19:27 +00002510static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002511 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002512 "_ssl._SSLSocket", /*tp_name*/
2513 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002514 0, /*tp_itemsize*/
2515 /* methods */
2516 (destructor)PySSL_dealloc, /*tp_dealloc*/
2517 0, /*tp_print*/
2518 0, /*tp_getattr*/
2519 0, /*tp_setattr*/
2520 0, /*tp_reserved*/
2521 0, /*tp_repr*/
2522 0, /*tp_as_number*/
2523 0, /*tp_as_sequence*/
2524 0, /*tp_as_mapping*/
2525 0, /*tp_hash*/
2526 0, /*tp_call*/
2527 0, /*tp_str*/
2528 0, /*tp_getattro*/
2529 0, /*tp_setattro*/
2530 0, /*tp_as_buffer*/
2531 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2532 0, /*tp_doc*/
2533 0, /*tp_traverse*/
2534 0, /*tp_clear*/
2535 0, /*tp_richcompare*/
2536 0, /*tp_weaklistoffset*/
2537 0, /*tp_iter*/
2538 0, /*tp_iternext*/
2539 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002540 0, /*tp_members*/
2541 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002542};
2543
Antoine Pitrou152efa22010-05-16 18:19:27 +00002544
2545/*
2546 * _SSLContext objects
2547 */
2548
Christian Heimes5fe668c2016-09-12 00:01:11 +02002549static int
2550_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2551{
2552 int mode;
2553 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2554
2555 switch(n) {
2556 case PY_SSL_CERT_NONE:
2557 mode = SSL_VERIFY_NONE;
2558 break;
2559 case PY_SSL_CERT_OPTIONAL:
2560 mode = SSL_VERIFY_PEER;
2561 break;
2562 case PY_SSL_CERT_REQUIRED:
2563 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2564 break;
2565 default:
2566 PyErr_SetString(PyExc_ValueError,
2567 "invalid value for verify_mode");
2568 return -1;
2569 }
2570 /* keep current verify cb */
2571 verify_cb = SSL_CTX_get_verify_callback(ctx);
2572 SSL_CTX_set_verify(ctx, mode, verify_cb);
2573 return 0;
2574}
2575
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002576/*[clinic input]
2577@classmethod
2578_ssl._SSLContext.__new__
2579 protocol as proto_version: int
2580 /
2581[clinic start generated code]*/
2582
Antoine Pitrou152efa22010-05-16 18:19:27 +00002583static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002584_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2585/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002586{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002587 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002588 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002589 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002590 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002591#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002592 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002593#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002594
Antoine Pitrou152efa22010-05-16 18:19:27 +00002595 PySSL_BEGIN_ALLOW_THREADS
2596 if (proto_version == PY_SSL_VERSION_TLS1)
2597 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002598#if HAVE_TLSv1_2
2599 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2600 ctx = SSL_CTX_new(TLSv1_1_method());
2601 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2602 ctx = SSL_CTX_new(TLSv1_2_method());
2603#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002604#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002605 else if (proto_version == PY_SSL_VERSION_SSL3)
2606 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002607#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002608#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002609 else if (proto_version == PY_SSL_VERSION_SSL2)
2610 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002611#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002612 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002613 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002614 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2615 ctx = SSL_CTX_new(TLS_client_method());
2616 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2617 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002618 else
2619 proto_version = -1;
2620 PySSL_END_ALLOW_THREADS
2621
2622 if (proto_version == -1) {
2623 PyErr_SetString(PyExc_ValueError,
2624 "invalid protocol version");
2625 return NULL;
2626 }
2627 if (ctx == NULL) {
2628 PyErr_SetString(PySSLErrorObject,
2629 "failed to allocate SSL context");
2630 return NULL;
2631 }
2632
2633 assert(type != NULL && type->tp_alloc != NULL);
2634 self = (PySSLContext *) type->tp_alloc(type, 0);
2635 if (self == NULL) {
2636 SSL_CTX_free(ctx);
2637 return NULL;
2638 }
2639 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002640#ifdef OPENSSL_NPN_NEGOTIATED
2641 self->npn_protocols = NULL;
2642#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002643#ifdef HAVE_ALPN
2644 self->alpn_protocols = NULL;
2645#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002646#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002647 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002648#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002649 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002650 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2651 self->check_hostname = 1;
2652 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2653 Py_DECREF(self);
2654 return NULL;
2655 }
2656 } else {
2657 self->check_hostname = 0;
2658 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2659 Py_DECREF(self);
2660 return NULL;
2661 }
2662 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002663 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002664 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2665 if (proto_version != PY_SSL_VERSION_SSL2)
2666 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002667 if (proto_version != PY_SSL_VERSION_SSL3)
2668 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002669 /* Minimal security flags for server and client side context.
2670 * Client sockets ignore server-side parameters. */
2671#ifdef SSL_OP_NO_COMPRESSION
2672 options |= SSL_OP_NO_COMPRESSION;
2673#endif
2674#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2675 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2676#endif
2677#ifdef SSL_OP_SINGLE_DH_USE
2678 options |= SSL_OP_SINGLE_DH_USE;
2679#endif
2680#ifdef SSL_OP_SINGLE_ECDH_USE
2681 options |= SSL_OP_SINGLE_ECDH_USE;
2682#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002683 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002684
Christian Heimes358cfd42016-09-10 22:43:48 +02002685 /* A bare minimum cipher list without completly broken cipher suites.
2686 * It's far from perfect but gives users a better head start. */
2687 if (proto_version != PY_SSL_VERSION_SSL2) {
2688 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2689 } else {
2690 /* SSLv2 needs MD5 */
2691 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2692 }
2693 if (result == 0) {
2694 Py_DECREF(self);
2695 ERR_clear_error();
2696 PyErr_SetString(PySSLErrorObject,
2697 "No cipher can be selected.");
2698 return NULL;
2699 }
2700
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002701#if defined(SSL_MODE_RELEASE_BUFFERS)
2702 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2703 usage for no cost at all. However, don't do this for OpenSSL versions
2704 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2705 2014-0198. I can't find exactly which beta fixed this CVE, so be
2706 conservative and assume it wasn't fixed until release. We do this check
2707 at runtime to avoid problems from the dynamic linker.
2708 See #25672 for more on this. */
2709 libver = SSLeay();
2710 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2711 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2712 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2713 }
2714#endif
2715
2716
Donald Stufft8ae264c2017-03-02 11:45:29 -05002717#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002718 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2719 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002720 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2721 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002722#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002723 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2724#else
2725 {
2726 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2727 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2728 EC_KEY_free(key);
2729 }
2730#endif
2731#endif
2732
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002733#define SID_CTX "Python"
2734 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2735 sizeof(SID_CTX));
2736#undef SID_CTX
2737
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002738#ifdef X509_V_FLAG_TRUSTED_FIRST
2739 {
2740 /* Improve trust chain building when cross-signed intermediate
2741 certificates are present. See https://bugs.python.org/issue23476. */
2742 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2743 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2744 }
2745#endif
2746
Antoine Pitrou152efa22010-05-16 18:19:27 +00002747 return (PyObject *)self;
2748}
2749
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002750static int
2751context_traverse(PySSLContext *self, visitproc visit, void *arg)
2752{
2753#ifndef OPENSSL_NO_TLSEXT
2754 Py_VISIT(self->set_hostname);
2755#endif
2756 return 0;
2757}
2758
2759static int
2760context_clear(PySSLContext *self)
2761{
2762#ifndef OPENSSL_NO_TLSEXT
2763 Py_CLEAR(self->set_hostname);
2764#endif
2765 return 0;
2766}
2767
Antoine Pitrou152efa22010-05-16 18:19:27 +00002768static void
2769context_dealloc(PySSLContext *self)
2770{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002771 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002772 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002773#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002774 PyMem_FREE(self->npn_protocols);
2775#endif
2776#ifdef HAVE_ALPN
2777 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002778#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002779 Py_TYPE(self)->tp_free(self);
2780}
2781
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002782/*[clinic input]
2783_ssl._SSLContext.set_ciphers
2784 cipherlist: str
2785 /
2786[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002787
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002788static PyObject *
2789_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2790/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2791{
2792 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002793 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002794 /* Clearing the error queue is necessary on some OpenSSL versions,
2795 otherwise the error will be reported again when another SSL call
2796 is done. */
2797 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002798 PyErr_SetString(PySSLErrorObject,
2799 "No cipher can be selected.");
2800 return NULL;
2801 }
2802 Py_RETURN_NONE;
2803}
2804
Christian Heimes25bfcd52016-09-06 00:04:45 +02002805#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2806/*[clinic input]
2807_ssl._SSLContext.get_ciphers
2808[clinic start generated code]*/
2809
2810static PyObject *
2811_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2812/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2813{
2814 SSL *ssl = NULL;
2815 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002816 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002817 int i=0;
2818 PyObject *result = NULL, *dct;
2819
2820 ssl = SSL_new(self->ctx);
2821 if (ssl == NULL) {
2822 _setSSLError(NULL, 0, __FILE__, __LINE__);
2823 goto exit;
2824 }
2825 sk = SSL_get_ciphers(ssl);
2826
2827 result = PyList_New(sk_SSL_CIPHER_num(sk));
2828 if (result == NULL) {
2829 goto exit;
2830 }
2831
2832 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2833 cipher = sk_SSL_CIPHER_value(sk, i);
2834 dct = cipher_to_dict(cipher);
2835 if (dct == NULL) {
2836 Py_CLEAR(result);
2837 goto exit;
2838 }
2839 PyList_SET_ITEM(result, i, dct);
2840 }
2841
2842 exit:
2843 if (ssl != NULL)
2844 SSL_free(ssl);
2845 return result;
2846
2847}
2848#endif
2849
2850
Benjamin Petersonc54de472015-01-28 12:06:39 -05002851#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002852static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002853do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2854 const unsigned char *server_protocols, unsigned int server_protocols_len,
2855 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002856{
Benjamin Peterson88615022015-01-23 17:30:26 -05002857 int ret;
2858 if (client_protocols == NULL) {
2859 client_protocols = (unsigned char *)"";
2860 client_protocols_len = 0;
2861 }
2862 if (server_protocols == NULL) {
2863 server_protocols = (unsigned char *)"";
2864 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002865 }
2866
Benjamin Peterson88615022015-01-23 17:30:26 -05002867 ret = SSL_select_next_proto(out, outlen,
2868 server_protocols, server_protocols_len,
2869 client_protocols, client_protocols_len);
2870 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2871 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002872
2873 return SSL_TLSEXT_ERR_OK;
2874}
2875
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002876/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2877static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002878_advertiseNPN_cb(SSL *s,
2879 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002880 void *args)
2881{
2882 PySSLContext *ssl_ctx = (PySSLContext *) args;
2883
2884 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002885 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002886 *len = 0;
2887 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002888 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002889 *len = ssl_ctx->npn_protocols_len;
2890 }
2891
2892 return SSL_TLSEXT_ERR_OK;
2893}
2894/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2895static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002896_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002897 unsigned char **out, unsigned char *outlen,
2898 const unsigned char *server, unsigned int server_len,
2899 void *args)
2900{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002901 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002902 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002903 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002904}
2905#endif
2906
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002907/*[clinic input]
2908_ssl._SSLContext._set_npn_protocols
2909 protos: Py_buffer
2910 /
2911[clinic start generated code]*/
2912
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002913static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002914_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2915 Py_buffer *protos)
2916/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002917{
2918#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002919 PyMem_Free(self->npn_protocols);
2920 self->npn_protocols = PyMem_Malloc(protos->len);
2921 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002922 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002923 memcpy(self->npn_protocols, protos->buf, protos->len);
2924 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002925
2926 /* set both server and client callbacks, because the context can
2927 * be used to create both types of sockets */
2928 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2929 _advertiseNPN_cb,
2930 self);
2931 SSL_CTX_set_next_proto_select_cb(self->ctx,
2932 _selectNPN_cb,
2933 self);
2934
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002935 Py_RETURN_NONE;
2936#else
2937 PyErr_SetString(PyExc_NotImplementedError,
2938 "The NPN extension requires OpenSSL 1.0.1 or later.");
2939 return NULL;
2940#endif
2941}
2942
Benjamin Petersoncca27322015-01-23 16:35:37 -05002943#ifdef HAVE_ALPN
2944static int
2945_selectALPN_cb(SSL *s,
2946 const unsigned char **out, unsigned char *outlen,
2947 const unsigned char *client_protocols, unsigned int client_protocols_len,
2948 void *args)
2949{
2950 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002951 return do_protocol_selection(1, (unsigned char **)out, outlen,
2952 ctx->alpn_protocols, ctx->alpn_protocols_len,
2953 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002954}
2955#endif
2956
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002957/*[clinic input]
2958_ssl._SSLContext._set_alpn_protocols
2959 protos: Py_buffer
2960 /
2961[clinic start generated code]*/
2962
Benjamin Petersoncca27322015-01-23 16:35:37 -05002963static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002964_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2965 Py_buffer *protos)
2966/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002967{
2968#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002969 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002970 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002971 if (!self->alpn_protocols)
2972 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002973 memcpy(self->alpn_protocols, protos->buf, protos->len);
2974 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002975
2976 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2977 return PyErr_NoMemory();
2978 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2979
Benjamin Petersoncca27322015-01-23 16:35:37 -05002980 Py_RETURN_NONE;
2981#else
2982 PyErr_SetString(PyExc_NotImplementedError,
2983 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2984 return NULL;
2985#endif
2986}
2987
Antoine Pitrou152efa22010-05-16 18:19:27 +00002988static PyObject *
2989get_verify_mode(PySSLContext *self, void *c)
2990{
2991 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2992 case SSL_VERIFY_NONE:
2993 return PyLong_FromLong(PY_SSL_CERT_NONE);
2994 case SSL_VERIFY_PEER:
2995 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2996 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2997 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2998 }
2999 PyErr_SetString(PySSLErrorObject,
3000 "invalid return value from SSL_CTX_get_verify_mode");
3001 return NULL;
3002}
3003
3004static int
3005set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3006{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003007 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003008 if (!PyArg_Parse(arg, "i", &n))
3009 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003010 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003011 PyErr_SetString(PyExc_ValueError,
3012 "Cannot set verify_mode to CERT_NONE when "
3013 "check_hostname is enabled.");
3014 return -1;
3015 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003016 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003017}
3018
3019static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003020get_verify_flags(PySSLContext *self, void *c)
3021{
3022 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003023 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003024 unsigned long flags;
3025
3026 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003027 param = X509_STORE_get0_param(store);
3028 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003029 return PyLong_FromUnsignedLong(flags);
3030}
3031
3032static int
3033set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3034{
3035 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003036 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003037 unsigned long new_flags, flags, set, clear;
3038
3039 if (!PyArg_Parse(arg, "k", &new_flags))
3040 return -1;
3041 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003042 param = X509_STORE_get0_param(store);
3043 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003044 clear = flags & ~new_flags;
3045 set = ~flags & new_flags;
3046 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003047 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003048 _setSSLError(NULL, 0, __FILE__, __LINE__);
3049 return -1;
3050 }
3051 }
3052 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003053 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003054 _setSSLError(NULL, 0, __FILE__, __LINE__);
3055 return -1;
3056 }
3057 }
3058 return 0;
3059}
3060
3061static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003062get_options(PySSLContext *self, void *c)
3063{
3064 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3065}
3066
3067static int
3068set_options(PySSLContext *self, PyObject *arg, void *c)
3069{
3070 long new_opts, opts, set, clear;
3071 if (!PyArg_Parse(arg, "l", &new_opts))
3072 return -1;
3073 opts = SSL_CTX_get_options(self->ctx);
3074 clear = opts & ~new_opts;
3075 set = ~opts & new_opts;
3076 if (clear) {
3077#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3078 SSL_CTX_clear_options(self->ctx, clear);
3079#else
3080 PyErr_SetString(PyExc_ValueError,
3081 "can't clear options before OpenSSL 0.9.8m");
3082 return -1;
3083#endif
3084 }
3085 if (set)
3086 SSL_CTX_set_options(self->ctx, set);
3087 return 0;
3088}
3089
Christian Heimes1aa9a752013-12-02 02:41:19 +01003090static PyObject *
3091get_check_hostname(PySSLContext *self, void *c)
3092{
3093 return PyBool_FromLong(self->check_hostname);
3094}
3095
3096static int
3097set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3098{
3099 int check_hostname;
3100 if (!PyArg_Parse(arg, "p", &check_hostname))
3101 return -1;
3102 if (check_hostname &&
3103 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3104 PyErr_SetString(PyExc_ValueError,
3105 "check_hostname needs a SSL context with either "
3106 "CERT_OPTIONAL or CERT_REQUIRED");
3107 return -1;
3108 }
3109 self->check_hostname = check_hostname;
3110 return 0;
3111}
3112
3113
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003114typedef struct {
3115 PyThreadState *thread_state;
3116 PyObject *callable;
3117 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003118 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003119 int error;
3120} _PySSLPasswordInfo;
3121
3122static int
3123_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3124 const char *bad_type_error)
3125{
3126 /* Set the password and size fields of a _PySSLPasswordInfo struct
3127 from a unicode, bytes, or byte array object.
3128 The password field will be dynamically allocated and must be freed
3129 by the caller */
3130 PyObject *password_bytes = NULL;
3131 const char *data = NULL;
3132 Py_ssize_t size;
3133
3134 if (PyUnicode_Check(password)) {
3135 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3136 if (!password_bytes) {
3137 goto error;
3138 }
3139 data = PyBytes_AS_STRING(password_bytes);
3140 size = PyBytes_GET_SIZE(password_bytes);
3141 } else if (PyBytes_Check(password)) {
3142 data = PyBytes_AS_STRING(password);
3143 size = PyBytes_GET_SIZE(password);
3144 } else if (PyByteArray_Check(password)) {
3145 data = PyByteArray_AS_STRING(password);
3146 size = PyByteArray_GET_SIZE(password);
3147 } else {
3148 PyErr_SetString(PyExc_TypeError, bad_type_error);
3149 goto error;
3150 }
3151
Victor Stinner9ee02032013-06-23 15:08:23 +02003152 if (size > (Py_ssize_t)INT_MAX) {
3153 PyErr_Format(PyExc_ValueError,
3154 "password cannot be longer than %d bytes", INT_MAX);
3155 goto error;
3156 }
3157
Victor Stinner11ebff22013-07-07 17:07:52 +02003158 PyMem_Free(pw_info->password);
3159 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003160 if (!pw_info->password) {
3161 PyErr_SetString(PyExc_MemoryError,
3162 "unable to allocate password buffer");
3163 goto error;
3164 }
3165 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003166 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003167
3168 Py_XDECREF(password_bytes);
3169 return 1;
3170
3171error:
3172 Py_XDECREF(password_bytes);
3173 return 0;
3174}
3175
3176static int
3177_password_callback(char *buf, int size, int rwflag, void *userdata)
3178{
3179 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3180 PyObject *fn_ret = NULL;
3181
3182 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3183
3184 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003185 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003186 if (!fn_ret) {
3187 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3188 core python API, so we could use it to add a frame here */
3189 goto error;
3190 }
3191
3192 if (!_pwinfo_set(pw_info, fn_ret,
3193 "password callback must return a string")) {
3194 goto error;
3195 }
3196 Py_CLEAR(fn_ret);
3197 }
3198
3199 if (pw_info->size > size) {
3200 PyErr_Format(PyExc_ValueError,
3201 "password cannot be longer than %d bytes", size);
3202 goto error;
3203 }
3204
3205 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3206 memcpy(buf, pw_info->password, pw_info->size);
3207 return pw_info->size;
3208
3209error:
3210 Py_XDECREF(fn_ret);
3211 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3212 pw_info->error = 1;
3213 return -1;
3214}
3215
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003216/*[clinic input]
3217_ssl._SSLContext.load_cert_chain
3218 certfile: object
3219 keyfile: object = NULL
3220 password: object = NULL
3221
3222[clinic start generated code]*/
3223
Antoine Pitroub5218772010-05-21 09:56:06 +00003224static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003225_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3226 PyObject *keyfile, PyObject *password)
3227/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003228{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003229 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003230 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3231 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003232 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003233 int r;
3234
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003235 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003236 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003237 if (keyfile == Py_None)
3238 keyfile = NULL;
3239 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3240 PyErr_SetString(PyExc_TypeError,
3241 "certfile should be a valid filesystem path");
3242 return NULL;
3243 }
3244 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3245 PyErr_SetString(PyExc_TypeError,
3246 "keyfile should be a valid filesystem path");
3247 goto error;
3248 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003249 if (password && password != Py_None) {
3250 if (PyCallable_Check(password)) {
3251 pw_info.callable = password;
3252 } else if (!_pwinfo_set(&pw_info, password,
3253 "password should be a string or callable")) {
3254 goto error;
3255 }
3256 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3257 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3258 }
3259 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003260 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3261 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003262 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003263 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003264 if (pw_info.error) {
3265 ERR_clear_error();
3266 /* the password callback has already set the error information */
3267 }
3268 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003269 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003270 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003271 }
3272 else {
3273 _setSSLError(NULL, 0, __FILE__, __LINE__);
3274 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003275 goto error;
3276 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003277 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003278 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003279 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3280 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003281 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3282 Py_CLEAR(keyfile_bytes);
3283 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003284 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003285 if (pw_info.error) {
3286 ERR_clear_error();
3287 /* the password callback has already set the error information */
3288 }
3289 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003290 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003291 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003292 }
3293 else {
3294 _setSSLError(NULL, 0, __FILE__, __LINE__);
3295 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003296 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003297 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003298 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003299 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003300 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003301 if (r != 1) {
3302 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003303 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003304 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003305 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3306 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003307 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003308 Py_RETURN_NONE;
3309
3310error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003311 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3312 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003313 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003314 Py_XDECREF(keyfile_bytes);
3315 Py_XDECREF(certfile_bytes);
3316 return NULL;
3317}
3318
Christian Heimesefff7062013-11-21 03:35:02 +01003319/* internal helper function, returns -1 on error
3320 */
3321static int
3322_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3323 int filetype)
3324{
3325 BIO *biobuf = NULL;
3326 X509_STORE *store;
3327 int retval = 0, err, loaded = 0;
3328
3329 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3330
3331 if (len <= 0) {
3332 PyErr_SetString(PyExc_ValueError,
3333 "Empty certificate data");
3334 return -1;
3335 } else if (len > INT_MAX) {
3336 PyErr_SetString(PyExc_OverflowError,
3337 "Certificate data is too long.");
3338 return -1;
3339 }
3340
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003341 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003342 if (biobuf == NULL) {
3343 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3344 return -1;
3345 }
3346
3347 store = SSL_CTX_get_cert_store(self->ctx);
3348 assert(store != NULL);
3349
3350 while (1) {
3351 X509 *cert = NULL;
3352 int r;
3353
3354 if (filetype == SSL_FILETYPE_ASN1) {
3355 cert = d2i_X509_bio(biobuf, NULL);
3356 } else {
3357 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003358 SSL_CTX_get_default_passwd_cb(self->ctx),
3359 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3360 );
Christian Heimesefff7062013-11-21 03:35:02 +01003361 }
3362 if (cert == NULL) {
3363 break;
3364 }
3365 r = X509_STORE_add_cert(store, cert);
3366 X509_free(cert);
3367 if (!r) {
3368 err = ERR_peek_last_error();
3369 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3370 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3371 /* cert already in hash table, not an error */
3372 ERR_clear_error();
3373 } else {
3374 break;
3375 }
3376 }
3377 loaded++;
3378 }
3379
3380 err = ERR_peek_last_error();
3381 if ((filetype == SSL_FILETYPE_ASN1) &&
3382 (loaded > 0) &&
3383 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3384 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3385 /* EOF ASN1 file, not an error */
3386 ERR_clear_error();
3387 retval = 0;
3388 } else if ((filetype == SSL_FILETYPE_PEM) &&
3389 (loaded > 0) &&
3390 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3391 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3392 /* EOF PEM file, not an error */
3393 ERR_clear_error();
3394 retval = 0;
3395 } else {
3396 _setSSLError(NULL, 0, __FILE__, __LINE__);
3397 retval = -1;
3398 }
3399
3400 BIO_free(biobuf);
3401 return retval;
3402}
3403
3404
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003405/*[clinic input]
3406_ssl._SSLContext.load_verify_locations
3407 cafile: object = NULL
3408 capath: object = NULL
3409 cadata: object = NULL
3410
3411[clinic start generated code]*/
3412
Antoine Pitrou152efa22010-05-16 18:19:27 +00003413static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003414_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3415 PyObject *cafile,
3416 PyObject *capath,
3417 PyObject *cadata)
3418/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003419{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003420 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3421 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003422 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003423
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003424 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003425 if (cafile == Py_None)
3426 cafile = NULL;
3427 if (capath == Py_None)
3428 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003429 if (cadata == Py_None)
3430 cadata = NULL;
3431
3432 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003433 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003434 "cafile, capath and cadata cannot be all omitted");
3435 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003436 }
3437 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3438 PyErr_SetString(PyExc_TypeError,
3439 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003440 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003441 }
3442 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003443 PyErr_SetString(PyExc_TypeError,
3444 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003445 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003446 }
Christian Heimesefff7062013-11-21 03:35:02 +01003447
3448 /* validata cadata type and load cadata */
3449 if (cadata) {
3450 Py_buffer buf;
3451 PyObject *cadata_ascii = NULL;
3452
3453 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3454 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3455 PyBuffer_Release(&buf);
3456 PyErr_SetString(PyExc_TypeError,
3457 "cadata should be a contiguous buffer with "
3458 "a single dimension");
3459 goto error;
3460 }
3461 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3462 PyBuffer_Release(&buf);
3463 if (r == -1) {
3464 goto error;
3465 }
3466 } else {
3467 PyErr_Clear();
3468 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3469 if (cadata_ascii == NULL) {
3470 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003471 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003472 "bytes-like object");
3473 goto error;
3474 }
3475 r = _add_ca_certs(self,
3476 PyBytes_AS_STRING(cadata_ascii),
3477 PyBytes_GET_SIZE(cadata_ascii),
3478 SSL_FILETYPE_PEM);
3479 Py_DECREF(cadata_ascii);
3480 if (r == -1) {
3481 goto error;
3482 }
3483 }
3484 }
3485
3486 /* load cafile or capath */
3487 if (cafile || capath) {
3488 if (cafile)
3489 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3490 if (capath)
3491 capath_buf = PyBytes_AS_STRING(capath_bytes);
3492 PySSL_BEGIN_ALLOW_THREADS
3493 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3494 PySSL_END_ALLOW_THREADS
3495 if (r != 1) {
3496 ok = 0;
3497 if (errno != 0) {
3498 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003499 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003500 }
3501 else {
3502 _setSSLError(NULL, 0, __FILE__, __LINE__);
3503 }
3504 goto error;
3505 }
3506 }
3507 goto end;
3508
3509 error:
3510 ok = 0;
3511 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003512 Py_XDECREF(cafile_bytes);
3513 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003514 if (ok) {
3515 Py_RETURN_NONE;
3516 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003517 return NULL;
3518 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003519}
3520
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003521/*[clinic input]
3522_ssl._SSLContext.load_dh_params
3523 path as filepath: object
3524 /
3525
3526[clinic start generated code]*/
3527
Antoine Pitrou152efa22010-05-16 18:19:27 +00003528static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003529_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3530/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003531{
3532 FILE *f;
3533 DH *dh;
3534
Victor Stinnerdaf45552013-08-28 00:53:59 +02003535 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003536 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003537 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003538
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003539 errno = 0;
3540 PySSL_BEGIN_ALLOW_THREADS
3541 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003542 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003543 PySSL_END_ALLOW_THREADS
3544 if (dh == NULL) {
3545 if (errno != 0) {
3546 ERR_clear_error();
3547 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3548 }
3549 else {
3550 _setSSLError(NULL, 0, __FILE__, __LINE__);
3551 }
3552 return NULL;
3553 }
3554 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3555 _setSSLError(NULL, 0, __FILE__, __LINE__);
3556 DH_free(dh);
3557 Py_RETURN_NONE;
3558}
3559
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003560/*[clinic input]
3561_ssl._SSLContext._wrap_socket
3562 sock: object(subclass_of="PySocketModule.Sock_Type")
3563 server_side: int
3564 server_hostname as hostname_obj: object = None
3565
3566[clinic start generated code]*/
3567
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003568static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003569_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3570 int server_side, PyObject *hostname_obj)
3571/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003572{
Antoine Pitroud5323212010-10-22 18:19:07 +00003573 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003574 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003575
Antoine Pitroud5323212010-10-22 18:19:07 +00003576 /* server_hostname is either None (or absent), or to be encoded
3577 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003578 if (hostname_obj != Py_None) {
3579 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003580 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003581 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003582
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003583 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3584 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003585 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003586 if (hostname != NULL)
3587 PyMem_Free(hostname);
3588 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003589}
3590
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003591/*[clinic input]
3592_ssl._SSLContext._wrap_bio
3593 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3594 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3595 server_side: int
3596 server_hostname as hostname_obj: object = None
3597
3598[clinic start generated code]*/
3599
Antoine Pitroub0182c82010-10-12 20:09:02 +00003600static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003601_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3602 PySSLMemoryBIO *outgoing, int server_side,
3603 PyObject *hostname_obj)
3604/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003605{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003606 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003607 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003608
3609 /* server_hostname is either None (or absent), or to be encoded
3610 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003611 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003612 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3613 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003614 }
3615
3616 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3617 incoming, outgoing);
3618
3619 PyMem_Free(hostname);
3620 return res;
3621}
3622
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003623/*[clinic input]
3624_ssl._SSLContext.session_stats
3625[clinic start generated code]*/
3626
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003627static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003628_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3629/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003630{
3631 int r;
3632 PyObject *value, *stats = PyDict_New();
3633 if (!stats)
3634 return NULL;
3635
3636#define ADD_STATS(SSL_NAME, KEY_NAME) \
3637 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3638 if (value == NULL) \
3639 goto error; \
3640 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3641 Py_DECREF(value); \
3642 if (r < 0) \
3643 goto error;
3644
3645 ADD_STATS(number, "number");
3646 ADD_STATS(connect, "connect");
3647 ADD_STATS(connect_good, "connect_good");
3648 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3649 ADD_STATS(accept, "accept");
3650 ADD_STATS(accept_good, "accept_good");
3651 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3652 ADD_STATS(accept, "accept");
3653 ADD_STATS(hits, "hits");
3654 ADD_STATS(misses, "misses");
3655 ADD_STATS(timeouts, "timeouts");
3656 ADD_STATS(cache_full, "cache_full");
3657
3658#undef ADD_STATS
3659
3660 return stats;
3661
3662error:
3663 Py_DECREF(stats);
3664 return NULL;
3665}
3666
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003667/*[clinic input]
3668_ssl._SSLContext.set_default_verify_paths
3669[clinic start generated code]*/
3670
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003671static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003672_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3673/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003674{
3675 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3676 _setSSLError(NULL, 0, __FILE__, __LINE__);
3677 return NULL;
3678 }
3679 Py_RETURN_NONE;
3680}
3681
Antoine Pitrou501da612011-12-21 09:27:41 +01003682#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003683/*[clinic input]
3684_ssl._SSLContext.set_ecdh_curve
3685 name: object
3686 /
3687
3688[clinic start generated code]*/
3689
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003690static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003691_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3692/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003693{
3694 PyObject *name_bytes;
3695 int nid;
3696 EC_KEY *key;
3697
3698 if (!PyUnicode_FSConverter(name, &name_bytes))
3699 return NULL;
3700 assert(PyBytes_Check(name_bytes));
3701 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3702 Py_DECREF(name_bytes);
3703 if (nid == 0) {
3704 PyErr_Format(PyExc_ValueError,
3705 "unknown elliptic curve name %R", name);
3706 return NULL;
3707 }
3708 key = EC_KEY_new_by_curve_name(nid);
3709 if (key == NULL) {
3710 _setSSLError(NULL, 0, __FILE__, __LINE__);
3711 return NULL;
3712 }
3713 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3714 EC_KEY_free(key);
3715 Py_RETURN_NONE;
3716}
Antoine Pitrou501da612011-12-21 09:27:41 +01003717#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003718
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003719#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003720static int
3721_servername_callback(SSL *s, int *al, void *args)
3722{
3723 int ret;
3724 PySSLContext *ssl_ctx = (PySSLContext *) args;
3725 PySSLSocket *ssl;
3726 PyObject *servername_o;
3727 PyObject *servername_idna;
3728 PyObject *result;
3729 /* The high-level ssl.SSLSocket object */
3730 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003731 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003732#ifdef WITH_THREAD
3733 PyGILState_STATE gstate = PyGILState_Ensure();
3734#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003735
3736 if (ssl_ctx->set_hostname == NULL) {
3737 /* remove race condition in this the call back while if removing the
3738 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003739#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003740 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003741#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003742 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003743 }
3744
3745 ssl = SSL_get_app_data(s);
3746 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003747
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003748 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003749 * SSL connection and that has a .context attribute that can be changed to
3750 * identify the requested hostname. Since the official API is the Python
3751 * level API we want to pass the callback a Python level object rather than
3752 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3753 * SSLObject) that will be passed. Otherwise if there's a socket then that
3754 * will be passed. If both do not exist only then the C-level object is
3755 * passed. */
3756 if (ssl->owner)
3757 ssl_socket = PyWeakref_GetObject(ssl->owner);
3758 else if (ssl->Socket)
3759 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3760 else
3761 ssl_socket = (PyObject *) ssl;
3762
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003763 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003764 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003765 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003766
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003767 if (servername == NULL) {
3768 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3769 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003770 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003771 else {
3772 servername_o = PyBytes_FromString(servername);
3773 if (servername_o == NULL) {
3774 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3775 goto error;
3776 }
3777 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3778 if (servername_idna == NULL) {
3779 PyErr_WriteUnraisable(servername_o);
3780 Py_DECREF(servername_o);
3781 goto error;
3782 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003783 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003784 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3785 servername_idna, ssl_ctx, NULL);
3786 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003787 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003788 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003789
3790 if (result == NULL) {
3791 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3792 *al = SSL_AD_HANDSHAKE_FAILURE;
3793 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3794 }
3795 else {
3796 if (result != Py_None) {
3797 *al = (int) PyLong_AsLong(result);
3798 if (PyErr_Occurred()) {
3799 PyErr_WriteUnraisable(result);
3800 *al = SSL_AD_INTERNAL_ERROR;
3801 }
3802 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3803 }
3804 else {
3805 ret = SSL_TLSEXT_ERR_OK;
3806 }
3807 Py_DECREF(result);
3808 }
3809
Stefan Krah20d60802013-01-17 17:07:17 +01003810#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003811 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003812#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003813 return ret;
3814
3815error:
3816 Py_DECREF(ssl_socket);
3817 *al = SSL_AD_INTERNAL_ERROR;
3818 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003819#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003820 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003821#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003822 return ret;
3823}
Antoine Pitroua5963382013-03-30 16:39:00 +01003824#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003825
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003826/*[clinic input]
3827_ssl._SSLContext.set_servername_callback
3828 method as cb: object
3829 /
3830
3831Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3832
3833If the argument is None then the callback is disabled. The method is called
3834with the SSLSocket, the server name as a string, and the SSLContext object.
3835See RFC 6066 for details of the SNI extension.
3836[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003837
3838static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003839_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3840/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003841{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003842#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003843 Py_CLEAR(self->set_hostname);
3844 if (cb == Py_None) {
3845 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3846 }
3847 else {
3848 if (!PyCallable_Check(cb)) {
3849 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3850 PyErr_SetString(PyExc_TypeError,
3851 "not a callable object");
3852 return NULL;
3853 }
3854 Py_INCREF(cb);
3855 self->set_hostname = cb;
3856 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3857 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3858 }
3859 Py_RETURN_NONE;
3860#else
3861 PyErr_SetString(PyExc_NotImplementedError,
3862 "The TLS extension servername callback, "
3863 "SSL_CTX_set_tlsext_servername_callback, "
3864 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003865 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003866#endif
3867}
3868
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003869/*[clinic input]
3870_ssl._SSLContext.cert_store_stats
3871
3872Returns quantities of loaded X.509 certificates.
3873
3874X.509 certificates with a CA extension and certificate revocation lists
3875inside the context's cert store.
3876
3877NOTE: Certificates in a capath directory aren't loaded unless they have
3878been used at least once.
3879[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003880
3881static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003882_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3883/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003884{
3885 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003886 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003887 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003888 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003889
3890 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003891 objs = X509_STORE_get0_objects(store);
3892 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3893 obj = sk_X509_OBJECT_value(objs, i);
3894 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003895 case X509_LU_X509:
3896 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003897 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003898 ca++;
3899 }
3900 break;
3901 case X509_LU_CRL:
3902 crl++;
3903 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003904 default:
3905 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3906 * As far as I can tell they are internal states and never
3907 * stored in a cert store */
3908 break;
3909 }
3910 }
3911 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3912 "x509_ca", ca);
3913}
3914
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003915/*[clinic input]
3916_ssl._SSLContext.get_ca_certs
3917 binary_form: bool = False
3918
3919Returns a list of dicts with information of loaded CA certs.
3920
3921If the optional argument is True, returns a DER-encoded copy of the CA
3922certificate.
3923
3924NOTE: Certificates in a capath directory aren't loaded unless they have
3925been used at least once.
3926[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003927
3928static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003929_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3930/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003931{
3932 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003933 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003934 PyObject *ci = NULL, *rlist = NULL;
3935 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003936
3937 if ((rlist = PyList_New(0)) == NULL) {
3938 return NULL;
3939 }
3940
3941 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003942 objs = X509_STORE_get0_objects(store);
3943 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003944 X509_OBJECT *obj;
3945 X509 *cert;
3946
Christian Heimes598894f2016-09-05 23:19:05 +02003947 obj = sk_X509_OBJECT_value(objs, i);
3948 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003949 /* not a x509 cert */
3950 continue;
3951 }
3952 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003953 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003954 if (!X509_check_ca(cert)) {
3955 continue;
3956 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003957 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003958 ci = _certificate_to_der(cert);
3959 } else {
3960 ci = _decode_certificate(cert);
3961 }
3962 if (ci == NULL) {
3963 goto error;
3964 }
3965 if (PyList_Append(rlist, ci) == -1) {
3966 goto error;
3967 }
3968 Py_CLEAR(ci);
3969 }
3970 return rlist;
3971
3972 error:
3973 Py_XDECREF(ci);
3974 Py_XDECREF(rlist);
3975 return NULL;
3976}
3977
3978
Antoine Pitrou152efa22010-05-16 18:19:27 +00003979static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003980 {"check_hostname", (getter) get_check_hostname,
3981 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003982 {"options", (getter) get_options,
3983 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003984 {"verify_flags", (getter) get_verify_flags,
3985 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003986 {"verify_mode", (getter) get_verify_mode,
3987 (setter) set_verify_mode, NULL},
3988 {NULL}, /* sentinel */
3989};
3990
3991static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003992 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
3993 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
3994 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
3995 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
3996 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
3997 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
3998 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
3999 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4000 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4001 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4002 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4003 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4004 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4005 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004006 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004007 {NULL, NULL} /* sentinel */
4008};
4009
4010static PyTypeObject PySSLContext_Type = {
4011 PyVarObject_HEAD_INIT(NULL, 0)
4012 "_ssl._SSLContext", /*tp_name*/
4013 sizeof(PySSLContext), /*tp_basicsize*/
4014 0, /*tp_itemsize*/
4015 (destructor)context_dealloc, /*tp_dealloc*/
4016 0, /*tp_print*/
4017 0, /*tp_getattr*/
4018 0, /*tp_setattr*/
4019 0, /*tp_reserved*/
4020 0, /*tp_repr*/
4021 0, /*tp_as_number*/
4022 0, /*tp_as_sequence*/
4023 0, /*tp_as_mapping*/
4024 0, /*tp_hash*/
4025 0, /*tp_call*/
4026 0, /*tp_str*/
4027 0, /*tp_getattro*/
4028 0, /*tp_setattro*/
4029 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004030 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004031 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004032 (traverseproc) context_traverse, /*tp_traverse*/
4033 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004034 0, /*tp_richcompare*/
4035 0, /*tp_weaklistoffset*/
4036 0, /*tp_iter*/
4037 0, /*tp_iternext*/
4038 context_methods, /*tp_methods*/
4039 0, /*tp_members*/
4040 context_getsetlist, /*tp_getset*/
4041 0, /*tp_base*/
4042 0, /*tp_dict*/
4043 0, /*tp_descr_get*/
4044 0, /*tp_descr_set*/
4045 0, /*tp_dictoffset*/
4046 0, /*tp_init*/
4047 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004048 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004049};
4050
4051
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004052/*
4053 * MemoryBIO objects
4054 */
4055
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004056/*[clinic input]
4057@classmethod
4058_ssl.MemoryBIO.__new__
4059
4060[clinic start generated code]*/
4061
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004062static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004063_ssl_MemoryBIO_impl(PyTypeObject *type)
4064/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004065{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004066 BIO *bio;
4067 PySSLMemoryBIO *self;
4068
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004069 bio = BIO_new(BIO_s_mem());
4070 if (bio == NULL) {
4071 PyErr_SetString(PySSLErrorObject,
4072 "failed to allocate BIO");
4073 return NULL;
4074 }
4075 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4076 * just that no data is currently available. The SSL routines should retry
4077 * the read, which we can achieve by calling BIO_set_retry_read(). */
4078 BIO_set_retry_read(bio);
4079 BIO_set_mem_eof_return(bio, -1);
4080
4081 assert(type != NULL && type->tp_alloc != NULL);
4082 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4083 if (self == NULL) {
4084 BIO_free(bio);
4085 return NULL;
4086 }
4087 self->bio = bio;
4088 self->eof_written = 0;
4089
4090 return (PyObject *) self;
4091}
4092
4093static void
4094memory_bio_dealloc(PySSLMemoryBIO *self)
4095{
4096 BIO_free(self->bio);
4097 Py_TYPE(self)->tp_free(self);
4098}
4099
4100static PyObject *
4101memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4102{
4103 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
4104}
4105
4106PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4107"The number of bytes pending in the memory BIO.");
4108
4109static PyObject *
4110memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4111{
4112 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4113 && self->eof_written);
4114}
4115
4116PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4117"Whether the memory BIO is at EOF.");
4118
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004119/*[clinic input]
4120_ssl.MemoryBIO.read
4121 size as len: int = -1
4122 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004123
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004124Read up to size bytes from the memory BIO.
4125
4126If size is not specified, read the entire buffer.
4127If the return value is an empty bytes instance, this means either
4128EOF or that no data is available. Use the "eof" property to
4129distinguish between the two.
4130[clinic start generated code]*/
4131
4132static PyObject *
4133_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4134/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4135{
4136 int avail, nbytes;
4137 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004138
4139 avail = BIO_ctrl_pending(self->bio);
4140 if ((len < 0) || (len > avail))
4141 len = avail;
4142
4143 result = PyBytes_FromStringAndSize(NULL, len);
4144 if ((result == NULL) || (len == 0))
4145 return result;
4146
4147 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4148 /* There should never be any short reads but check anyway. */
4149 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4150 Py_DECREF(result);
4151 return NULL;
4152 }
4153
4154 return result;
4155}
4156
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004157/*[clinic input]
4158_ssl.MemoryBIO.write
4159 b: Py_buffer
4160 /
4161
4162Writes the bytes b into the memory BIO.
4163
4164Returns the number of bytes written.
4165[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004166
4167static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004168_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4169/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004170{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004171 int nbytes;
4172
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004173 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004174 PyErr_Format(PyExc_OverflowError,
4175 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004176 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004177 }
4178
4179 if (self->eof_written) {
4180 PyErr_SetString(PySSLErrorObject,
4181 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004182 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004183 }
4184
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004185 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004186 if (nbytes < 0) {
4187 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004188 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004189 }
4190
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004191 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004192}
4193
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004194/*[clinic input]
4195_ssl.MemoryBIO.write_eof
4196
4197Write an EOF marker to the memory BIO.
4198
4199When all data has been read, the "eof" property will be True.
4200[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004201
4202static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004203_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4204/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004205{
4206 self->eof_written = 1;
4207 /* After an EOF is written, a zero return from read() should be a real EOF
4208 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4209 BIO_clear_retry_flags(self->bio);
4210 BIO_set_mem_eof_return(self->bio, 0);
4211
4212 Py_RETURN_NONE;
4213}
4214
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004215static PyGetSetDef memory_bio_getsetlist[] = {
4216 {"pending", (getter) memory_bio_get_pending, NULL,
4217 PySSL_memory_bio_pending_doc},
4218 {"eof", (getter) memory_bio_get_eof, NULL,
4219 PySSL_memory_bio_eof_doc},
4220 {NULL}, /* sentinel */
4221};
4222
4223static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004224 _SSL_MEMORYBIO_READ_METHODDEF
4225 _SSL_MEMORYBIO_WRITE_METHODDEF
4226 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004227 {NULL, NULL} /* sentinel */
4228};
4229
4230static PyTypeObject PySSLMemoryBIO_Type = {
4231 PyVarObject_HEAD_INIT(NULL, 0)
4232 "_ssl.MemoryBIO", /*tp_name*/
4233 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4234 0, /*tp_itemsize*/
4235 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4236 0, /*tp_print*/
4237 0, /*tp_getattr*/
4238 0, /*tp_setattr*/
4239 0, /*tp_reserved*/
4240 0, /*tp_repr*/
4241 0, /*tp_as_number*/
4242 0, /*tp_as_sequence*/
4243 0, /*tp_as_mapping*/
4244 0, /*tp_hash*/
4245 0, /*tp_call*/
4246 0, /*tp_str*/
4247 0, /*tp_getattro*/
4248 0, /*tp_setattro*/
4249 0, /*tp_as_buffer*/
4250 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4251 0, /*tp_doc*/
4252 0, /*tp_traverse*/
4253 0, /*tp_clear*/
4254 0, /*tp_richcompare*/
4255 0, /*tp_weaklistoffset*/
4256 0, /*tp_iter*/
4257 0, /*tp_iternext*/
4258 memory_bio_methods, /*tp_methods*/
4259 0, /*tp_members*/
4260 memory_bio_getsetlist, /*tp_getset*/
4261 0, /*tp_base*/
4262 0, /*tp_dict*/
4263 0, /*tp_descr_get*/
4264 0, /*tp_descr_set*/
4265 0, /*tp_dictoffset*/
4266 0, /*tp_init*/
4267 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004268 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004269};
4270
Antoine Pitrou152efa22010-05-16 18:19:27 +00004271
Christian Heimes99a65702016-09-10 23:44:53 +02004272/*
4273 * SSL Session object
4274 */
4275
4276static void
4277PySSLSession_dealloc(PySSLSession *self)
4278{
Christian Heimesa5d07652016-09-24 10:48:05 +02004279 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004280 Py_XDECREF(self->ctx);
4281 if (self->session != NULL) {
4282 SSL_SESSION_free(self->session);
4283 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004284 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004285}
4286
4287static PyObject *
4288PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4289{
4290 int result;
4291
4292 if (left == NULL || right == NULL) {
4293 PyErr_BadInternalCall();
4294 return NULL;
4295 }
4296
4297 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4298 Py_RETURN_NOTIMPLEMENTED;
4299 }
4300
4301 if (left == right) {
4302 result = 0;
4303 } else {
4304 const unsigned char *left_id, *right_id;
4305 unsigned int left_len, right_len;
4306 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4307 &left_len);
4308 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4309 &right_len);
4310 if (left_len == right_len) {
4311 result = memcmp(left_id, right_id, left_len);
4312 } else {
4313 result = 1;
4314 }
4315 }
4316
4317 switch (op) {
4318 case Py_EQ:
4319 if (result == 0) {
4320 Py_RETURN_TRUE;
4321 } else {
4322 Py_RETURN_FALSE;
4323 }
4324 break;
4325 case Py_NE:
4326 if (result != 0) {
4327 Py_RETURN_TRUE;
4328 } else {
4329 Py_RETURN_FALSE;
4330 }
4331 break;
4332 case Py_LT:
4333 case Py_LE:
4334 case Py_GT:
4335 case Py_GE:
4336 Py_RETURN_NOTIMPLEMENTED;
4337 break;
4338 default:
4339 PyErr_BadArgument();
4340 return NULL;
4341 }
4342}
4343
4344static int
4345PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4346{
4347 Py_VISIT(self->ctx);
4348 return 0;
4349}
4350
4351static int
4352PySSLSession_clear(PySSLSession *self)
4353{
4354 Py_CLEAR(self->ctx);
4355 return 0;
4356}
4357
4358
4359static PyObject *
4360PySSLSession_get_time(PySSLSession *self, void *closure) {
4361 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4362}
4363
4364PyDoc_STRVAR(PySSLSession_get_time_doc,
4365"Session creation time (seconds since epoch).");
4366
4367
4368static PyObject *
4369PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4370 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4371}
4372
4373PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4374"Session timeout (delta in seconds).");
4375
4376
4377static PyObject *
4378PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4379 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4380 return PyLong_FromUnsignedLong(hint);
4381}
4382
4383PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4384"Ticket life time hint.");
4385
4386
4387static PyObject *
4388PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4389 const unsigned char *id;
4390 unsigned int len;
4391 id = SSL_SESSION_get_id(self->session, &len);
4392 return PyBytes_FromStringAndSize((const char *)id, len);
4393}
4394
4395PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4396"Session id");
4397
4398
4399static PyObject *
4400PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4401 if (SSL_SESSION_has_ticket(self->session)) {
4402 Py_RETURN_TRUE;
4403 } else {
4404 Py_RETURN_FALSE;
4405 }
4406}
4407
4408PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4409"Does the session contain a ticket?");
4410
4411
4412static PyGetSetDef PySSLSession_getsetlist[] = {
4413 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4414 PySSLSession_get_has_ticket_doc},
4415 {"id", (getter) PySSLSession_get_session_id, NULL,
4416 PySSLSession_get_session_id_doc},
4417 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4418 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4419 {"time", (getter) PySSLSession_get_time, NULL,
4420 PySSLSession_get_time_doc},
4421 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4422 PySSLSession_get_timeout_doc},
4423 {NULL}, /* sentinel */
4424};
4425
4426static PyTypeObject PySSLSession_Type = {
4427 PyVarObject_HEAD_INIT(NULL, 0)
4428 "_ssl.Session", /*tp_name*/
4429 sizeof(PySSLSession), /*tp_basicsize*/
4430 0, /*tp_itemsize*/
4431 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4432 0, /*tp_print*/
4433 0, /*tp_getattr*/
4434 0, /*tp_setattr*/
4435 0, /*tp_reserved*/
4436 0, /*tp_repr*/
4437 0, /*tp_as_number*/
4438 0, /*tp_as_sequence*/
4439 0, /*tp_as_mapping*/
4440 0, /*tp_hash*/
4441 0, /*tp_call*/
4442 0, /*tp_str*/
4443 0, /*tp_getattro*/
4444 0, /*tp_setattro*/
4445 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004446 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004447 0, /*tp_doc*/
4448 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4449 (inquiry)PySSLSession_clear, /*tp_clear*/
4450 PySSLSession_richcompare, /*tp_richcompare*/
4451 0, /*tp_weaklistoffset*/
4452 0, /*tp_iter*/
4453 0, /*tp_iternext*/
4454 0, /*tp_methods*/
4455 0, /*tp_members*/
4456 PySSLSession_getsetlist, /*tp_getset*/
4457};
4458
4459
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004460/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004461/*[clinic input]
4462_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004463 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004464 entropy: double
4465 /
4466
4467Mix string into the OpenSSL PRNG state.
4468
4469entropy (a float) is a lower bound on the entropy contained in
4470string. See RFC 1750.
4471[clinic start generated code]*/
4472
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004473static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004474_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
4475/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004476{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004477 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004478 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004479
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004480 buf = (const char *)view->buf;
4481 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004482 do {
4483 written = Py_MIN(len, INT_MAX);
4484 RAND_add(buf, (int)written, entropy);
4485 buf += written;
4486 len -= written;
4487 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004488 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004489}
4490
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004491static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004492PySSL_RAND(int len, int pseudo)
4493{
4494 int ok;
4495 PyObject *bytes;
4496 unsigned long err;
4497 const char *errstr;
4498 PyObject *v;
4499
Victor Stinner1e81a392013-12-19 16:47:04 +01004500 if (len < 0) {
4501 PyErr_SetString(PyExc_ValueError, "num must be positive");
4502 return NULL;
4503 }
4504
Victor Stinner99c8b162011-05-24 12:05:19 +02004505 bytes = PyBytes_FromStringAndSize(NULL, len);
4506 if (bytes == NULL)
4507 return NULL;
4508 if (pseudo) {
4509 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4510 if (ok == 0 || ok == 1)
4511 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4512 }
4513 else {
4514 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4515 if (ok == 1)
4516 return bytes;
4517 }
4518 Py_DECREF(bytes);
4519
4520 err = ERR_get_error();
4521 errstr = ERR_reason_error_string(err);
4522 v = Py_BuildValue("(ks)", err, errstr);
4523 if (v != NULL) {
4524 PyErr_SetObject(PySSLErrorObject, v);
4525 Py_DECREF(v);
4526 }
4527 return NULL;
4528}
4529
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004530/*[clinic input]
4531_ssl.RAND_bytes
4532 n: int
4533 /
4534
4535Generate n cryptographically strong pseudo-random bytes.
4536[clinic start generated code]*/
4537
Victor Stinner99c8b162011-05-24 12:05:19 +02004538static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004539_ssl_RAND_bytes_impl(PyObject *module, int n)
4540/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004541{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004542 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004543}
4544
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004545/*[clinic input]
4546_ssl.RAND_pseudo_bytes
4547 n: int
4548 /
4549
4550Generate n pseudo-random bytes.
4551
4552Return a pair (bytes, is_cryptographic). is_cryptographic is True
4553if the bytes generated are cryptographically strong.
4554[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004555
4556static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004557_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4558/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004559{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004560 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004561}
4562
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004563/*[clinic input]
4564_ssl.RAND_status
4565
4566Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4567
4568It is necessary to seed the PRNG with RAND_add() on some platforms before
4569using the ssl() function.
4570[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004571
4572static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004573_ssl_RAND_status_impl(PyObject *module)
4574/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004575{
Christian Heimes217cfd12007-12-02 14:31:20 +00004576 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004577}
4578
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004579#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004580/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004581/*[clinic input]
4582_ssl.RAND_egd
4583 path: object(converter="PyUnicode_FSConverter")
4584 /
4585
4586Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4587
4588Returns number of bytes read. Raises SSLError if connection to EGD
4589fails or if it does not provide enough data to seed PRNG.
4590[clinic start generated code]*/
4591
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004592static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004593_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4594/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004595{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004596 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004597 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004598 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004599 PyErr_SetString(PySSLErrorObject,
4600 "EGD connection failed or EGD did not return "
4601 "enough data to seed the PRNG");
4602 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004603 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004604 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004605}
Christian Heimesa5d07652016-09-24 10:48:05 +02004606/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004607#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004608
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004609
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004610
4611/*[clinic input]
4612_ssl.get_default_verify_paths
4613
4614Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4615
4616The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4617[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004618
4619static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004620_ssl_get_default_verify_paths_impl(PyObject *module)
4621/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004622{
4623 PyObject *ofile_env = NULL;
4624 PyObject *ofile = NULL;
4625 PyObject *odir_env = NULL;
4626 PyObject *odir = NULL;
4627
Benjamin Petersond113c962015-07-18 10:59:13 -07004628#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004629 const char *tmp = (info); \
4630 target = NULL; \
4631 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4632 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4633 target = PyBytes_FromString(tmp); } \
4634 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004635 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004636
Benjamin Petersond113c962015-07-18 10:59:13 -07004637 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4638 CONVERT(X509_get_default_cert_file(), ofile);
4639 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4640 CONVERT(X509_get_default_cert_dir(), odir);
4641#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004642
Christian Heimes200bb1b2013-06-14 15:14:29 +02004643 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004644
4645 error:
4646 Py_XDECREF(ofile_env);
4647 Py_XDECREF(ofile);
4648 Py_XDECREF(odir_env);
4649 Py_XDECREF(odir);
4650 return NULL;
4651}
4652
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004653static PyObject*
4654asn1obj2py(ASN1_OBJECT *obj)
4655{
4656 int nid;
4657 const char *ln, *sn;
4658 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004659 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004660
4661 nid = OBJ_obj2nid(obj);
4662 if (nid == NID_undef) {
4663 PyErr_Format(PyExc_ValueError, "Unknown object");
4664 return NULL;
4665 }
4666 sn = OBJ_nid2sn(nid);
4667 ln = OBJ_nid2ln(nid);
4668 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4669 if (buflen < 0) {
4670 _setSSLError(NULL, 0, __FILE__, __LINE__);
4671 return NULL;
4672 }
4673 if (buflen) {
4674 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4675 } else {
4676 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4677 }
4678}
4679
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004680/*[clinic input]
4681_ssl.txt2obj
4682 txt: str
4683 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004684
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004685Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4686
4687By default objects are looked up by OID. With name=True short and
4688long name are also matched.
4689[clinic start generated code]*/
4690
4691static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004692_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4693/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004694{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004695 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004696 ASN1_OBJECT *obj;
4697
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004698 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4699 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004700 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004701 return NULL;
4702 }
4703 result = asn1obj2py(obj);
4704 ASN1_OBJECT_free(obj);
4705 return result;
4706}
4707
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004708/*[clinic input]
4709_ssl.nid2obj
4710 nid: int
4711 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004712
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004713Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4714[clinic start generated code]*/
4715
4716static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004717_ssl_nid2obj_impl(PyObject *module, int nid)
4718/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004719{
4720 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004721 ASN1_OBJECT *obj;
4722
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004723 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004724 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004725 return NULL;
4726 }
4727 obj = OBJ_nid2obj(nid);
4728 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004729 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004730 return NULL;
4731 }
4732 result = asn1obj2py(obj);
4733 ASN1_OBJECT_free(obj);
4734 return result;
4735}
4736
Christian Heimes46bebee2013-06-09 19:03:31 +02004737#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004738
4739static PyObject*
4740certEncodingType(DWORD encodingType)
4741{
4742 static PyObject *x509_asn = NULL;
4743 static PyObject *pkcs_7_asn = NULL;
4744
4745 if (x509_asn == NULL) {
4746 x509_asn = PyUnicode_InternFromString("x509_asn");
4747 if (x509_asn == NULL)
4748 return NULL;
4749 }
4750 if (pkcs_7_asn == NULL) {
4751 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4752 if (pkcs_7_asn == NULL)
4753 return NULL;
4754 }
4755 switch(encodingType) {
4756 case X509_ASN_ENCODING:
4757 Py_INCREF(x509_asn);
4758 return x509_asn;
4759 case PKCS_7_ASN_ENCODING:
4760 Py_INCREF(pkcs_7_asn);
4761 return pkcs_7_asn;
4762 default:
4763 return PyLong_FromLong(encodingType);
4764 }
4765}
4766
4767static PyObject*
4768parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4769{
4770 CERT_ENHKEY_USAGE *usage;
4771 DWORD size, error, i;
4772 PyObject *retval;
4773
4774 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4775 error = GetLastError();
4776 if (error == CRYPT_E_NOT_FOUND) {
4777 Py_RETURN_TRUE;
4778 }
4779 return PyErr_SetFromWindowsErr(error);
4780 }
4781
4782 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4783 if (usage == NULL) {
4784 return PyErr_NoMemory();
4785 }
4786
4787 /* Now get the actual enhanced usage property */
4788 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4789 PyMem_Free(usage);
4790 error = GetLastError();
4791 if (error == CRYPT_E_NOT_FOUND) {
4792 Py_RETURN_TRUE;
4793 }
4794 return PyErr_SetFromWindowsErr(error);
4795 }
4796 retval = PySet_New(NULL);
4797 if (retval == NULL) {
4798 goto error;
4799 }
4800 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4801 if (usage->rgpszUsageIdentifier[i]) {
4802 PyObject *oid;
4803 int err;
4804 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4805 if (oid == NULL) {
4806 Py_CLEAR(retval);
4807 goto error;
4808 }
4809 err = PySet_Add(retval, oid);
4810 Py_DECREF(oid);
4811 if (err == -1) {
4812 Py_CLEAR(retval);
4813 goto error;
4814 }
4815 }
4816 }
4817 error:
4818 PyMem_Free(usage);
4819 return retval;
4820}
4821
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004822/*[clinic input]
4823_ssl.enum_certificates
4824 store_name: str
4825
4826Retrieve certificates from Windows' cert store.
4827
4828store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4829more cert storages, too. The function returns a list of (bytes,
4830encoding_type, trust) tuples. The encoding_type flag can be interpreted
4831with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4832a set of OIDs or the boolean True.
4833[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004834
Christian Heimes46bebee2013-06-09 19:03:31 +02004835static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004836_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4837/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004838{
Christian Heimes46bebee2013-06-09 19:03:31 +02004839 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004840 PCCERT_CONTEXT pCertCtx = NULL;
4841 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004842 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004843
Christian Heimes44109d72013-11-22 01:51:30 +01004844 result = PyList_New(0);
4845 if (result == NULL) {
4846 return NULL;
4847 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004848 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4849 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4850 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004851 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004852 Py_DECREF(result);
4853 return PyErr_SetFromWindowsErr(GetLastError());
4854 }
4855
Christian Heimes44109d72013-11-22 01:51:30 +01004856 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4857 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4858 pCertCtx->cbCertEncoded);
4859 if (!cert) {
4860 Py_CLEAR(result);
4861 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004862 }
Christian Heimes44109d72013-11-22 01:51:30 +01004863 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4864 Py_CLEAR(result);
4865 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004866 }
Christian Heimes44109d72013-11-22 01:51:30 +01004867 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4868 if (keyusage == Py_True) {
4869 Py_DECREF(keyusage);
4870 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004871 }
Christian Heimes44109d72013-11-22 01:51:30 +01004872 if (keyusage == NULL) {
4873 Py_CLEAR(result);
4874 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004875 }
Christian Heimes44109d72013-11-22 01:51:30 +01004876 if ((tup = PyTuple_New(3)) == NULL) {
4877 Py_CLEAR(result);
4878 break;
4879 }
4880 PyTuple_SET_ITEM(tup, 0, cert);
4881 cert = NULL;
4882 PyTuple_SET_ITEM(tup, 1, enc);
4883 enc = NULL;
4884 PyTuple_SET_ITEM(tup, 2, keyusage);
4885 keyusage = NULL;
4886 if (PyList_Append(result, tup) < 0) {
4887 Py_CLEAR(result);
4888 break;
4889 }
4890 Py_CLEAR(tup);
4891 }
4892 if (pCertCtx) {
4893 /* loop ended with an error, need to clean up context manually */
4894 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004895 }
4896
4897 /* In error cases cert, enc and tup may not be NULL */
4898 Py_XDECREF(cert);
4899 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004900 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004901 Py_XDECREF(tup);
4902
4903 if (!CertCloseStore(hStore, 0)) {
4904 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004905 Py_XDECREF(result);
4906 return PyErr_SetFromWindowsErr(GetLastError());
4907 }
4908 return result;
4909}
4910
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004911/*[clinic input]
4912_ssl.enum_crls
4913 store_name: str
4914
4915Retrieve CRLs from Windows' cert store.
4916
4917store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4918more cert storages, too. The function returns a list of (bytes,
4919encoding_type) tuples. The encoding_type flag can be interpreted with
4920X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4921[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004922
4923static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004924_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4925/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004926{
Christian Heimes44109d72013-11-22 01:51:30 +01004927 HCERTSTORE hStore = NULL;
4928 PCCRL_CONTEXT pCrlCtx = NULL;
4929 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4930 PyObject *result = NULL;
4931
Christian Heimes44109d72013-11-22 01:51:30 +01004932 result = PyList_New(0);
4933 if (result == NULL) {
4934 return NULL;
4935 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004936 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4937 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4938 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004939 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004940 Py_DECREF(result);
4941 return PyErr_SetFromWindowsErr(GetLastError());
4942 }
Christian Heimes44109d72013-11-22 01:51:30 +01004943
4944 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4945 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4946 pCrlCtx->cbCrlEncoded);
4947 if (!crl) {
4948 Py_CLEAR(result);
4949 break;
4950 }
4951 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4952 Py_CLEAR(result);
4953 break;
4954 }
4955 if ((tup = PyTuple_New(2)) == NULL) {
4956 Py_CLEAR(result);
4957 break;
4958 }
4959 PyTuple_SET_ITEM(tup, 0, crl);
4960 crl = NULL;
4961 PyTuple_SET_ITEM(tup, 1, enc);
4962 enc = NULL;
4963
4964 if (PyList_Append(result, tup) < 0) {
4965 Py_CLEAR(result);
4966 break;
4967 }
4968 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004969 }
Christian Heimes44109d72013-11-22 01:51:30 +01004970 if (pCrlCtx) {
4971 /* loop ended with an error, need to clean up context manually */
4972 CertFreeCRLContext(pCrlCtx);
4973 }
4974
4975 /* In error cases cert, enc and tup may not be NULL */
4976 Py_XDECREF(crl);
4977 Py_XDECREF(enc);
4978 Py_XDECREF(tup);
4979
4980 if (!CertCloseStore(hStore, 0)) {
4981 /* This error case might shadow another exception.*/
4982 Py_XDECREF(result);
4983 return PyErr_SetFromWindowsErr(GetLastError());
4984 }
4985 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004986}
Christian Heimes44109d72013-11-22 01:51:30 +01004987
4988#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004989
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004990/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004991static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004992 _SSL__TEST_DECODE_CERT_METHODDEF
4993 _SSL_RAND_ADD_METHODDEF
4994 _SSL_RAND_BYTES_METHODDEF
4995 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4996 _SSL_RAND_EGD_METHODDEF
4997 _SSL_RAND_STATUS_METHODDEF
4998 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
4999 _SSL_ENUM_CERTIFICATES_METHODDEF
5000 _SSL_ENUM_CRLS_METHODDEF
5001 _SSL_TXT2OBJ_METHODDEF
5002 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005003 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005004};
5005
5006
Christian Heimes598894f2016-09-05 23:19:05 +02005007#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005008
5009/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005010 * of the Python C thread library
5011 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5012 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005013
5014static PyThread_type_lock *_ssl_locks = NULL;
5015
Christian Heimes4d98ca92013-08-19 17:36:29 +02005016#if OPENSSL_VERSION_NUMBER >= 0x10000000
5017/* use new CRYPTO_THREADID API. */
5018static void
5019_ssl_threadid_callback(CRYPTO_THREADID *id)
5020{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005021 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005022}
5023#else
5024/* deprecated CRYPTO_set_id_callback() API. */
5025static unsigned long
5026_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005027 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005028}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005029#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005030
Bill Janssen6e027db2007-11-15 22:23:56 +00005031static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005032 (int mode, int n, const char *file, int line) {
5033 /* this function is needed to perform locking on shared data
5034 structures. (Note that OpenSSL uses a number of global data
5035 structures that will be implicitly shared whenever multiple
5036 threads use OpenSSL.) Multi-threaded applications will
5037 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005038
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005039 locking_function() must be able to handle up to
5040 CRYPTO_num_locks() different mutex locks. It sets the n-th
5041 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005042
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005043 file and line are the file number of the function setting the
5044 lock. They can be useful for debugging.
5045 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005046
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005047 if ((_ssl_locks == NULL) ||
5048 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5049 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005050
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005051 if (mode & CRYPTO_LOCK) {
5052 PyThread_acquire_lock(_ssl_locks[n], 1);
5053 } else {
5054 PyThread_release_lock(_ssl_locks[n]);
5055 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005056}
5057
5058static int _setup_ssl_threads(void) {
5059
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005060 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005061
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005062 if (_ssl_locks == NULL) {
5063 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005064 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5065 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005066 if (_ssl_locks == NULL) {
5067 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005068 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005069 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005070 for (i = 0; i < _ssl_locks_count; i++) {
5071 _ssl_locks[i] = PyThread_allocate_lock();
5072 if (_ssl_locks[i] == NULL) {
5073 unsigned int j;
5074 for (j = 0; j < i; j++) {
5075 PyThread_free_lock(_ssl_locks[j]);
5076 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005077 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005078 return 0;
5079 }
5080 }
5081 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005082#if OPENSSL_VERSION_NUMBER >= 0x10000000
5083 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5084#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005085 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005086#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005087 }
5088 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005089}
5090
Christian Heimes598894f2016-09-05 23:19:05 +02005091#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005092
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005093PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005094"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005095for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005096
Martin v. Löwis1a214512008-06-11 05:26:20 +00005097
5098static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005099 PyModuleDef_HEAD_INIT,
5100 "_ssl",
5101 module_doc,
5102 -1,
5103 PySSL_methods,
5104 NULL,
5105 NULL,
5106 NULL,
5107 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005108};
5109
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005110
5111static void
5112parse_openssl_version(unsigned long libver,
5113 unsigned int *major, unsigned int *minor,
5114 unsigned int *fix, unsigned int *patch,
5115 unsigned int *status)
5116{
5117 *status = libver & 0xF;
5118 libver >>= 4;
5119 *patch = libver & 0xFF;
5120 libver >>= 8;
5121 *fix = libver & 0xFF;
5122 libver >>= 8;
5123 *minor = libver & 0xFF;
5124 libver >>= 8;
5125 *major = libver & 0xFF;
5126}
5127
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005128PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005129PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005130{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005131 PyObject *m, *d, *r;
5132 unsigned long libver;
5133 unsigned int major, minor, fix, patch, status;
5134 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005135 struct py_ssl_error_code *errcode;
5136 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005137
Antoine Pitrou152efa22010-05-16 18:19:27 +00005138 if (PyType_Ready(&PySSLContext_Type) < 0)
5139 return NULL;
5140 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005141 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005142 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5143 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005144 if (PyType_Ready(&PySSLSession_Type) < 0)
5145 return NULL;
5146
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005147
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005148 m = PyModule_Create(&_sslmodule);
5149 if (m == NULL)
5150 return NULL;
5151 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005152
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005153 /* Load _socket module and its C API */
5154 socket_api = PySocketModule_ImportModuleAndAPI();
5155 if (!socket_api)
5156 return NULL;
5157 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005158
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005159 /* Init OpenSSL */
5160 SSL_load_error_strings();
5161 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005162#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02005163#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005164 /* note that this will start threading if not already started */
5165 if (!_setup_ssl_threads()) {
5166 return NULL;
5167 }
Christian Heimes598894f2016-09-05 23:19:05 +02005168#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5169 /* OpenSSL 1.1.0 builtin thread support is enabled */
5170 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005171#endif
Christian Heimes598894f2016-09-05 23:19:05 +02005172#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005173 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005174
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005175 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005176 sslerror_type_slots[0].pfunc = PyExc_OSError;
5177 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005178 if (PySSLErrorObject == NULL)
5179 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005180
Antoine Pitrou41032a62011-10-27 23:56:55 +02005181 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5182 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5183 PySSLErrorObject, NULL);
5184 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5185 "ssl.SSLWantReadError", SSLWantReadError_doc,
5186 PySSLErrorObject, NULL);
5187 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5188 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5189 PySSLErrorObject, NULL);
5190 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5191 "ssl.SSLSyscallError", SSLSyscallError_doc,
5192 PySSLErrorObject, NULL);
5193 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5194 "ssl.SSLEOFError", SSLEOFError_doc,
5195 PySSLErrorObject, NULL);
5196 if (PySSLZeroReturnErrorObject == NULL
5197 || PySSLWantReadErrorObject == NULL
5198 || PySSLWantWriteErrorObject == NULL
5199 || PySSLSyscallErrorObject == NULL
5200 || PySSLEOFErrorObject == NULL)
5201 return NULL;
5202 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5203 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5204 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5205 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5206 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5207 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005208 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005209 if (PyDict_SetItemString(d, "_SSLContext",
5210 (PyObject *)&PySSLContext_Type) != 0)
5211 return NULL;
5212 if (PyDict_SetItemString(d, "_SSLSocket",
5213 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005214 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005215 if (PyDict_SetItemString(d, "MemoryBIO",
5216 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5217 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005218 if (PyDict_SetItemString(d, "SSLSession",
5219 (PyObject *)&PySSLSession_Type) != 0)
5220 return NULL;
5221
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005222 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5223 PY_SSL_ERROR_ZERO_RETURN);
5224 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5225 PY_SSL_ERROR_WANT_READ);
5226 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5227 PY_SSL_ERROR_WANT_WRITE);
5228 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5229 PY_SSL_ERROR_WANT_X509_LOOKUP);
5230 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5231 PY_SSL_ERROR_SYSCALL);
5232 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5233 PY_SSL_ERROR_SSL);
5234 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5235 PY_SSL_ERROR_WANT_CONNECT);
5236 /* non ssl.h errorcodes */
5237 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5238 PY_SSL_ERROR_EOF);
5239 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5240 PY_SSL_ERROR_INVALID_ERROR_CODE);
5241 /* cert requirements */
5242 PyModule_AddIntConstant(m, "CERT_NONE",
5243 PY_SSL_CERT_NONE);
5244 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5245 PY_SSL_CERT_OPTIONAL);
5246 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5247 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005248 /* CRL verification for verification_flags */
5249 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5250 0);
5251 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5252 X509_V_FLAG_CRL_CHECK);
5253 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5254 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5255 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5256 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005257#ifdef X509_V_FLAG_TRUSTED_FIRST
5258 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5259 X509_V_FLAG_TRUSTED_FIRST);
5260#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005261
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005262 /* Alert Descriptions from ssl.h */
5263 /* note RESERVED constants no longer intended for use have been removed */
5264 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5265
5266#define ADD_AD_CONSTANT(s) \
5267 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5268 SSL_AD_##s)
5269
5270 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5271 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5272 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5273 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5274 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5275 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5276 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5277 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5278 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5279 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5280 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5281 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5282 ADD_AD_CONSTANT(UNKNOWN_CA);
5283 ADD_AD_CONSTANT(ACCESS_DENIED);
5284 ADD_AD_CONSTANT(DECODE_ERROR);
5285 ADD_AD_CONSTANT(DECRYPT_ERROR);
5286 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5287 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5288 ADD_AD_CONSTANT(INTERNAL_ERROR);
5289 ADD_AD_CONSTANT(USER_CANCELLED);
5290 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005291 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005292#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5293 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5294#endif
5295#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5296 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5297#endif
5298#ifdef SSL_AD_UNRECOGNIZED_NAME
5299 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5300#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005301#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5302 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5303#endif
5304#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5305 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5306#endif
5307#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5308 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5309#endif
5310
5311#undef ADD_AD_CONSTANT
5312
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005313 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005314#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005315 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5316 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005317#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005318#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005319 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5320 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005321#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005322 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005323 PY_SSL_VERSION_TLS);
5324 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5325 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005326 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5327 PY_SSL_VERSION_TLS_CLIENT);
5328 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5329 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005330 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5331 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005332#if HAVE_TLSv1_2
5333 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5334 PY_SSL_VERSION_TLS1_1);
5335 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5336 PY_SSL_VERSION_TLS1_2);
5337#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005338
Antoine Pitroub5218772010-05-21 09:56:06 +00005339 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005340 PyModule_AddIntConstant(m, "OP_ALL",
5341 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005342 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5343 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5344 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005345#if HAVE_TLSv1_2
5346 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5347 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5348#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005349 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5350 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005351 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005352 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005353#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005354 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005355#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005356#ifdef SSL_OP_NO_COMPRESSION
5357 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5358 SSL_OP_NO_COMPRESSION);
5359#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005360
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005361#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005362 r = Py_True;
5363#else
5364 r = Py_False;
5365#endif
5366 Py_INCREF(r);
5367 PyModule_AddObject(m, "HAS_SNI", r);
5368
Antoine Pitroud6494802011-07-21 01:11:30 +02005369 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005370 Py_INCREF(r);
5371 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5372
Antoine Pitrou501da612011-12-21 09:27:41 +01005373#ifdef OPENSSL_NO_ECDH
5374 r = Py_False;
5375#else
5376 r = Py_True;
5377#endif
5378 Py_INCREF(r);
5379 PyModule_AddObject(m, "HAS_ECDH", r);
5380
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005381#ifdef OPENSSL_NPN_NEGOTIATED
5382 r = Py_True;
5383#else
5384 r = Py_False;
5385#endif
5386 Py_INCREF(r);
5387 PyModule_AddObject(m, "HAS_NPN", r);
5388
Benjamin Petersoncca27322015-01-23 16:35:37 -05005389#ifdef HAVE_ALPN
5390 r = Py_True;
5391#else
5392 r = Py_False;
5393#endif
5394 Py_INCREF(r);
5395 PyModule_AddObject(m, "HAS_ALPN", r);
5396
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005397 /* Mappings for error codes */
5398 err_codes_to_names = PyDict_New();
5399 err_names_to_codes = PyDict_New();
5400 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5401 return NULL;
5402 errcode = error_codes;
5403 while (errcode->mnemonic != NULL) {
5404 PyObject *mnemo, *key;
5405 mnemo = PyUnicode_FromString(errcode->mnemonic);
5406 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5407 if (mnemo == NULL || key == NULL)
5408 return NULL;
5409 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5410 return NULL;
5411 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5412 return NULL;
5413 Py_DECREF(key);
5414 Py_DECREF(mnemo);
5415 errcode++;
5416 }
5417 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5418 return NULL;
5419 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5420 return NULL;
5421
5422 lib_codes_to_names = PyDict_New();
5423 if (lib_codes_to_names == NULL)
5424 return NULL;
5425 libcode = library_codes;
5426 while (libcode->library != NULL) {
5427 PyObject *mnemo, *key;
5428 key = PyLong_FromLong(libcode->code);
5429 mnemo = PyUnicode_FromString(libcode->library);
5430 if (key == NULL || mnemo == NULL)
5431 return NULL;
5432 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5433 return NULL;
5434 Py_DECREF(key);
5435 Py_DECREF(mnemo);
5436 libcode++;
5437 }
5438 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5439 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005440
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005441 /* OpenSSL version */
5442 /* SSLeay() gives us the version of the library linked against,
5443 which could be different from the headers version.
5444 */
5445 libver = SSLeay();
5446 r = PyLong_FromUnsignedLong(libver);
5447 if (r == NULL)
5448 return NULL;
5449 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5450 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005451 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005452 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5453 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5454 return NULL;
5455 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5456 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5457 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005458
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005459 libver = OPENSSL_VERSION_NUMBER;
5460 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5461 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5462 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5463 return NULL;
5464
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005465 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005466}