blob: b32d1c1756e16257e8df8e22451735e11705c0b4 [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
152static int COMP_get_type(const COMP_METHOD *meth)
153{
154 return meth->type;
155}
Christian Heimes598894f2016-09-05 23:19:05 +0200156#endif
157
158static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
159{
160 return ctx->default_passwd_callback;
161}
162
163static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
164{
165 return ctx->default_passwd_callback_userdata;
166}
167
168static int X509_OBJECT_get_type(X509_OBJECT *x)
169{
170 return x->type;
171}
172
173static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
174{
175 return x->data.x509;
176}
177
178static int BIO_up_ref(BIO *b)
179{
180 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
181 return 1;
182}
183
184static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
185 return store->objs;
186}
187
188static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
189{
190 return store->param;
191}
Christian Heimes99a65702016-09-10 23:44:53 +0200192
193static int
194SSL_SESSION_has_ticket(const SSL_SESSION *s)
195{
196 return (s->tlsext_ticklen > 0) ? 1 : 0;
197}
198
199static unsigned long
200SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
201{
202 return s->tlsext_tick_lifetime_hint;
203}
204
Christian Heimes598894f2016-09-05 23:19:05 +0200205#endif /* OpenSSL < 1.1.0 or LibreSSL */
206
207
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000208enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000209 /* these mirror ssl.h */
210 PY_SSL_ERROR_NONE,
211 PY_SSL_ERROR_SSL,
212 PY_SSL_ERROR_WANT_READ,
213 PY_SSL_ERROR_WANT_WRITE,
214 PY_SSL_ERROR_WANT_X509_LOOKUP,
215 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
216 PY_SSL_ERROR_ZERO_RETURN,
217 PY_SSL_ERROR_WANT_CONNECT,
218 /* start of non ssl.h errorcodes */
219 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
220 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
221 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000222};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000223
Thomas Woutersed03b412007-08-28 21:37:11 +0000224enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000225 PY_SSL_CLIENT,
226 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000227};
228
229enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000230 PY_SSL_CERT_NONE,
231 PY_SSL_CERT_OPTIONAL,
232 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000233};
234
235enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000236 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200237 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200238 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100239#if HAVE_TLSv1_2
240 PY_SSL_VERSION_TLS1,
241 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200242 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100243#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200244 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000245#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200246 PY_SSL_VERSION_TLS_CLIENT=0x10,
247 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100248};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200249
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000250#ifdef WITH_THREAD
251
252/* serves as a flag to see whether we've initialized the SSL thread support. */
253/* 0 means no, greater than 0 means yes */
254
255static unsigned int _ssl_locks_count = 0;
256
257#endif /* def WITH_THREAD */
258
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000259/* SSL socket object */
260
261#define X509_NAME_MAXLEN 256
262
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000263/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
264 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
265 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
266#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000267# define HAVE_SSL_CTX_CLEAR_OPTIONS
268#else
269# undef HAVE_SSL_CTX_CLEAR_OPTIONS
270#endif
271
Antoine Pitroud6494802011-07-21 01:11:30 +0200272/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
273 * older SSL, but let's be safe */
274#define PySSL_CB_MAXLEN 128
275
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100276
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000277typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000278 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000279 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100280#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -0500281 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100282 int npn_protocols_len;
283#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500284#ifdef HAVE_ALPN
285 unsigned char *alpn_protocols;
286 int alpn_protocols_len;
287#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100288#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200289 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100290#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100291 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000292} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000293
Antoine Pitrou152efa22010-05-16 18:19:27 +0000294typedef struct {
295 PyObject_HEAD
296 PyObject *Socket; /* weakref to socket on which we're layered */
297 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100298 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000299 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200300 char shutdown_seen_zero;
301 char handshake_done;
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->peer_cert = NULL;
597 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000598 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100599 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200600 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200601 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200602 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700603 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200604 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700605 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
606 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200607 if (hostname == NULL) {
608 Py_DECREF(self);
609 return NULL;
610 }
611 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700612 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200613
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100614 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000615
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000616 /* Make sure the SSL error state is initialized */
617 (void) ERR_get_state();
618 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000620 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000621 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000622 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200623 SSL_set_app_data(self->ssl, self);
624 if (sock) {
625 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
626 } else {
627 /* BIOs are reference counted and SSL_set_bio borrows our reference.
628 * To prevent a double free in memory_bio_dealloc() we need to take an
629 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200630 BIO_up_ref(inbio->bio);
631 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200632 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
633 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200634 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000635#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200636 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000637#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200638 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000639
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100640#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000641 if (server_hostname != NULL)
642 SSL_set_tlsext_host_name(self->ssl, server_hostname);
643#endif
644
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000645 /* If the socket is in non-blocking mode or timeout mode, set the BIO
646 * to non-blocking mode (blocking is the default)
647 */
Victor Stinnere2452312015-03-28 03:00:46 +0100648 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000649 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
650 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
651 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000652
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000653 PySSL_BEGIN_ALLOW_THREADS
654 if (socket_type == PY_SSL_CLIENT)
655 SSL_set_connect_state(self->ssl);
656 else
657 SSL_set_accept_state(self->ssl);
658 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000659
Antoine Pitroud6494802011-07-21 01:11:30 +0200660 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200661 if (sock != NULL) {
662 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
663 if (self->Socket == NULL) {
664 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200665 return NULL;
666 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100667 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000668 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000669}
670
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000671/* SSL object methods */
672
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300673/*[clinic input]
674_ssl._SSLSocket.do_handshake
675[clinic start generated code]*/
676
677static PyObject *
678_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
679/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000680{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000681 int ret;
682 int err;
683 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200684 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200685 _PyTime_t timeout, deadline = 0;
686 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000687
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200688 if (sock) {
689 if (((PyObject*)sock) == Py_None) {
690 _setSSLError("Underlying socket connection gone",
691 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
692 return NULL;
693 }
694 Py_INCREF(sock);
695
696 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100697 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200698 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
699 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000700 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000701
Victor Stinner14690702015-04-06 22:46:13 +0200702 timeout = GET_SOCKET_TIMEOUT(sock);
703 has_timeout = (timeout > 0);
704 if (has_timeout)
705 deadline = _PyTime_GetMonotonicClock() + timeout;
706
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 /* Actually negotiate SSL connection */
708 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000709 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000710 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000711 ret = SSL_do_handshake(self->ssl);
712 err = SSL_get_error(self->ssl, ret);
713 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200714
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000715 if (PyErr_CheckSignals())
716 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200717
Victor Stinner14690702015-04-06 22:46:13 +0200718 if (has_timeout)
719 timeout = deadline - _PyTime_GetMonotonicClock();
720
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000721 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200722 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200724 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000725 } else {
726 sockstate = SOCKET_OPERATION_OK;
727 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200728
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000729 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000730 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000731 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000732 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000733 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
734 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000735 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000736 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000737 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
738 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000739 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000740 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
742 break;
743 }
744 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200745 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000746 if (ret < 1)
747 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000748
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000749 if (self->peer_cert)
750 X509_free (self->peer_cert);
751 PySSL_BEGIN_ALLOW_THREADS
752 self->peer_cert = SSL_get_peer_certificate(self->ssl);
753 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200754 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000755
756 Py_INCREF(Py_None);
757 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000758
759error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200760 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000761 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000762}
763
Thomas Woutersed03b412007-08-28 21:37:11 +0000764static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000765_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000766
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000767 char namebuf[X509_NAME_MAXLEN];
768 int buflen;
769 PyObject *name_obj;
770 PyObject *value_obj;
771 PyObject *attr;
772 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000773
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
775 if (buflen < 0) {
776 _setSSLError(NULL, 0, __FILE__, __LINE__);
777 goto fail;
778 }
779 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
780 if (name_obj == NULL)
781 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000782
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
784 if (buflen < 0) {
785 _setSSLError(NULL, 0, __FILE__, __LINE__);
786 Py_DECREF(name_obj);
787 goto fail;
788 }
789 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000790 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000791 OPENSSL_free(valuebuf);
792 if (value_obj == NULL) {
793 Py_DECREF(name_obj);
794 goto fail;
795 }
796 attr = PyTuple_New(2);
797 if (attr == NULL) {
798 Py_DECREF(name_obj);
799 Py_DECREF(value_obj);
800 goto fail;
801 }
802 PyTuple_SET_ITEM(attr, 0, name_obj);
803 PyTuple_SET_ITEM(attr, 1, value_obj);
804 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000805
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000806 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000807 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000808}
809
810static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000812{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000813 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
814 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
815 PyObject *rdnt;
816 PyObject *attr = NULL; /* tuple to hold an attribute */
817 int entry_count = X509_NAME_entry_count(xname);
818 X509_NAME_ENTRY *entry;
819 ASN1_OBJECT *name;
820 ASN1_STRING *value;
821 int index_counter;
822 int rdn_level = -1;
823 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000824
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 dn = PyList_New(0);
826 if (dn == NULL)
827 return NULL;
828 /* now create another tuple to hold the top-level RDN */
829 rdn = PyList_New(0);
830 if (rdn == NULL)
831 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000832
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 for (index_counter = 0;
834 index_counter < entry_count;
835 index_counter++)
836 {
837 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000838
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000839 /* check to see if we've gotten to a new RDN */
840 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200841 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000842 /* yes, new RDN */
843 /* add old RDN to DN */
844 rdnt = PyList_AsTuple(rdn);
845 Py_DECREF(rdn);
846 if (rdnt == NULL)
847 goto fail0;
848 retcode = PyList_Append(dn, rdnt);
849 Py_DECREF(rdnt);
850 if (retcode < 0)
851 goto fail0;
852 /* create new RDN */
853 rdn = PyList_New(0);
854 if (rdn == NULL)
855 goto fail0;
856 }
857 }
Christian Heimes598894f2016-09-05 23:19:05 +0200858 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000859
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000860 /* now add this attribute to the current RDN */
861 name = X509_NAME_ENTRY_get_object(entry);
862 value = X509_NAME_ENTRY_get_data(entry);
863 attr = _create_tuple_for_attribute(name, value);
864 /*
865 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
866 entry->set,
867 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
868 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
869 */
870 if (attr == NULL)
871 goto fail1;
872 retcode = PyList_Append(rdn, attr);
873 Py_DECREF(attr);
874 if (retcode < 0)
875 goto fail1;
876 }
877 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100878 if (rdn != NULL) {
879 if (PyList_GET_SIZE(rdn) > 0) {
880 rdnt = PyList_AsTuple(rdn);
881 Py_DECREF(rdn);
882 if (rdnt == NULL)
883 goto fail0;
884 retcode = PyList_Append(dn, rdnt);
885 Py_DECREF(rdnt);
886 if (retcode < 0)
887 goto fail0;
888 }
889 else {
890 Py_DECREF(rdn);
891 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000892 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000893
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000894 /* convert list to tuple */
895 rdnt = PyList_AsTuple(dn);
896 Py_DECREF(dn);
897 if (rdnt == NULL)
898 return NULL;
899 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000900
901 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000903
904 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000905 Py_XDECREF(dn);
906 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000907}
908
909static PyObject *
910_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000911
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000912 /* this code follows the procedure outlined in
913 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
914 function to extract the STACK_OF(GENERAL_NAME),
915 then iterates through the stack to add the
916 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000917
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000918 int i, j;
919 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200920 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000921 X509_EXTENSION *ext = NULL;
922 GENERAL_NAMES *names = NULL;
923 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000924 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000925 BIO *biobuf = NULL;
926 char buf[2048];
927 char *vptr;
928 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000929 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000930
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 if (certificate == NULL)
932 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000933
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 /* get a memory buffer */
935 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000936
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200937 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 while ((i = X509_get_ext_by_NID(
939 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000940
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 if (peer_alt_names == Py_None) {
942 peer_alt_names = PyList_New(0);
943 if (peer_alt_names == NULL)
944 goto fail;
945 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000946
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000947 /* now decode the altName */
948 ext = X509_get_ext(certificate, i);
949 if(!(method = X509V3_EXT_get(ext))) {
950 PyErr_SetString
951 (PySSLErrorObject,
952 ERRSTR("No method for internalizing subjectAltName!"));
953 goto fail;
954 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000955
Christian Heimes598894f2016-09-05 23:19:05 +0200956 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 if (method->it)
958 names = (GENERAL_NAMES*)
959 (ASN1_item_d2i(NULL,
960 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200961 X509_EXTENSION_get_data(ext)->length,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000962 ASN1_ITEM_ptr(method->it)));
963 else
964 names = (GENERAL_NAMES*)
965 (method->d2i(NULL,
966 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200967 X509_EXTENSION_get_data(ext)->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000968
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000969 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200971 int gntype;
972 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000973
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200975 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200976 switch (gntype) {
977 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000978 /* we special-case DirName as a tuple of
979 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000980
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000981 t = PyTuple_New(2);
982 if (t == NULL) {
983 goto fail;
984 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000985
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000986 v = PyUnicode_FromString("DirName");
987 if (v == NULL) {
988 Py_DECREF(t);
989 goto fail;
990 }
991 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000992
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000993 v = _create_tuple_for_X509_NAME (name->d.dirn);
994 if (v == NULL) {
995 Py_DECREF(t);
996 goto fail;
997 }
998 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200999 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001000
Christian Heimes824f7f32013-08-17 00:54:47 +02001001 case GEN_EMAIL:
1002 case GEN_DNS:
1003 case GEN_URI:
1004 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1005 correctly, CVE-2013-4238 */
1006 t = PyTuple_New(2);
1007 if (t == NULL)
1008 goto fail;
1009 switch (gntype) {
1010 case GEN_EMAIL:
1011 v = PyUnicode_FromString("email");
1012 as = name->d.rfc822Name;
1013 break;
1014 case GEN_DNS:
1015 v = PyUnicode_FromString("DNS");
1016 as = name->d.dNSName;
1017 break;
1018 case GEN_URI:
1019 v = PyUnicode_FromString("URI");
1020 as = name->d.uniformResourceIdentifier;
1021 break;
1022 }
1023 if (v == NULL) {
1024 Py_DECREF(t);
1025 goto fail;
1026 }
1027 PyTuple_SET_ITEM(t, 0, v);
1028 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1029 ASN1_STRING_length(as));
1030 if (v == NULL) {
1031 Py_DECREF(t);
1032 goto fail;
1033 }
1034 PyTuple_SET_ITEM(t, 1, v);
1035 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001036
Christian Heimes1c03abd2016-09-06 23:25:35 +02001037 case GEN_RID:
1038 t = PyTuple_New(2);
1039 if (t == NULL)
1040 goto fail;
1041
1042 v = PyUnicode_FromString("Registered ID");
1043 if (v == NULL) {
1044 Py_DECREF(t);
1045 goto fail;
1046 }
1047 PyTuple_SET_ITEM(t, 0, v);
1048
1049 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1050 if (len < 0) {
1051 Py_DECREF(t);
1052 _setSSLError(NULL, 0, __FILE__, __LINE__);
1053 goto fail;
1054 } else if (len >= (int)sizeof(buf)) {
1055 v = PyUnicode_FromString("<INVALID>");
1056 } else {
1057 v = PyUnicode_FromStringAndSize(buf, len);
1058 }
1059 if (v == NULL) {
1060 Py_DECREF(t);
1061 goto fail;
1062 }
1063 PyTuple_SET_ITEM(t, 1, v);
1064 break;
1065
Christian Heimes824f7f32013-08-17 00:54:47 +02001066 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001067 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001068 switch (gntype) {
1069 /* check for new general name type */
1070 case GEN_OTHERNAME:
1071 case GEN_X400:
1072 case GEN_EDIPARTY:
1073 case GEN_IPADD:
1074 case GEN_RID:
1075 break;
1076 default:
1077 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1078 "Unknown general name type %d",
1079 gntype) == -1) {
1080 goto fail;
1081 }
1082 break;
1083 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001084 (void) BIO_reset(biobuf);
1085 GENERAL_NAME_print(biobuf, name);
1086 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1087 if (len < 0) {
1088 _setSSLError(NULL, 0, __FILE__, __LINE__);
1089 goto fail;
1090 }
1091 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001092 if (vptr == NULL) {
1093 PyErr_Format(PyExc_ValueError,
1094 "Invalid value %.200s",
1095 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001096 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001097 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001098 t = PyTuple_New(2);
1099 if (t == NULL)
1100 goto fail;
1101 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1102 if (v == NULL) {
1103 Py_DECREF(t);
1104 goto fail;
1105 }
1106 PyTuple_SET_ITEM(t, 0, v);
1107 v = PyUnicode_FromStringAndSize((vptr + 1),
1108 (len - (vptr - buf + 1)));
1109 if (v == NULL) {
1110 Py_DECREF(t);
1111 goto fail;
1112 }
1113 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001114 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001115 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001116
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001117 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001118
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001119 if (PyList_Append(peer_alt_names, t) < 0) {
1120 Py_DECREF(t);
1121 goto fail;
1122 }
1123 Py_DECREF(t);
1124 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001125 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001126 }
1127 BIO_free(biobuf);
1128 if (peer_alt_names != Py_None) {
1129 v = PyList_AsTuple(peer_alt_names);
1130 Py_DECREF(peer_alt_names);
1131 return v;
1132 } else {
1133 return peer_alt_names;
1134 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001135
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136
1137 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001138 if (biobuf != NULL)
1139 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001140
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001141 if (peer_alt_names != Py_None) {
1142 Py_XDECREF(peer_alt_names);
1143 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001144
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001146}
1147
1148static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001149_get_aia_uri(X509 *certificate, int nid) {
1150 PyObject *lst = NULL, *ostr = NULL;
1151 int i, result;
1152 AUTHORITY_INFO_ACCESS *info;
1153
1154 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001155 if (info == NULL)
1156 return Py_None;
1157 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1158 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001159 return Py_None;
1160 }
1161
1162 if ((lst = PyList_New(0)) == NULL) {
1163 goto fail;
1164 }
1165
1166 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1167 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1168 ASN1_IA5STRING *uri;
1169
1170 if ((OBJ_obj2nid(ad->method) != nid) ||
1171 (ad->location->type != GEN_URI)) {
1172 continue;
1173 }
1174 uri = ad->location->d.uniformResourceIdentifier;
1175 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1176 uri->length);
1177 if (ostr == NULL) {
1178 goto fail;
1179 }
1180 result = PyList_Append(lst, ostr);
1181 Py_DECREF(ostr);
1182 if (result < 0) {
1183 goto fail;
1184 }
1185 }
1186 AUTHORITY_INFO_ACCESS_free(info);
1187
1188 /* convert to tuple or None */
1189 if (PyList_Size(lst) == 0) {
1190 Py_DECREF(lst);
1191 return Py_None;
1192 } else {
1193 PyObject *tup;
1194 tup = PyList_AsTuple(lst);
1195 Py_DECREF(lst);
1196 return tup;
1197 }
1198
1199 fail:
1200 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001201 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001202 return NULL;
1203}
1204
1205static PyObject *
1206_get_crl_dp(X509 *certificate) {
1207 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001208 int i, j;
1209 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001210
Christian Heimes598894f2016-09-05 23:19:05 +02001211#if OPENSSL_VERSION_NUMBER >= 0x10001000L
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001212 /* Calls x509v3_cache_extensions and sets up crldp */
1213 X509_check_ca(certificate);
Christian Heimes949ec142013-11-21 16:26:51 +01001214#endif
Christian Heimes598894f2016-09-05 23:19:05 +02001215 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001216
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001217 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001218 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001219
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001220 lst = PyList_New(0);
1221 if (lst == NULL)
1222 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001223
1224 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1225 DIST_POINT *dp;
1226 STACK_OF(GENERAL_NAME) *gns;
1227
1228 dp = sk_DIST_POINT_value(dps, i);
1229 gns = dp->distpoint->name.fullname;
1230
1231 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1232 GENERAL_NAME *gn;
1233 ASN1_IA5STRING *uri;
1234 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001235 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001236
1237 gn = sk_GENERAL_NAME_value(gns, j);
1238 if (gn->type != GEN_URI) {
1239 continue;
1240 }
1241 uri = gn->d.uniformResourceIdentifier;
1242 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1243 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001244 if (ouri == NULL)
1245 goto done;
1246
1247 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001248 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001249 if (err < 0)
1250 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001251 }
1252 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001253
1254 /* Convert to tuple. */
1255 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1256
1257 done:
1258 Py_XDECREF(lst);
1259#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Peterson806fb252015-11-14 00:09:22 -08001260 sk_DIST_POINT_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001261#endif
1262 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001263}
1264
1265static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001266_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001267
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001268 PyObject *retval = NULL;
1269 BIO *biobuf = NULL;
1270 PyObject *peer;
1271 PyObject *peer_alt_names = NULL;
1272 PyObject *issuer;
1273 PyObject *version;
1274 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001275 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 ASN1_INTEGER *serialNumber;
1277 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001278 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001279 ASN1_TIME *notBefore, *notAfter;
1280 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001281
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001282 retval = PyDict_New();
1283 if (retval == NULL)
1284 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001285
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001286 peer = _create_tuple_for_X509_NAME(
1287 X509_get_subject_name(certificate));
1288 if (peer == NULL)
1289 goto fail0;
1290 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1291 Py_DECREF(peer);
1292 goto fail0;
1293 }
1294 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001295
Antoine Pitroufb046912010-11-09 20:21:19 +00001296 issuer = _create_tuple_for_X509_NAME(
1297 X509_get_issuer_name(certificate));
1298 if (issuer == NULL)
1299 goto fail0;
1300 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001301 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001302 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001303 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001304 Py_DECREF(issuer);
1305
1306 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001307 if (version == NULL)
1308 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001309 if (PyDict_SetItemString(retval, "version", version) < 0) {
1310 Py_DECREF(version);
1311 goto fail0;
1312 }
1313 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001314
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001315 /* get a memory buffer */
1316 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001317
Antoine Pitroufb046912010-11-09 20:21:19 +00001318 (void) BIO_reset(biobuf);
1319 serialNumber = X509_get_serialNumber(certificate);
1320 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1321 i2a_ASN1_INTEGER(biobuf, serialNumber);
1322 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1323 if (len < 0) {
1324 _setSSLError(NULL, 0, __FILE__, __LINE__);
1325 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001326 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001327 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1328 if (sn_obj == NULL)
1329 goto fail1;
1330 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1331 Py_DECREF(sn_obj);
1332 goto fail1;
1333 }
1334 Py_DECREF(sn_obj);
1335
1336 (void) BIO_reset(biobuf);
1337 notBefore = X509_get_notBefore(certificate);
1338 ASN1_TIME_print(biobuf, notBefore);
1339 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1340 if (len < 0) {
1341 _setSSLError(NULL, 0, __FILE__, __LINE__);
1342 goto fail1;
1343 }
1344 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1345 if (pnotBefore == NULL)
1346 goto fail1;
1347 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1348 Py_DECREF(pnotBefore);
1349 goto fail1;
1350 }
1351 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001352
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001353 (void) BIO_reset(biobuf);
1354 notAfter = X509_get_notAfter(certificate);
1355 ASN1_TIME_print(biobuf, notAfter);
1356 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1357 if (len < 0) {
1358 _setSSLError(NULL, 0, __FILE__, __LINE__);
1359 goto fail1;
1360 }
1361 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1362 if (pnotAfter == NULL)
1363 goto fail1;
1364 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1365 Py_DECREF(pnotAfter);
1366 goto fail1;
1367 }
1368 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001369
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001371
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001372 peer_alt_names = _get_peer_alt_names(certificate);
1373 if (peer_alt_names == NULL)
1374 goto fail1;
1375 else if (peer_alt_names != Py_None) {
1376 if (PyDict_SetItemString(retval, "subjectAltName",
1377 peer_alt_names) < 0) {
1378 Py_DECREF(peer_alt_names);
1379 goto fail1;
1380 }
1381 Py_DECREF(peer_alt_names);
1382 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001383
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001384 /* Authority Information Access: OCSP URIs */
1385 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1386 if (obj == NULL) {
1387 goto fail1;
1388 } else if (obj != Py_None) {
1389 result = PyDict_SetItemString(retval, "OCSP", obj);
1390 Py_DECREF(obj);
1391 if (result < 0) {
1392 goto fail1;
1393 }
1394 }
1395
1396 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1397 if (obj == NULL) {
1398 goto fail1;
1399 } else if (obj != Py_None) {
1400 result = PyDict_SetItemString(retval, "caIssuers", obj);
1401 Py_DECREF(obj);
1402 if (result < 0) {
1403 goto fail1;
1404 }
1405 }
1406
1407 /* CDP (CRL distribution points) */
1408 obj = _get_crl_dp(certificate);
1409 if (obj == NULL) {
1410 goto fail1;
1411 } else if (obj != Py_None) {
1412 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1413 Py_DECREF(obj);
1414 if (result < 0) {
1415 goto fail1;
1416 }
1417 }
1418
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001419 BIO_free(biobuf);
1420 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001421
1422 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001423 if (biobuf != NULL)
1424 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001425 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001426 Py_XDECREF(retval);
1427 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001428}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001429
Christian Heimes9a5395a2013-06-17 15:44:12 +02001430static PyObject *
1431_certificate_to_der(X509 *certificate)
1432{
1433 unsigned char *bytes_buf = NULL;
1434 int len;
1435 PyObject *retval;
1436
1437 bytes_buf = NULL;
1438 len = i2d_X509(certificate, &bytes_buf);
1439 if (len < 0) {
1440 _setSSLError(NULL, 0, __FILE__, __LINE__);
1441 return NULL;
1442 }
1443 /* this is actually an immutable bytes sequence */
1444 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1445 OPENSSL_free(bytes_buf);
1446 return retval;
1447}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001448
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001449/*[clinic input]
1450_ssl._test_decode_cert
1451 path: object(converter="PyUnicode_FSConverter")
1452 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001453
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001454[clinic start generated code]*/
1455
1456static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001457_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1458/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001459{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001460 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001461 X509 *x=NULL;
1462 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001463
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001464 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1465 PyErr_SetString(PySSLErrorObject,
1466 "Can't malloc memory to read file");
1467 goto fail0;
1468 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001469
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001470 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001471 PyErr_SetString(PySSLErrorObject,
1472 "Can't open file");
1473 goto fail0;
1474 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001475
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001476 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1477 if (x == NULL) {
1478 PyErr_SetString(PySSLErrorObject,
1479 "Error decoding PEM-encoded file");
1480 goto fail0;
1481 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001482
Antoine Pitroufb046912010-11-09 20:21:19 +00001483 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001484 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001485
1486 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001487 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001488 if (cert != NULL) BIO_free(cert);
1489 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001490}
1491
1492
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001493/*[clinic input]
1494_ssl._SSLSocket.peer_certificate
1495 der as binary_mode: bool = False
1496 /
1497
1498Returns the certificate for the peer.
1499
1500If no certificate was provided, returns None. If a certificate was
1501provided, but not validated, returns an empty dictionary. Otherwise
1502returns a dict containing information about the peer certificate.
1503
1504If the optional argument is True, returns a DER-encoded copy of the
1505peer certificate, or None if no certificate was provided. This will
1506return the certificate even if it wasn't validated.
1507[clinic start generated code]*/
1508
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001509static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001510_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1511/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001512{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001513 int verification;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001514
Antoine Pitrou20b85552013-09-29 19:50:53 +02001515 if (!self->handshake_done) {
1516 PyErr_SetString(PyExc_ValueError,
1517 "handshake not done yet");
1518 return NULL;
1519 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001520 if (!self->peer_cert)
1521 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001522
Antoine Pitrou721738f2012-08-15 23:20:39 +02001523 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001525 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001526 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001527 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 if ((verification & SSL_VERIFY_PEER) == 0)
1529 return PyDict_New();
1530 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001531 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001532 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001533}
1534
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001535static PyObject *
1536cipher_to_tuple(const SSL_CIPHER *cipher)
1537{
1538 const char *cipher_name, *cipher_protocol;
1539 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001540 if (retval == NULL)
1541 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001542
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001543 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001544 if (cipher_name == 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, 0, Py_None);
1547 } else {
1548 v = PyUnicode_FromString(cipher_name);
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, 0, v);
1552 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001553
1554 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001555 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001556 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001557 PyTuple_SET_ITEM(retval, 1, Py_None);
1558 } else {
1559 v = PyUnicode_FromString(cipher_protocol);
1560 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001561 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001562 PyTuple_SET_ITEM(retval, 1, v);
1563 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001564
1565 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001566 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001567 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001569
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001570 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001571
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001572 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001573 Py_DECREF(retval);
1574 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001575}
1576
Christian Heimes25bfcd52016-09-06 00:04:45 +02001577#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1578static PyObject *
1579cipher_to_dict(const SSL_CIPHER *cipher)
1580{
1581 const char *cipher_name, *cipher_protocol;
1582
1583 unsigned long cipher_id;
1584 int alg_bits, strength_bits, len;
1585 char buf[512] = {0};
1586#if OPENSSL_VERSION_1_1
1587 int aead, nid;
1588 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1589#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001590
1591 /* can be NULL */
1592 cipher_name = SSL_CIPHER_get_name(cipher);
1593 cipher_protocol = SSL_CIPHER_get_version(cipher);
1594 cipher_id = SSL_CIPHER_get_id(cipher);
1595 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1596 len = strlen(buf);
1597 if (len > 1 && buf[len-1] == '\n')
1598 buf[len-1] = '\0';
1599 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1600
1601#if OPENSSL_VERSION_1_1
1602 aead = SSL_CIPHER_is_aead(cipher);
1603 nid = SSL_CIPHER_get_cipher_nid(cipher);
1604 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1605 nid = SSL_CIPHER_get_digest_nid(cipher);
1606 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1607 nid = SSL_CIPHER_get_kx_nid(cipher);
1608 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1609 nid = SSL_CIPHER_get_auth_nid(cipher);
1610 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1611#endif
1612
Victor Stinner410b9882016-09-12 12:00:23 +02001613 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001614 "{sksssssssisi"
1615#if OPENSSL_VERSION_1_1
1616 "sOssssssss"
1617#endif
1618 "}",
1619 "id", cipher_id,
1620 "name", cipher_name,
1621 "protocol", cipher_protocol,
1622 "description", buf,
1623 "strength_bits", strength_bits,
1624 "alg_bits", alg_bits
1625#if OPENSSL_VERSION_1_1
1626 ,"aead", aead ? Py_True : Py_False,
1627 "symmetric", skcipher,
1628 "digest", digest,
1629 "kea", kx,
1630 "auth", auth
1631#endif
1632 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001633}
1634#endif
1635
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001636/*[clinic input]
1637_ssl._SSLSocket.shared_ciphers
1638[clinic start generated code]*/
1639
1640static PyObject *
1641_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1642/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001643{
1644 STACK_OF(SSL_CIPHER) *ciphers;
1645 int i;
1646 PyObject *res;
1647
Christian Heimes598894f2016-09-05 23:19:05 +02001648 ciphers = SSL_get_ciphers(self->ssl);
1649 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001650 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001651 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1652 if (!res)
1653 return NULL;
1654 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1655 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1656 if (!tup) {
1657 Py_DECREF(res);
1658 return NULL;
1659 }
1660 PyList_SET_ITEM(res, i, tup);
1661 }
1662 return res;
1663}
1664
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001665/*[clinic input]
1666_ssl._SSLSocket.cipher
1667[clinic start generated code]*/
1668
1669static PyObject *
1670_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1671/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001672{
1673 const SSL_CIPHER *current;
1674
1675 if (self->ssl == NULL)
1676 Py_RETURN_NONE;
1677 current = SSL_get_current_cipher(self->ssl);
1678 if (current == NULL)
1679 Py_RETURN_NONE;
1680 return cipher_to_tuple(current);
1681}
1682
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001683/*[clinic input]
1684_ssl._SSLSocket.version
1685[clinic start generated code]*/
1686
1687static PyObject *
1688_ssl__SSLSocket_version_impl(PySSLSocket *self)
1689/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001690{
1691 const char *version;
1692
1693 if (self->ssl == NULL)
1694 Py_RETURN_NONE;
1695 version = SSL_get_version(self->ssl);
1696 if (!strcmp(version, "unknown"))
1697 Py_RETURN_NONE;
1698 return PyUnicode_FromString(version);
1699}
1700
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001701#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001702/*[clinic input]
1703_ssl._SSLSocket.selected_npn_protocol
1704[clinic start generated code]*/
1705
1706static PyObject *
1707_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1708/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1709{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001710 const unsigned char *out;
1711 unsigned int outlen;
1712
Victor Stinner4569cd52013-06-23 14:58:43 +02001713 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001714 &out, &outlen);
1715
1716 if (out == NULL)
1717 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001718 return PyUnicode_FromStringAndSize((char *)out, outlen);
1719}
1720#endif
1721
1722#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001723/*[clinic input]
1724_ssl._SSLSocket.selected_alpn_protocol
1725[clinic start generated code]*/
1726
1727static PyObject *
1728_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1729/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1730{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001731 const unsigned char *out;
1732 unsigned int outlen;
1733
1734 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1735
1736 if (out == NULL)
1737 Py_RETURN_NONE;
1738 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001739}
1740#endif
1741
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001742/*[clinic input]
1743_ssl._SSLSocket.compression
1744[clinic start generated code]*/
1745
1746static PyObject *
1747_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1748/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1749{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001750#ifdef OPENSSL_NO_COMP
1751 Py_RETURN_NONE;
1752#else
1753 const COMP_METHOD *comp_method;
1754 const char *short_name;
1755
1756 if (self->ssl == NULL)
1757 Py_RETURN_NONE;
1758 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001759 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001760 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001761 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001762 if (short_name == NULL)
1763 Py_RETURN_NONE;
1764 return PyUnicode_DecodeFSDefault(short_name);
1765#endif
1766}
1767
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001768static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1769 Py_INCREF(self->ctx);
1770 return self->ctx;
1771}
1772
1773static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1774 void *closure) {
1775
1776 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001777#if !HAVE_SNI
1778 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1779 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001780 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001781#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001782 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001783 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001784 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001785#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001786 } else {
1787 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1788 return -1;
1789 }
1790
1791 return 0;
1792}
1793
1794PyDoc_STRVAR(PySSL_set_context_doc,
1795"_setter_context(ctx)\n\
1796\
1797This changes the context associated with the SSLSocket. This is typically\n\
1798used from within a callback function set by the set_servername_callback\n\
1799on the SSLContext to change the certificate information associated with the\n\
1800SSLSocket before the cryptographic exchange handshake messages\n");
1801
1802
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001803static PyObject *
1804PySSL_get_server_side(PySSLSocket *self, void *c)
1805{
1806 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1807}
1808
1809PyDoc_STRVAR(PySSL_get_server_side_doc,
1810"Whether this is a server-side socket.");
1811
1812static PyObject *
1813PySSL_get_server_hostname(PySSLSocket *self, void *c)
1814{
1815 if (self->server_hostname == NULL)
1816 Py_RETURN_NONE;
1817 Py_INCREF(self->server_hostname);
1818 return self->server_hostname;
1819}
1820
1821PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1822"The currently set server hostname (for SNI).");
1823
1824static PyObject *
1825PySSL_get_owner(PySSLSocket *self, void *c)
1826{
1827 PyObject *owner;
1828
1829 if (self->owner == NULL)
1830 Py_RETURN_NONE;
1831
1832 owner = PyWeakref_GetObject(self->owner);
1833 Py_INCREF(owner);
1834 return owner;
1835}
1836
1837static int
1838PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1839{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001840 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001841 if (self->owner == NULL)
1842 return -1;
1843 return 0;
1844}
1845
1846PyDoc_STRVAR(PySSL_get_owner_doc,
1847"The Python-level owner of this object.\
1848Passed as \"self\" in servername callback.");
1849
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001850
Antoine Pitrou152efa22010-05-16 18:19:27 +00001851static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001852{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001853 if (self->peer_cert) /* Possible not to have one? */
1854 X509_free (self->peer_cert);
1855 if (self->ssl)
1856 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001857 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001858 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001859 Py_XDECREF(self->server_hostname);
1860 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001861 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001862}
1863
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001864/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001865 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001866 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001867 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001868
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001869static int
Victor Stinner14690702015-04-06 22:46:13 +02001870PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001871{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001872 int rc;
1873#ifdef HAVE_POLL
1874 struct pollfd pollfd;
1875 _PyTime_t ms;
1876#else
1877 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001878 fd_set fds;
1879 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001880#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001881
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001882 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001883 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001884 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001885 else if (timeout < 0) {
1886 if (s->sock_timeout > 0)
1887 return SOCKET_HAS_TIMED_OUT;
1888 else
1889 return SOCKET_IS_BLOCKING;
1890 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001891
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001892 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001893 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001894 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001895
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001896 /* Prefer poll, if available, since you can poll() any fd
1897 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001898#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001899 pollfd.fd = s->sock_fd;
1900 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001901
Victor Stinner14690702015-04-06 22:46:13 +02001902 /* timeout is in seconds, poll() uses milliseconds */
1903 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001904 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001905
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001906 PySSL_BEGIN_ALLOW_THREADS
1907 rc = poll(&pollfd, 1, (int)ms);
1908 PySSL_END_ALLOW_THREADS
1909#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001910 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001911 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001912 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001913
Victor Stinner14690702015-04-06 22:46:13 +02001914 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001915
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001916 FD_ZERO(&fds);
1917 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001918
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001919 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001920 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001921 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001922 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001923 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001924 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001925 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001926 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001927#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001928
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001929 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1930 (when we are able to write or when there's something to read) */
1931 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001932}
1933
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001934/*[clinic input]
1935_ssl._SSLSocket.write
1936 b: Py_buffer
1937 /
1938
1939Writes the bytes-like object b into the SSL object.
1940
1941Returns the number of bytes written.
1942[clinic start generated code]*/
1943
1944static PyObject *
1945_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1946/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001947{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001948 int len;
1949 int sockstate;
1950 int err;
1951 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001952 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001953 _PyTime_t timeout, deadline = 0;
1954 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001955
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001956 if (sock != NULL) {
1957 if (((PyObject*)sock) == Py_None) {
1958 _setSSLError("Underlying socket connection gone",
1959 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1960 return NULL;
1961 }
1962 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001963 }
1964
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001965 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001966 PyErr_Format(PyExc_OverflowError,
1967 "string longer than %d bytes", INT_MAX);
1968 goto error;
1969 }
1970
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001971 if (sock != NULL) {
1972 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001973 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001974 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1975 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1976 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001977
Victor Stinner14690702015-04-06 22:46:13 +02001978 timeout = GET_SOCKET_TIMEOUT(sock);
1979 has_timeout = (timeout > 0);
1980 if (has_timeout)
1981 deadline = _PyTime_GetMonotonicClock() + timeout;
1982
1983 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001984 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001985 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001986 "The write operation timed out");
1987 goto error;
1988 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1989 PyErr_SetString(PySSLErrorObject,
1990 "Underlying socket has been closed.");
1991 goto error;
1992 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1993 PyErr_SetString(PySSLErrorObject,
1994 "Underlying socket too large for select().");
1995 goto error;
1996 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001997
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001998 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001999 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002000 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002001 err = SSL_get_error(self->ssl, len);
2002 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002003
2004 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002005 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002006
Victor Stinner14690702015-04-06 22:46:13 +02002007 if (has_timeout)
2008 timeout = deadline - _PyTime_GetMonotonicClock();
2009
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002010 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002011 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002012 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002013 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002014 } else {
2015 sockstate = SOCKET_OPERATION_OK;
2016 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002017
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002018 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002019 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002020 "The write operation timed out");
2021 goto error;
2022 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2023 PyErr_SetString(PySSLErrorObject,
2024 "Underlying socket has been closed.");
2025 goto error;
2026 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2027 break;
2028 }
2029 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002030
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002031 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002032 if (len > 0)
2033 return PyLong_FromLong(len);
2034 else
2035 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002036
2037error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002038 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002039 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002040}
2041
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002042/*[clinic input]
2043_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002044
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002045Returns the number of already decrypted bytes available for read, pending on the connection.
2046[clinic start generated code]*/
2047
2048static PyObject *
2049_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2050/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002051{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002052 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002053
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002054 PySSL_BEGIN_ALLOW_THREADS
2055 count = SSL_pending(self->ssl);
2056 PySSL_END_ALLOW_THREADS
2057 if (count < 0)
2058 return PySSL_SetError(self, count, __FILE__, __LINE__);
2059 else
2060 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002061}
2062
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002063/*[clinic input]
2064_ssl._SSLSocket.read
2065 size as len: int
2066 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002067 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002068 ]
2069 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002070
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002071Read up to size bytes from the SSL socket.
2072[clinic start generated code]*/
2073
2074static PyObject *
2075_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2076 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002077/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002078{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002079 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002080 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002081 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002082 int sockstate;
2083 int err;
2084 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002085 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002086 _PyTime_t timeout, deadline = 0;
2087 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002088
Martin Panter5503d472016-03-27 05:35:19 +00002089 if (!group_right_1 && len < 0) {
2090 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2091 return NULL;
2092 }
2093
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002094 if (sock != NULL) {
2095 if (((PyObject*)sock) == Py_None) {
2096 _setSSLError("Underlying socket connection gone",
2097 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2098 return NULL;
2099 }
2100 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002101 }
2102
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002103 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002104 dest = PyBytes_FromStringAndSize(NULL, len);
2105 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002106 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002107 if (len == 0) {
2108 Py_XDECREF(sock);
2109 return dest;
2110 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002111 mem = PyBytes_AS_STRING(dest);
2112 }
2113 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002114 mem = buffer->buf;
2115 if (len <= 0 || len > buffer->len) {
2116 len = (int) buffer->len;
2117 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002118 PyErr_SetString(PyExc_OverflowError,
2119 "maximum length can't fit in a C 'int'");
2120 goto error;
2121 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002122 if (len == 0) {
2123 count = 0;
2124 goto done;
2125 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002126 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002127 }
2128
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002129 if (sock != NULL) {
2130 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002131 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002132 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2133 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2134 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002135
Victor Stinner14690702015-04-06 22:46:13 +02002136 timeout = GET_SOCKET_TIMEOUT(sock);
2137 has_timeout = (timeout > 0);
2138 if (has_timeout)
2139 deadline = _PyTime_GetMonotonicClock() + timeout;
2140
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002141 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002142 PySSL_BEGIN_ALLOW_THREADS
2143 count = SSL_read(self->ssl, mem, len);
2144 err = SSL_get_error(self->ssl, count);
2145 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002146
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002147 if (PyErr_CheckSignals())
2148 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002149
Victor Stinner14690702015-04-06 22:46:13 +02002150 if (has_timeout)
2151 timeout = deadline - _PyTime_GetMonotonicClock();
2152
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002153 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002154 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002155 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002156 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002157 } else if (err == SSL_ERROR_ZERO_RETURN &&
2158 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002159 {
2160 count = 0;
2161 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002162 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002163 else
2164 sockstate = SOCKET_OPERATION_OK;
2165
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002166 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002167 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002168 "The read operation timed out");
2169 goto error;
2170 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2171 break;
2172 }
2173 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002174
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002175 if (count <= 0) {
2176 PySSL_SetError(self, count, __FILE__, __LINE__);
2177 goto error;
2178 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002179
2180done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002181 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002182 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002183 _PyBytes_Resize(&dest, count);
2184 return dest;
2185 }
2186 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002187 return PyLong_FromLong(count);
2188 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002189
2190error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002191 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002192 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002193 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002194 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002195}
2196
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002197/*[clinic input]
2198_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002199
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002200Does the SSL shutdown handshake with the remote end.
2201
2202Returns the underlying socket object.
2203[clinic start generated code]*/
2204
2205static PyObject *
2206_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2207/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002208{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002209 int err, ssl_err, sockstate, nonblocking;
2210 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002211 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002212 _PyTime_t timeout, deadline = 0;
2213 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002214
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002215 if (sock != NULL) {
2216 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002217 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002218 _setSSLError("Underlying socket connection gone",
2219 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2220 return NULL;
2221 }
2222 Py_INCREF(sock);
2223
2224 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002225 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002226 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2227 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002228 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002229
Victor Stinner14690702015-04-06 22:46:13 +02002230 timeout = GET_SOCKET_TIMEOUT(sock);
2231 has_timeout = (timeout > 0);
2232 if (has_timeout)
2233 deadline = _PyTime_GetMonotonicClock() + timeout;
2234
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002235 while (1) {
2236 PySSL_BEGIN_ALLOW_THREADS
2237 /* Disable read-ahead so that unwrap can work correctly.
2238 * Otherwise OpenSSL might read in too much data,
2239 * eating clear text data that happens to be
2240 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002241 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002242 * function is used and the shutdown_seen_zero != 0
2243 * condition is met.
2244 */
2245 if (self->shutdown_seen_zero)
2246 SSL_set_read_ahead(self->ssl, 0);
2247 err = SSL_shutdown(self->ssl);
2248 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002249
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002250 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2251 if (err > 0)
2252 break;
2253 if (err == 0) {
2254 /* Don't loop endlessly; instead preserve legacy
2255 behaviour of trying SSL_shutdown() only twice.
2256 This looks necessary for OpenSSL < 0.9.8m */
2257 if (++zeros > 1)
2258 break;
2259 /* Shutdown was sent, now try receiving */
2260 self->shutdown_seen_zero = 1;
2261 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002262 }
2263
Victor Stinner14690702015-04-06 22:46:13 +02002264 if (has_timeout)
2265 timeout = deadline - _PyTime_GetMonotonicClock();
2266
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002267 /* Possibly retry shutdown until timeout or failure */
2268 ssl_err = SSL_get_error(self->ssl, err);
2269 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002270 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002271 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002272 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002273 else
2274 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002275
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002276 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2277 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002278 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002279 "The read operation timed out");
2280 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002281 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002282 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002283 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002284 }
2285 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2286 PyErr_SetString(PySSLErrorObject,
2287 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002288 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002289 }
2290 else if (sockstate != SOCKET_OPERATION_OK)
2291 /* Retain the SSL error code */
2292 break;
2293 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002294
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002295 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002296 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002297 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002298 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002299 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002300 /* It's already INCREF'ed */
2301 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002302 else
2303 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002304
2305error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002306 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002307 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002308}
2309
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002310/*[clinic input]
2311_ssl._SSLSocket.tls_unique_cb
2312
2313Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2314
2315If the TLS handshake is not yet complete, None is returned.
2316[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002317
Antoine Pitroud6494802011-07-21 01:11:30 +02002318static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002319_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2320/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002321{
2322 PyObject *retval = NULL;
2323 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002324 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002325
2326 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2327 /* if session is resumed XOR we are the client */
2328 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2329 }
2330 else {
2331 /* if a new session XOR we are the server */
2332 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2333 }
2334
2335 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002336 if (len == 0)
2337 Py_RETURN_NONE;
2338
2339 retval = PyBytes_FromStringAndSize(buf, len);
2340
2341 return retval;
2342}
2343
Christian Heimes99a65702016-09-10 23:44:53 +02002344#ifdef OPENSSL_VERSION_1_1
2345
2346static SSL_SESSION*
2347_ssl_session_dup(SSL_SESSION *session) {
2348 SSL_SESSION *newsession = NULL;
2349 int slen;
2350 unsigned char *senc = NULL, *p;
2351 const unsigned char *const_p;
2352
2353 if (session == NULL) {
2354 PyErr_SetString(PyExc_ValueError, "Invalid session");
2355 goto error;
2356 }
2357
2358 /* get length */
2359 slen = i2d_SSL_SESSION(session, NULL);
2360 if (slen == 0 || slen > 0xFF00) {
2361 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2362 goto error;
2363 }
2364 if ((senc = PyMem_Malloc(slen)) == NULL) {
2365 PyErr_NoMemory();
2366 goto error;
2367 }
2368 p = senc;
2369 if (!i2d_SSL_SESSION(session, &p)) {
2370 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2371 goto error;
2372 }
2373 const_p = senc;
2374 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2375 if (session == NULL) {
2376 goto error;
2377 }
2378 PyMem_Free(senc);
2379 return newsession;
2380 error:
2381 if (senc != NULL) {
2382 PyMem_Free(senc);
2383 }
2384 return NULL;
2385}
2386#endif
2387
2388static PyObject *
2389PySSL_get_session(PySSLSocket *self, void *closure) {
2390 /* get_session can return sessions from a server-side connection,
2391 * it does not check for handshake done or client socket. */
2392 PySSLSession *pysess;
2393 SSL_SESSION *session;
2394
2395#ifdef OPENSSL_VERSION_1_1
2396 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2397 * https://github.com/openssl/openssl/issues/1550 */
2398 session = SSL_get0_session(self->ssl); /* borrowed reference */
2399 if (session == NULL) {
2400 Py_RETURN_NONE;
2401 }
2402 if ((session = _ssl_session_dup(session)) == NULL) {
2403 return NULL;
2404 }
2405#else
2406 session = SSL_get1_session(self->ssl);
2407 if (session == NULL) {
2408 Py_RETURN_NONE;
2409 }
2410#endif
2411
2412 pysess = PyObject_New(PySSLSession, &PySSLSession_Type);
2413 if (pysess == NULL) {
2414 SSL_SESSION_free(session);
2415 return NULL;
2416 }
2417
2418 assert(self->ctx);
2419 pysess->ctx = self->ctx;
2420 Py_INCREF(pysess->ctx);
2421 pysess->session = session;
2422 return (PyObject *)pysess;
2423}
2424
2425static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2426 void *closure)
2427 {
2428 PySSLSession *pysess;
2429#ifdef OPENSSL_VERSION_1_1
2430 SSL_SESSION *session;
2431#endif
2432 int result;
2433
2434 if (!PySSLSession_Check(value)) {
2435 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2436 return -1;
2437 }
2438 pysess = (PySSLSession *)value;
2439
2440 if (self->ctx->ctx != pysess->ctx->ctx) {
2441 PyErr_SetString(PyExc_ValueError,
2442 "Session refers to a different SSLContext.");
2443 return -1;
2444 }
2445 if (self->socket_type != PY_SSL_CLIENT) {
2446 PyErr_SetString(PyExc_ValueError,
2447 "Cannot set session for server-side SSLSocket.");
2448 return -1;
2449 }
2450 if (self->handshake_done) {
2451 PyErr_SetString(PyExc_ValueError,
2452 "Cannot set session after handshake.");
2453 return -1;
2454 }
2455#ifdef OPENSSL_VERSION_1_1
2456 /* duplicate session */
2457 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2458 return -1;
2459 }
2460 result = SSL_set_session(self->ssl, session);
2461 /* free duplicate, SSL_set_session() bumps ref count */
2462 SSL_SESSION_free(session);
2463#else
2464 result = SSL_set_session(self->ssl, pysess->session);
2465#endif
2466 if (result == 0) {
2467 _setSSLError(NULL, 0, __FILE__, __LINE__);
2468 return -1;
2469 }
2470 return 0;
2471}
2472
2473PyDoc_STRVAR(PySSL_set_session_doc,
2474"_setter_session(session)\n\
2475\
2476Get / set SSLSession.");
2477
2478static PyObject *
2479PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2480 if (SSL_session_reused(self->ssl)) {
2481 Py_RETURN_TRUE;
2482 } else {
2483 Py_RETURN_FALSE;
2484 }
2485}
2486
2487PyDoc_STRVAR(PySSL_get_session_reused_doc,
2488"Was the client session reused during handshake?");
2489
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002490static PyGetSetDef ssl_getsetlist[] = {
2491 {"context", (getter) PySSL_get_context,
2492 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002493 {"server_side", (getter) PySSL_get_server_side, NULL,
2494 PySSL_get_server_side_doc},
2495 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2496 PySSL_get_server_hostname_doc},
2497 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2498 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002499 {"session", (getter) PySSL_get_session,
2500 (setter) PySSL_set_session, PySSL_set_session_doc},
2501 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2502 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002503 {NULL}, /* sentinel */
2504};
2505
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002506static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002507 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2508 _SSL__SSLSOCKET_WRITE_METHODDEF
2509 _SSL__SSLSOCKET_READ_METHODDEF
2510 _SSL__SSLSOCKET_PENDING_METHODDEF
2511 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2512 _SSL__SSLSOCKET_CIPHER_METHODDEF
2513 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2514 _SSL__SSLSOCKET_VERSION_METHODDEF
2515 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2516 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2517 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2518 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2519 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002520 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002521};
2522
Antoine Pitrou152efa22010-05-16 18:19:27 +00002523static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002524 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002525 "_ssl._SSLSocket", /*tp_name*/
2526 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002527 0, /*tp_itemsize*/
2528 /* methods */
2529 (destructor)PySSL_dealloc, /*tp_dealloc*/
2530 0, /*tp_print*/
2531 0, /*tp_getattr*/
2532 0, /*tp_setattr*/
2533 0, /*tp_reserved*/
2534 0, /*tp_repr*/
2535 0, /*tp_as_number*/
2536 0, /*tp_as_sequence*/
2537 0, /*tp_as_mapping*/
2538 0, /*tp_hash*/
2539 0, /*tp_call*/
2540 0, /*tp_str*/
2541 0, /*tp_getattro*/
2542 0, /*tp_setattro*/
2543 0, /*tp_as_buffer*/
2544 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2545 0, /*tp_doc*/
2546 0, /*tp_traverse*/
2547 0, /*tp_clear*/
2548 0, /*tp_richcompare*/
2549 0, /*tp_weaklistoffset*/
2550 0, /*tp_iter*/
2551 0, /*tp_iternext*/
2552 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002553 0, /*tp_members*/
2554 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002555};
2556
Antoine Pitrou152efa22010-05-16 18:19:27 +00002557
2558/*
2559 * _SSLContext objects
2560 */
2561
Christian Heimes5fe668c2016-09-12 00:01:11 +02002562static int
2563_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2564{
2565 int mode;
2566 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2567
2568 switch(n) {
2569 case PY_SSL_CERT_NONE:
2570 mode = SSL_VERIFY_NONE;
2571 break;
2572 case PY_SSL_CERT_OPTIONAL:
2573 mode = SSL_VERIFY_PEER;
2574 break;
2575 case PY_SSL_CERT_REQUIRED:
2576 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2577 break;
2578 default:
2579 PyErr_SetString(PyExc_ValueError,
2580 "invalid value for verify_mode");
2581 return -1;
2582 }
2583 /* keep current verify cb */
2584 verify_cb = SSL_CTX_get_verify_callback(ctx);
2585 SSL_CTX_set_verify(ctx, mode, verify_cb);
2586 return 0;
2587}
2588
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002589/*[clinic input]
2590@classmethod
2591_ssl._SSLContext.__new__
2592 protocol as proto_version: int
2593 /
2594[clinic start generated code]*/
2595
Antoine Pitrou152efa22010-05-16 18:19:27 +00002596static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002597_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2598/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002599{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002600 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002601 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002602 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002603 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002604#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002605 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002606#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002607
Antoine Pitrou152efa22010-05-16 18:19:27 +00002608 PySSL_BEGIN_ALLOW_THREADS
2609 if (proto_version == PY_SSL_VERSION_TLS1)
2610 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002611#if HAVE_TLSv1_2
2612 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2613 ctx = SSL_CTX_new(TLSv1_1_method());
2614 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2615 ctx = SSL_CTX_new(TLSv1_2_method());
2616#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002617#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002618 else if (proto_version == PY_SSL_VERSION_SSL3)
2619 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002620#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002621#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002622 else if (proto_version == PY_SSL_VERSION_SSL2)
2623 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002624#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002625 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002626 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002627 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2628 ctx = SSL_CTX_new(TLS_client_method());
2629 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2630 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002631 else
2632 proto_version = -1;
2633 PySSL_END_ALLOW_THREADS
2634
2635 if (proto_version == -1) {
2636 PyErr_SetString(PyExc_ValueError,
2637 "invalid protocol version");
2638 return NULL;
2639 }
2640 if (ctx == NULL) {
2641 PyErr_SetString(PySSLErrorObject,
2642 "failed to allocate SSL context");
2643 return NULL;
2644 }
2645
2646 assert(type != NULL && type->tp_alloc != NULL);
2647 self = (PySSLContext *) type->tp_alloc(type, 0);
2648 if (self == NULL) {
2649 SSL_CTX_free(ctx);
2650 return NULL;
2651 }
2652 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002653#ifdef OPENSSL_NPN_NEGOTIATED
2654 self->npn_protocols = NULL;
2655#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002656#ifdef HAVE_ALPN
2657 self->alpn_protocols = NULL;
2658#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002659#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002660 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002661#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002662 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002663 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2664 self->check_hostname = 1;
2665 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2666 Py_DECREF(self);
2667 return NULL;
2668 }
2669 } else {
2670 self->check_hostname = 0;
2671 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2672 Py_DECREF(self);
2673 return NULL;
2674 }
2675 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002676 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002677 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2678 if (proto_version != PY_SSL_VERSION_SSL2)
2679 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002680 if (proto_version != PY_SSL_VERSION_SSL3)
2681 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002682 /* Minimal security flags for server and client side context.
2683 * Client sockets ignore server-side parameters. */
2684#ifdef SSL_OP_NO_COMPRESSION
2685 options |= SSL_OP_NO_COMPRESSION;
2686#endif
2687#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2688 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2689#endif
2690#ifdef SSL_OP_SINGLE_DH_USE
2691 options |= SSL_OP_SINGLE_DH_USE;
2692#endif
2693#ifdef SSL_OP_SINGLE_ECDH_USE
2694 options |= SSL_OP_SINGLE_ECDH_USE;
2695#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002696 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002697
Christian Heimes358cfd42016-09-10 22:43:48 +02002698 /* A bare minimum cipher list without completly broken cipher suites.
2699 * It's far from perfect but gives users a better head start. */
2700 if (proto_version != PY_SSL_VERSION_SSL2) {
2701 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2702 } else {
2703 /* SSLv2 needs MD5 */
2704 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2705 }
2706 if (result == 0) {
2707 Py_DECREF(self);
2708 ERR_clear_error();
2709 PyErr_SetString(PySSLErrorObject,
2710 "No cipher can be selected.");
2711 return NULL;
2712 }
2713
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002714#if defined(SSL_MODE_RELEASE_BUFFERS)
2715 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2716 usage for no cost at all. However, don't do this for OpenSSL versions
2717 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2718 2014-0198. I can't find exactly which beta fixed this CVE, so be
2719 conservative and assume it wasn't fixed until release. We do this check
2720 at runtime to avoid problems from the dynamic linker.
2721 See #25672 for more on this. */
2722 libver = SSLeay();
2723 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2724 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2725 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2726 }
2727#endif
2728
2729
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002730#ifndef OPENSSL_NO_ECDH
2731 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2732 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002733 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2734 */
2735#if defined(SSL_CTX_set_ecdh_auto) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002736 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2737#else
2738 {
2739 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2740 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2741 EC_KEY_free(key);
2742 }
2743#endif
2744#endif
2745
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002746#define SID_CTX "Python"
2747 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2748 sizeof(SID_CTX));
2749#undef SID_CTX
2750
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002751#ifdef X509_V_FLAG_TRUSTED_FIRST
2752 {
2753 /* Improve trust chain building when cross-signed intermediate
2754 certificates are present. See https://bugs.python.org/issue23476. */
2755 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2756 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2757 }
2758#endif
2759
Antoine Pitrou152efa22010-05-16 18:19:27 +00002760 return (PyObject *)self;
2761}
2762
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002763static int
2764context_traverse(PySSLContext *self, visitproc visit, void *arg)
2765{
2766#ifndef OPENSSL_NO_TLSEXT
2767 Py_VISIT(self->set_hostname);
2768#endif
2769 return 0;
2770}
2771
2772static int
2773context_clear(PySSLContext *self)
2774{
2775#ifndef OPENSSL_NO_TLSEXT
2776 Py_CLEAR(self->set_hostname);
2777#endif
2778 return 0;
2779}
2780
Antoine Pitrou152efa22010-05-16 18:19:27 +00002781static void
2782context_dealloc(PySSLContext *self)
2783{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002784 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002785 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002786#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002787 PyMem_FREE(self->npn_protocols);
2788#endif
2789#ifdef HAVE_ALPN
2790 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002791#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002792 Py_TYPE(self)->tp_free(self);
2793}
2794
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002795/*[clinic input]
2796_ssl._SSLContext.set_ciphers
2797 cipherlist: str
2798 /
2799[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002800
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002801static PyObject *
2802_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2803/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2804{
2805 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002806 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002807 /* Clearing the error queue is necessary on some OpenSSL versions,
2808 otherwise the error will be reported again when another SSL call
2809 is done. */
2810 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002811 PyErr_SetString(PySSLErrorObject,
2812 "No cipher can be selected.");
2813 return NULL;
2814 }
2815 Py_RETURN_NONE;
2816}
2817
Christian Heimes25bfcd52016-09-06 00:04:45 +02002818#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2819/*[clinic input]
2820_ssl._SSLContext.get_ciphers
2821[clinic start generated code]*/
2822
2823static PyObject *
2824_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2825/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2826{
2827 SSL *ssl = NULL;
2828 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002829 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002830 int i=0;
2831 PyObject *result = NULL, *dct;
2832
2833 ssl = SSL_new(self->ctx);
2834 if (ssl == NULL) {
2835 _setSSLError(NULL, 0, __FILE__, __LINE__);
2836 goto exit;
2837 }
2838 sk = SSL_get_ciphers(ssl);
2839
2840 result = PyList_New(sk_SSL_CIPHER_num(sk));
2841 if (result == NULL) {
2842 goto exit;
2843 }
2844
2845 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2846 cipher = sk_SSL_CIPHER_value(sk, i);
2847 dct = cipher_to_dict(cipher);
2848 if (dct == NULL) {
2849 Py_CLEAR(result);
2850 goto exit;
2851 }
2852 PyList_SET_ITEM(result, i, dct);
2853 }
2854
2855 exit:
2856 if (ssl != NULL)
2857 SSL_free(ssl);
2858 return result;
2859
2860}
2861#endif
2862
2863
Benjamin Petersonc54de472015-01-28 12:06:39 -05002864#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002865static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002866do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2867 const unsigned char *server_protocols, unsigned int server_protocols_len,
2868 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002869{
Benjamin Peterson88615022015-01-23 17:30:26 -05002870 int ret;
2871 if (client_protocols == NULL) {
2872 client_protocols = (unsigned char *)"";
2873 client_protocols_len = 0;
2874 }
2875 if (server_protocols == NULL) {
2876 server_protocols = (unsigned char *)"";
2877 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002878 }
2879
Benjamin Peterson88615022015-01-23 17:30:26 -05002880 ret = SSL_select_next_proto(out, outlen,
2881 server_protocols, server_protocols_len,
2882 client_protocols, client_protocols_len);
2883 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2884 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002885
2886 return SSL_TLSEXT_ERR_OK;
2887}
2888
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002889/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2890static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002891_advertiseNPN_cb(SSL *s,
2892 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002893 void *args)
2894{
2895 PySSLContext *ssl_ctx = (PySSLContext *) args;
2896
2897 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002898 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002899 *len = 0;
2900 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002901 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002902 *len = ssl_ctx->npn_protocols_len;
2903 }
2904
2905 return SSL_TLSEXT_ERR_OK;
2906}
2907/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2908static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002909_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002910 unsigned char **out, unsigned char *outlen,
2911 const unsigned char *server, unsigned int server_len,
2912 void *args)
2913{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002914 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002915 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002916 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002917}
2918#endif
2919
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002920/*[clinic input]
2921_ssl._SSLContext._set_npn_protocols
2922 protos: Py_buffer
2923 /
2924[clinic start generated code]*/
2925
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002926static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002927_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2928 Py_buffer *protos)
2929/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002930{
2931#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002932 PyMem_Free(self->npn_protocols);
2933 self->npn_protocols = PyMem_Malloc(protos->len);
2934 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002935 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002936 memcpy(self->npn_protocols, protos->buf, protos->len);
2937 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002938
2939 /* set both server and client callbacks, because the context can
2940 * be used to create both types of sockets */
2941 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2942 _advertiseNPN_cb,
2943 self);
2944 SSL_CTX_set_next_proto_select_cb(self->ctx,
2945 _selectNPN_cb,
2946 self);
2947
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002948 Py_RETURN_NONE;
2949#else
2950 PyErr_SetString(PyExc_NotImplementedError,
2951 "The NPN extension requires OpenSSL 1.0.1 or later.");
2952 return NULL;
2953#endif
2954}
2955
Benjamin Petersoncca27322015-01-23 16:35:37 -05002956#ifdef HAVE_ALPN
2957static int
2958_selectALPN_cb(SSL *s,
2959 const unsigned char **out, unsigned char *outlen,
2960 const unsigned char *client_protocols, unsigned int client_protocols_len,
2961 void *args)
2962{
2963 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002964 return do_protocol_selection(1, (unsigned char **)out, outlen,
2965 ctx->alpn_protocols, ctx->alpn_protocols_len,
2966 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002967}
2968#endif
2969
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002970/*[clinic input]
2971_ssl._SSLContext._set_alpn_protocols
2972 protos: Py_buffer
2973 /
2974[clinic start generated code]*/
2975
Benjamin Petersoncca27322015-01-23 16:35:37 -05002976static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002977_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2978 Py_buffer *protos)
2979/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002980{
2981#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002982 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002983 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002984 if (!self->alpn_protocols)
2985 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002986 memcpy(self->alpn_protocols, protos->buf, protos->len);
2987 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002988
2989 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2990 return PyErr_NoMemory();
2991 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2992
Benjamin Petersoncca27322015-01-23 16:35:37 -05002993 Py_RETURN_NONE;
2994#else
2995 PyErr_SetString(PyExc_NotImplementedError,
2996 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2997 return NULL;
2998#endif
2999}
3000
Antoine Pitrou152efa22010-05-16 18:19:27 +00003001static PyObject *
3002get_verify_mode(PySSLContext *self, void *c)
3003{
3004 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3005 case SSL_VERIFY_NONE:
3006 return PyLong_FromLong(PY_SSL_CERT_NONE);
3007 case SSL_VERIFY_PEER:
3008 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3009 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3010 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3011 }
3012 PyErr_SetString(PySSLErrorObject,
3013 "invalid return value from SSL_CTX_get_verify_mode");
3014 return NULL;
3015}
3016
3017static int
3018set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3019{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003020 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003021 if (!PyArg_Parse(arg, "i", &n))
3022 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003023 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003024 PyErr_SetString(PyExc_ValueError,
3025 "Cannot set verify_mode to CERT_NONE when "
3026 "check_hostname is enabled.");
3027 return -1;
3028 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003029 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003030}
3031
3032static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003033get_verify_flags(PySSLContext *self, 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 flags;
3038
3039 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003040 param = X509_STORE_get0_param(store);
3041 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003042 return PyLong_FromUnsignedLong(flags);
3043}
3044
3045static int
3046set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3047{
3048 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003049 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003050 unsigned long new_flags, flags, set, clear;
3051
3052 if (!PyArg_Parse(arg, "k", &new_flags))
3053 return -1;
3054 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003055 param = X509_STORE_get0_param(store);
3056 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003057 clear = flags & ~new_flags;
3058 set = ~flags & new_flags;
3059 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003060 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003061 _setSSLError(NULL, 0, __FILE__, __LINE__);
3062 return -1;
3063 }
3064 }
3065 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003066 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003067 _setSSLError(NULL, 0, __FILE__, __LINE__);
3068 return -1;
3069 }
3070 }
3071 return 0;
3072}
3073
3074static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003075get_options(PySSLContext *self, void *c)
3076{
3077 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3078}
3079
3080static int
3081set_options(PySSLContext *self, PyObject *arg, void *c)
3082{
3083 long new_opts, opts, set, clear;
3084 if (!PyArg_Parse(arg, "l", &new_opts))
3085 return -1;
3086 opts = SSL_CTX_get_options(self->ctx);
3087 clear = opts & ~new_opts;
3088 set = ~opts & new_opts;
3089 if (clear) {
3090#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3091 SSL_CTX_clear_options(self->ctx, clear);
3092#else
3093 PyErr_SetString(PyExc_ValueError,
3094 "can't clear options before OpenSSL 0.9.8m");
3095 return -1;
3096#endif
3097 }
3098 if (set)
3099 SSL_CTX_set_options(self->ctx, set);
3100 return 0;
3101}
3102
Christian Heimes1aa9a752013-12-02 02:41:19 +01003103static PyObject *
3104get_check_hostname(PySSLContext *self, void *c)
3105{
3106 return PyBool_FromLong(self->check_hostname);
3107}
3108
3109static int
3110set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3111{
3112 int check_hostname;
3113 if (!PyArg_Parse(arg, "p", &check_hostname))
3114 return -1;
3115 if (check_hostname &&
3116 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3117 PyErr_SetString(PyExc_ValueError,
3118 "check_hostname needs a SSL context with either "
3119 "CERT_OPTIONAL or CERT_REQUIRED");
3120 return -1;
3121 }
3122 self->check_hostname = check_hostname;
3123 return 0;
3124}
3125
3126
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003127typedef struct {
3128 PyThreadState *thread_state;
3129 PyObject *callable;
3130 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003131 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003132 int error;
3133} _PySSLPasswordInfo;
3134
3135static int
3136_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3137 const char *bad_type_error)
3138{
3139 /* Set the password and size fields of a _PySSLPasswordInfo struct
3140 from a unicode, bytes, or byte array object.
3141 The password field will be dynamically allocated and must be freed
3142 by the caller */
3143 PyObject *password_bytes = NULL;
3144 const char *data = NULL;
3145 Py_ssize_t size;
3146
3147 if (PyUnicode_Check(password)) {
3148 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3149 if (!password_bytes) {
3150 goto error;
3151 }
3152 data = PyBytes_AS_STRING(password_bytes);
3153 size = PyBytes_GET_SIZE(password_bytes);
3154 } else if (PyBytes_Check(password)) {
3155 data = PyBytes_AS_STRING(password);
3156 size = PyBytes_GET_SIZE(password);
3157 } else if (PyByteArray_Check(password)) {
3158 data = PyByteArray_AS_STRING(password);
3159 size = PyByteArray_GET_SIZE(password);
3160 } else {
3161 PyErr_SetString(PyExc_TypeError, bad_type_error);
3162 goto error;
3163 }
3164
Victor Stinner9ee02032013-06-23 15:08:23 +02003165 if (size > (Py_ssize_t)INT_MAX) {
3166 PyErr_Format(PyExc_ValueError,
3167 "password cannot be longer than %d bytes", INT_MAX);
3168 goto error;
3169 }
3170
Victor Stinner11ebff22013-07-07 17:07:52 +02003171 PyMem_Free(pw_info->password);
3172 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003173 if (!pw_info->password) {
3174 PyErr_SetString(PyExc_MemoryError,
3175 "unable to allocate password buffer");
3176 goto error;
3177 }
3178 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003179 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003180
3181 Py_XDECREF(password_bytes);
3182 return 1;
3183
3184error:
3185 Py_XDECREF(password_bytes);
3186 return 0;
3187}
3188
3189static int
3190_password_callback(char *buf, int size, int rwflag, void *userdata)
3191{
3192 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3193 PyObject *fn_ret = NULL;
3194
3195 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3196
3197 if (pw_info->callable) {
3198 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
3199 if (!fn_ret) {
3200 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3201 core python API, so we could use it to add a frame here */
3202 goto error;
3203 }
3204
3205 if (!_pwinfo_set(pw_info, fn_ret,
3206 "password callback must return a string")) {
3207 goto error;
3208 }
3209 Py_CLEAR(fn_ret);
3210 }
3211
3212 if (pw_info->size > size) {
3213 PyErr_Format(PyExc_ValueError,
3214 "password cannot be longer than %d bytes", size);
3215 goto error;
3216 }
3217
3218 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3219 memcpy(buf, pw_info->password, pw_info->size);
3220 return pw_info->size;
3221
3222error:
3223 Py_XDECREF(fn_ret);
3224 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3225 pw_info->error = 1;
3226 return -1;
3227}
3228
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003229/*[clinic input]
3230_ssl._SSLContext.load_cert_chain
3231 certfile: object
3232 keyfile: object = NULL
3233 password: object = NULL
3234
3235[clinic start generated code]*/
3236
Antoine Pitroub5218772010-05-21 09:56:06 +00003237static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003238_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3239 PyObject *keyfile, PyObject *password)
3240/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003241{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003242 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003243 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3244 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003245 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003246 int r;
3247
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003248 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003249 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003250 if (keyfile == Py_None)
3251 keyfile = NULL;
3252 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3253 PyErr_SetString(PyExc_TypeError,
3254 "certfile should be a valid filesystem path");
3255 return NULL;
3256 }
3257 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3258 PyErr_SetString(PyExc_TypeError,
3259 "keyfile should be a valid filesystem path");
3260 goto error;
3261 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003262 if (password && password != Py_None) {
3263 if (PyCallable_Check(password)) {
3264 pw_info.callable = password;
3265 } else if (!_pwinfo_set(&pw_info, password,
3266 "password should be a string or callable")) {
3267 goto error;
3268 }
3269 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3270 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3271 }
3272 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003273 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3274 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003275 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003276 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003277 if (pw_info.error) {
3278 ERR_clear_error();
3279 /* the password callback has already set the error information */
3280 }
3281 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003282 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003283 PyErr_SetFromErrno(PyExc_IOError);
3284 }
3285 else {
3286 _setSSLError(NULL, 0, __FILE__, __LINE__);
3287 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003288 goto error;
3289 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003290 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003291 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003292 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3293 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003294 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3295 Py_CLEAR(keyfile_bytes);
3296 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003297 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003298 if (pw_info.error) {
3299 ERR_clear_error();
3300 /* the password callback has already set the error information */
3301 }
3302 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003303 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003304 PyErr_SetFromErrno(PyExc_IOError);
3305 }
3306 else {
3307 _setSSLError(NULL, 0, __FILE__, __LINE__);
3308 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003309 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003310 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003311 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003312 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003313 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003314 if (r != 1) {
3315 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003316 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003317 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003318 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3319 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003320 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003321 Py_RETURN_NONE;
3322
3323error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003324 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3325 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003326 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003327 Py_XDECREF(keyfile_bytes);
3328 Py_XDECREF(certfile_bytes);
3329 return NULL;
3330}
3331
Christian Heimesefff7062013-11-21 03:35:02 +01003332/* internal helper function, returns -1 on error
3333 */
3334static int
3335_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3336 int filetype)
3337{
3338 BIO *biobuf = NULL;
3339 X509_STORE *store;
3340 int retval = 0, err, loaded = 0;
3341
3342 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3343
3344 if (len <= 0) {
3345 PyErr_SetString(PyExc_ValueError,
3346 "Empty certificate data");
3347 return -1;
3348 } else if (len > INT_MAX) {
3349 PyErr_SetString(PyExc_OverflowError,
3350 "Certificate data is too long.");
3351 return -1;
3352 }
3353
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003354 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003355 if (biobuf == NULL) {
3356 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3357 return -1;
3358 }
3359
3360 store = SSL_CTX_get_cert_store(self->ctx);
3361 assert(store != NULL);
3362
3363 while (1) {
3364 X509 *cert = NULL;
3365 int r;
3366
3367 if (filetype == SSL_FILETYPE_ASN1) {
3368 cert = d2i_X509_bio(biobuf, NULL);
3369 } else {
3370 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003371 SSL_CTX_get_default_passwd_cb(self->ctx),
3372 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3373 );
Christian Heimesefff7062013-11-21 03:35:02 +01003374 }
3375 if (cert == NULL) {
3376 break;
3377 }
3378 r = X509_STORE_add_cert(store, cert);
3379 X509_free(cert);
3380 if (!r) {
3381 err = ERR_peek_last_error();
3382 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3383 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3384 /* cert already in hash table, not an error */
3385 ERR_clear_error();
3386 } else {
3387 break;
3388 }
3389 }
3390 loaded++;
3391 }
3392
3393 err = ERR_peek_last_error();
3394 if ((filetype == SSL_FILETYPE_ASN1) &&
3395 (loaded > 0) &&
3396 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3397 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3398 /* EOF ASN1 file, not an error */
3399 ERR_clear_error();
3400 retval = 0;
3401 } else if ((filetype == SSL_FILETYPE_PEM) &&
3402 (loaded > 0) &&
3403 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3404 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3405 /* EOF PEM file, not an error */
3406 ERR_clear_error();
3407 retval = 0;
3408 } else {
3409 _setSSLError(NULL, 0, __FILE__, __LINE__);
3410 retval = -1;
3411 }
3412
3413 BIO_free(biobuf);
3414 return retval;
3415}
3416
3417
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003418/*[clinic input]
3419_ssl._SSLContext.load_verify_locations
3420 cafile: object = NULL
3421 capath: object = NULL
3422 cadata: object = NULL
3423
3424[clinic start generated code]*/
3425
Antoine Pitrou152efa22010-05-16 18:19:27 +00003426static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003427_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3428 PyObject *cafile,
3429 PyObject *capath,
3430 PyObject *cadata)
3431/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003432{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003433 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3434 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003435 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003436
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003437 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003438 if (cafile == Py_None)
3439 cafile = NULL;
3440 if (capath == Py_None)
3441 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003442 if (cadata == Py_None)
3443 cadata = NULL;
3444
3445 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003446 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003447 "cafile, capath and cadata cannot be all omitted");
3448 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003449 }
3450 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3451 PyErr_SetString(PyExc_TypeError,
3452 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003453 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003454 }
3455 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003456 PyErr_SetString(PyExc_TypeError,
3457 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003458 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003459 }
Christian Heimesefff7062013-11-21 03:35:02 +01003460
3461 /* validata cadata type and load cadata */
3462 if (cadata) {
3463 Py_buffer buf;
3464 PyObject *cadata_ascii = NULL;
3465
3466 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3467 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3468 PyBuffer_Release(&buf);
3469 PyErr_SetString(PyExc_TypeError,
3470 "cadata should be a contiguous buffer with "
3471 "a single dimension");
3472 goto error;
3473 }
3474 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3475 PyBuffer_Release(&buf);
3476 if (r == -1) {
3477 goto error;
3478 }
3479 } else {
3480 PyErr_Clear();
3481 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3482 if (cadata_ascii == NULL) {
3483 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003484 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003485 "bytes-like object");
3486 goto error;
3487 }
3488 r = _add_ca_certs(self,
3489 PyBytes_AS_STRING(cadata_ascii),
3490 PyBytes_GET_SIZE(cadata_ascii),
3491 SSL_FILETYPE_PEM);
3492 Py_DECREF(cadata_ascii);
3493 if (r == -1) {
3494 goto error;
3495 }
3496 }
3497 }
3498
3499 /* load cafile or capath */
3500 if (cafile || capath) {
3501 if (cafile)
3502 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3503 if (capath)
3504 capath_buf = PyBytes_AS_STRING(capath_bytes);
3505 PySSL_BEGIN_ALLOW_THREADS
3506 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3507 PySSL_END_ALLOW_THREADS
3508 if (r != 1) {
3509 ok = 0;
3510 if (errno != 0) {
3511 ERR_clear_error();
3512 PyErr_SetFromErrno(PyExc_IOError);
3513 }
3514 else {
3515 _setSSLError(NULL, 0, __FILE__, __LINE__);
3516 }
3517 goto error;
3518 }
3519 }
3520 goto end;
3521
3522 error:
3523 ok = 0;
3524 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003525 Py_XDECREF(cafile_bytes);
3526 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003527 if (ok) {
3528 Py_RETURN_NONE;
3529 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003530 return NULL;
3531 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003532}
3533
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003534/*[clinic input]
3535_ssl._SSLContext.load_dh_params
3536 path as filepath: object
3537 /
3538
3539[clinic start generated code]*/
3540
Antoine Pitrou152efa22010-05-16 18:19:27 +00003541static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003542_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3543/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003544{
3545 FILE *f;
3546 DH *dh;
3547
Victor Stinnerdaf45552013-08-28 00:53:59 +02003548 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003549 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003550 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003551
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003552 errno = 0;
3553 PySSL_BEGIN_ALLOW_THREADS
3554 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003555 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003556 PySSL_END_ALLOW_THREADS
3557 if (dh == NULL) {
3558 if (errno != 0) {
3559 ERR_clear_error();
3560 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3561 }
3562 else {
3563 _setSSLError(NULL, 0, __FILE__, __LINE__);
3564 }
3565 return NULL;
3566 }
3567 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3568 _setSSLError(NULL, 0, __FILE__, __LINE__);
3569 DH_free(dh);
3570 Py_RETURN_NONE;
3571}
3572
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003573/*[clinic input]
3574_ssl._SSLContext._wrap_socket
3575 sock: object(subclass_of="PySocketModule.Sock_Type")
3576 server_side: int
3577 server_hostname as hostname_obj: object = None
3578
3579[clinic start generated code]*/
3580
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003581static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003582_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3583 int server_side, PyObject *hostname_obj)
3584/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003585{
Antoine Pitroud5323212010-10-22 18:19:07 +00003586 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003587 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003588
Antoine Pitroud5323212010-10-22 18:19:07 +00003589 /* server_hostname is either None (or absent), or to be encoded
3590 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003591 if (hostname_obj != Py_None) {
3592 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003593 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003594 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003595
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003596 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3597 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003598 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003599 if (hostname != NULL)
3600 PyMem_Free(hostname);
3601 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003602}
3603
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003604/*[clinic input]
3605_ssl._SSLContext._wrap_bio
3606 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3607 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3608 server_side: int
3609 server_hostname as hostname_obj: object = None
3610
3611[clinic start generated code]*/
3612
Antoine Pitroub0182c82010-10-12 20:09:02 +00003613static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003614_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3615 PySSLMemoryBIO *outgoing, int server_side,
3616 PyObject *hostname_obj)
3617/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003618{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003619 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003620 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003621
3622 /* server_hostname is either None (or absent), or to be encoded
3623 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003624 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003625 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3626 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003627 }
3628
3629 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3630 incoming, outgoing);
3631
3632 PyMem_Free(hostname);
3633 return res;
3634}
3635
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003636/*[clinic input]
3637_ssl._SSLContext.session_stats
3638[clinic start generated code]*/
3639
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003640static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003641_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3642/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003643{
3644 int r;
3645 PyObject *value, *stats = PyDict_New();
3646 if (!stats)
3647 return NULL;
3648
3649#define ADD_STATS(SSL_NAME, KEY_NAME) \
3650 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3651 if (value == NULL) \
3652 goto error; \
3653 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3654 Py_DECREF(value); \
3655 if (r < 0) \
3656 goto error;
3657
3658 ADD_STATS(number, "number");
3659 ADD_STATS(connect, "connect");
3660 ADD_STATS(connect_good, "connect_good");
3661 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3662 ADD_STATS(accept, "accept");
3663 ADD_STATS(accept_good, "accept_good");
3664 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3665 ADD_STATS(accept, "accept");
3666 ADD_STATS(hits, "hits");
3667 ADD_STATS(misses, "misses");
3668 ADD_STATS(timeouts, "timeouts");
3669 ADD_STATS(cache_full, "cache_full");
3670
3671#undef ADD_STATS
3672
3673 return stats;
3674
3675error:
3676 Py_DECREF(stats);
3677 return NULL;
3678}
3679
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003680/*[clinic input]
3681_ssl._SSLContext.set_default_verify_paths
3682[clinic start generated code]*/
3683
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003684static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003685_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3686/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003687{
3688 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3689 _setSSLError(NULL, 0, __FILE__, __LINE__);
3690 return NULL;
3691 }
3692 Py_RETURN_NONE;
3693}
3694
Antoine Pitrou501da612011-12-21 09:27:41 +01003695#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003696/*[clinic input]
3697_ssl._SSLContext.set_ecdh_curve
3698 name: object
3699 /
3700
3701[clinic start generated code]*/
3702
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003703static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003704_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3705/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003706{
3707 PyObject *name_bytes;
3708 int nid;
3709 EC_KEY *key;
3710
3711 if (!PyUnicode_FSConverter(name, &name_bytes))
3712 return NULL;
3713 assert(PyBytes_Check(name_bytes));
3714 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3715 Py_DECREF(name_bytes);
3716 if (nid == 0) {
3717 PyErr_Format(PyExc_ValueError,
3718 "unknown elliptic curve name %R", name);
3719 return NULL;
3720 }
3721 key = EC_KEY_new_by_curve_name(nid);
3722 if (key == NULL) {
3723 _setSSLError(NULL, 0, __FILE__, __LINE__);
3724 return NULL;
3725 }
3726 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3727 EC_KEY_free(key);
3728 Py_RETURN_NONE;
3729}
Antoine Pitrou501da612011-12-21 09:27:41 +01003730#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003731
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003732#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003733static int
3734_servername_callback(SSL *s, int *al, void *args)
3735{
3736 int ret;
3737 PySSLContext *ssl_ctx = (PySSLContext *) args;
3738 PySSLSocket *ssl;
3739 PyObject *servername_o;
3740 PyObject *servername_idna;
3741 PyObject *result;
3742 /* The high-level ssl.SSLSocket object */
3743 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003744 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003745#ifdef WITH_THREAD
3746 PyGILState_STATE gstate = PyGILState_Ensure();
3747#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003748
3749 if (ssl_ctx->set_hostname == NULL) {
3750 /* remove race condition in this the call back while if removing the
3751 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003752#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003753 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003754#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003755 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003756 }
3757
3758 ssl = SSL_get_app_data(s);
3759 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003760
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003761 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003762 * SSL connection and that has a .context attribute that can be changed to
3763 * identify the requested hostname. Since the official API is the Python
3764 * level API we want to pass the callback a Python level object rather than
3765 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3766 * SSLObject) that will be passed. Otherwise if there's a socket then that
3767 * will be passed. If both do not exist only then the C-level object is
3768 * passed. */
3769 if (ssl->owner)
3770 ssl_socket = PyWeakref_GetObject(ssl->owner);
3771 else if (ssl->Socket)
3772 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3773 else
3774 ssl_socket = (PyObject *) ssl;
3775
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003776 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003777 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003778 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003779
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003780 if (servername == NULL) {
3781 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3782 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003783 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003784 else {
3785 servername_o = PyBytes_FromString(servername);
3786 if (servername_o == NULL) {
3787 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3788 goto error;
3789 }
3790 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3791 if (servername_idna == NULL) {
3792 PyErr_WriteUnraisable(servername_o);
3793 Py_DECREF(servername_o);
3794 goto error;
3795 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003796 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003797 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3798 servername_idna, ssl_ctx, NULL);
3799 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003800 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003801 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003802
3803 if (result == NULL) {
3804 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3805 *al = SSL_AD_HANDSHAKE_FAILURE;
3806 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3807 }
3808 else {
3809 if (result != Py_None) {
3810 *al = (int) PyLong_AsLong(result);
3811 if (PyErr_Occurred()) {
3812 PyErr_WriteUnraisable(result);
3813 *al = SSL_AD_INTERNAL_ERROR;
3814 }
3815 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3816 }
3817 else {
3818 ret = SSL_TLSEXT_ERR_OK;
3819 }
3820 Py_DECREF(result);
3821 }
3822
Stefan Krah20d60802013-01-17 17:07:17 +01003823#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003824 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003825#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003826 return ret;
3827
3828error:
3829 Py_DECREF(ssl_socket);
3830 *al = SSL_AD_INTERNAL_ERROR;
3831 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003832#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003833 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003834#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003835 return ret;
3836}
Antoine Pitroua5963382013-03-30 16:39:00 +01003837#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003838
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003839/*[clinic input]
3840_ssl._SSLContext.set_servername_callback
3841 method as cb: object
3842 /
3843
3844Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3845
3846If the argument is None then the callback is disabled. The method is called
3847with the SSLSocket, the server name as a string, and the SSLContext object.
3848See RFC 6066 for details of the SNI extension.
3849[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003850
3851static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003852_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3853/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003854{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003855#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003856 Py_CLEAR(self->set_hostname);
3857 if (cb == Py_None) {
3858 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3859 }
3860 else {
3861 if (!PyCallable_Check(cb)) {
3862 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3863 PyErr_SetString(PyExc_TypeError,
3864 "not a callable object");
3865 return NULL;
3866 }
3867 Py_INCREF(cb);
3868 self->set_hostname = cb;
3869 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3870 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3871 }
3872 Py_RETURN_NONE;
3873#else
3874 PyErr_SetString(PyExc_NotImplementedError,
3875 "The TLS extension servername callback, "
3876 "SSL_CTX_set_tlsext_servername_callback, "
3877 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003878 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003879#endif
3880}
3881
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003882/*[clinic input]
3883_ssl._SSLContext.cert_store_stats
3884
3885Returns quantities of loaded X.509 certificates.
3886
3887X.509 certificates with a CA extension and certificate revocation lists
3888inside the context's cert store.
3889
3890NOTE: Certificates in a capath directory aren't loaded unless they have
3891been used at least once.
3892[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003893
3894static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003895_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3896/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003897{
3898 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003899 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003900 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003901 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003902
3903 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003904 objs = X509_STORE_get0_objects(store);
3905 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3906 obj = sk_X509_OBJECT_value(objs, i);
3907 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003908 case X509_LU_X509:
3909 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003910 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003911 ca++;
3912 }
3913 break;
3914 case X509_LU_CRL:
3915 crl++;
3916 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003917 default:
3918 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3919 * As far as I can tell they are internal states and never
3920 * stored in a cert store */
3921 break;
3922 }
3923 }
3924 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3925 "x509_ca", ca);
3926}
3927
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003928/*[clinic input]
3929_ssl._SSLContext.get_ca_certs
3930 binary_form: bool = False
3931
3932Returns a list of dicts with information of loaded CA certs.
3933
3934If the optional argument is True, returns a DER-encoded copy of the CA
3935certificate.
3936
3937NOTE: Certificates in a capath directory aren't loaded unless they have
3938been used at least once.
3939[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003940
3941static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003942_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3943/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003944{
3945 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003946 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003947 PyObject *ci = NULL, *rlist = NULL;
3948 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003949
3950 if ((rlist = PyList_New(0)) == NULL) {
3951 return NULL;
3952 }
3953
3954 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003955 objs = X509_STORE_get0_objects(store);
3956 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003957 X509_OBJECT *obj;
3958 X509 *cert;
3959
Christian Heimes598894f2016-09-05 23:19:05 +02003960 obj = sk_X509_OBJECT_value(objs, i);
3961 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003962 /* not a x509 cert */
3963 continue;
3964 }
3965 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003966 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003967 if (!X509_check_ca(cert)) {
3968 continue;
3969 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003970 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003971 ci = _certificate_to_der(cert);
3972 } else {
3973 ci = _decode_certificate(cert);
3974 }
3975 if (ci == NULL) {
3976 goto error;
3977 }
3978 if (PyList_Append(rlist, ci) == -1) {
3979 goto error;
3980 }
3981 Py_CLEAR(ci);
3982 }
3983 return rlist;
3984
3985 error:
3986 Py_XDECREF(ci);
3987 Py_XDECREF(rlist);
3988 return NULL;
3989}
3990
3991
Antoine Pitrou152efa22010-05-16 18:19:27 +00003992static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003993 {"check_hostname", (getter) get_check_hostname,
3994 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003995 {"options", (getter) get_options,
3996 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003997 {"verify_flags", (getter) get_verify_flags,
3998 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003999 {"verify_mode", (getter) get_verify_mode,
4000 (setter) set_verify_mode, NULL},
4001 {NULL}, /* sentinel */
4002};
4003
4004static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004005 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4006 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4007 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4008 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4009 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4010 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4011 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4012 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4013 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4014 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4015 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4016 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4017 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4018 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004019 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004020 {NULL, NULL} /* sentinel */
4021};
4022
4023static PyTypeObject PySSLContext_Type = {
4024 PyVarObject_HEAD_INIT(NULL, 0)
4025 "_ssl._SSLContext", /*tp_name*/
4026 sizeof(PySSLContext), /*tp_basicsize*/
4027 0, /*tp_itemsize*/
4028 (destructor)context_dealloc, /*tp_dealloc*/
4029 0, /*tp_print*/
4030 0, /*tp_getattr*/
4031 0, /*tp_setattr*/
4032 0, /*tp_reserved*/
4033 0, /*tp_repr*/
4034 0, /*tp_as_number*/
4035 0, /*tp_as_sequence*/
4036 0, /*tp_as_mapping*/
4037 0, /*tp_hash*/
4038 0, /*tp_call*/
4039 0, /*tp_str*/
4040 0, /*tp_getattro*/
4041 0, /*tp_setattro*/
4042 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004043 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004044 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004045 (traverseproc) context_traverse, /*tp_traverse*/
4046 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004047 0, /*tp_richcompare*/
4048 0, /*tp_weaklistoffset*/
4049 0, /*tp_iter*/
4050 0, /*tp_iternext*/
4051 context_methods, /*tp_methods*/
4052 0, /*tp_members*/
4053 context_getsetlist, /*tp_getset*/
4054 0, /*tp_base*/
4055 0, /*tp_dict*/
4056 0, /*tp_descr_get*/
4057 0, /*tp_descr_set*/
4058 0, /*tp_dictoffset*/
4059 0, /*tp_init*/
4060 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004061 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004062};
4063
4064
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004065/*
4066 * MemoryBIO objects
4067 */
4068
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004069/*[clinic input]
4070@classmethod
4071_ssl.MemoryBIO.__new__
4072
4073[clinic start generated code]*/
4074
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004075static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004076_ssl_MemoryBIO_impl(PyTypeObject *type)
4077/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004078{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004079 BIO *bio;
4080 PySSLMemoryBIO *self;
4081
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004082 bio = BIO_new(BIO_s_mem());
4083 if (bio == NULL) {
4084 PyErr_SetString(PySSLErrorObject,
4085 "failed to allocate BIO");
4086 return NULL;
4087 }
4088 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4089 * just that no data is currently available. The SSL routines should retry
4090 * the read, which we can achieve by calling BIO_set_retry_read(). */
4091 BIO_set_retry_read(bio);
4092 BIO_set_mem_eof_return(bio, -1);
4093
4094 assert(type != NULL && type->tp_alloc != NULL);
4095 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4096 if (self == NULL) {
4097 BIO_free(bio);
4098 return NULL;
4099 }
4100 self->bio = bio;
4101 self->eof_written = 0;
4102
4103 return (PyObject *) self;
4104}
4105
4106static void
4107memory_bio_dealloc(PySSLMemoryBIO *self)
4108{
4109 BIO_free(self->bio);
4110 Py_TYPE(self)->tp_free(self);
4111}
4112
4113static PyObject *
4114memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4115{
4116 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
4117}
4118
4119PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4120"The number of bytes pending in the memory BIO.");
4121
4122static PyObject *
4123memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4124{
4125 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4126 && self->eof_written);
4127}
4128
4129PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4130"Whether the memory BIO is at EOF.");
4131
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004132/*[clinic input]
4133_ssl.MemoryBIO.read
4134 size as len: int = -1
4135 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004136
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004137Read up to size bytes from the memory BIO.
4138
4139If size is not specified, read the entire buffer.
4140If the return value is an empty bytes instance, this means either
4141EOF or that no data is available. Use the "eof" property to
4142distinguish between the two.
4143[clinic start generated code]*/
4144
4145static PyObject *
4146_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4147/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4148{
4149 int avail, nbytes;
4150 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004151
4152 avail = BIO_ctrl_pending(self->bio);
4153 if ((len < 0) || (len > avail))
4154 len = avail;
4155
4156 result = PyBytes_FromStringAndSize(NULL, len);
4157 if ((result == NULL) || (len == 0))
4158 return result;
4159
4160 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4161 /* There should never be any short reads but check anyway. */
4162 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4163 Py_DECREF(result);
4164 return NULL;
4165 }
4166
4167 return result;
4168}
4169
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004170/*[clinic input]
4171_ssl.MemoryBIO.write
4172 b: Py_buffer
4173 /
4174
4175Writes the bytes b into the memory BIO.
4176
4177Returns the number of bytes written.
4178[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004179
4180static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004181_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4182/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004183{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004184 int nbytes;
4185
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004186 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004187 PyErr_Format(PyExc_OverflowError,
4188 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004189 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004190 }
4191
4192 if (self->eof_written) {
4193 PyErr_SetString(PySSLErrorObject,
4194 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004195 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004196 }
4197
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004198 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004199 if (nbytes < 0) {
4200 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004201 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004202 }
4203
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004204 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004205}
4206
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004207/*[clinic input]
4208_ssl.MemoryBIO.write_eof
4209
4210Write an EOF marker to the memory BIO.
4211
4212When all data has been read, the "eof" property will be True.
4213[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004214
4215static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004216_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4217/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004218{
4219 self->eof_written = 1;
4220 /* After an EOF is written, a zero return from read() should be a real EOF
4221 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4222 BIO_clear_retry_flags(self->bio);
4223 BIO_set_mem_eof_return(self->bio, 0);
4224
4225 Py_RETURN_NONE;
4226}
4227
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004228static PyGetSetDef memory_bio_getsetlist[] = {
4229 {"pending", (getter) memory_bio_get_pending, NULL,
4230 PySSL_memory_bio_pending_doc},
4231 {"eof", (getter) memory_bio_get_eof, NULL,
4232 PySSL_memory_bio_eof_doc},
4233 {NULL}, /* sentinel */
4234};
4235
4236static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004237 _SSL_MEMORYBIO_READ_METHODDEF
4238 _SSL_MEMORYBIO_WRITE_METHODDEF
4239 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004240 {NULL, NULL} /* sentinel */
4241};
4242
4243static PyTypeObject PySSLMemoryBIO_Type = {
4244 PyVarObject_HEAD_INIT(NULL, 0)
4245 "_ssl.MemoryBIO", /*tp_name*/
4246 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4247 0, /*tp_itemsize*/
4248 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4249 0, /*tp_print*/
4250 0, /*tp_getattr*/
4251 0, /*tp_setattr*/
4252 0, /*tp_reserved*/
4253 0, /*tp_repr*/
4254 0, /*tp_as_number*/
4255 0, /*tp_as_sequence*/
4256 0, /*tp_as_mapping*/
4257 0, /*tp_hash*/
4258 0, /*tp_call*/
4259 0, /*tp_str*/
4260 0, /*tp_getattro*/
4261 0, /*tp_setattro*/
4262 0, /*tp_as_buffer*/
4263 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4264 0, /*tp_doc*/
4265 0, /*tp_traverse*/
4266 0, /*tp_clear*/
4267 0, /*tp_richcompare*/
4268 0, /*tp_weaklistoffset*/
4269 0, /*tp_iter*/
4270 0, /*tp_iternext*/
4271 memory_bio_methods, /*tp_methods*/
4272 0, /*tp_members*/
4273 memory_bio_getsetlist, /*tp_getset*/
4274 0, /*tp_base*/
4275 0, /*tp_dict*/
4276 0, /*tp_descr_get*/
4277 0, /*tp_descr_set*/
4278 0, /*tp_dictoffset*/
4279 0, /*tp_init*/
4280 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004281 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004282};
4283
Antoine Pitrou152efa22010-05-16 18:19:27 +00004284
Christian Heimes99a65702016-09-10 23:44:53 +02004285/*
4286 * SSL Session object
4287 */
4288
4289static void
4290PySSLSession_dealloc(PySSLSession *self)
4291{
4292 Py_XDECREF(self->ctx);
4293 if (self->session != NULL) {
4294 SSL_SESSION_free(self->session);
4295 }
4296 PyObject_Del(self);
4297}
4298
4299static PyObject *
4300PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4301{
4302 int result;
4303
4304 if (left == NULL || right == NULL) {
4305 PyErr_BadInternalCall();
4306 return NULL;
4307 }
4308
4309 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4310 Py_RETURN_NOTIMPLEMENTED;
4311 }
4312
4313 if (left == right) {
4314 result = 0;
4315 } else {
4316 const unsigned char *left_id, *right_id;
4317 unsigned int left_len, right_len;
4318 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4319 &left_len);
4320 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4321 &right_len);
4322 if (left_len == right_len) {
4323 result = memcmp(left_id, right_id, left_len);
4324 } else {
4325 result = 1;
4326 }
4327 }
4328
4329 switch (op) {
4330 case Py_EQ:
4331 if (result == 0) {
4332 Py_RETURN_TRUE;
4333 } else {
4334 Py_RETURN_FALSE;
4335 }
4336 break;
4337 case Py_NE:
4338 if (result != 0) {
4339 Py_RETURN_TRUE;
4340 } else {
4341 Py_RETURN_FALSE;
4342 }
4343 break;
4344 case Py_LT:
4345 case Py_LE:
4346 case Py_GT:
4347 case Py_GE:
4348 Py_RETURN_NOTIMPLEMENTED;
4349 break;
4350 default:
4351 PyErr_BadArgument();
4352 return NULL;
4353 }
4354}
4355
4356static int
4357PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4358{
4359 Py_VISIT(self->ctx);
4360 return 0;
4361}
4362
4363static int
4364PySSLSession_clear(PySSLSession *self)
4365{
4366 Py_CLEAR(self->ctx);
4367 return 0;
4368}
4369
4370
4371static PyObject *
4372PySSLSession_get_time(PySSLSession *self, void *closure) {
4373 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4374}
4375
4376PyDoc_STRVAR(PySSLSession_get_time_doc,
4377"Session creation time (seconds since epoch).");
4378
4379
4380static PyObject *
4381PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4382 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4383}
4384
4385PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4386"Session timeout (delta in seconds).");
4387
4388
4389static PyObject *
4390PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4391 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4392 return PyLong_FromUnsignedLong(hint);
4393}
4394
4395PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4396"Ticket life time hint.");
4397
4398
4399static PyObject *
4400PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4401 const unsigned char *id;
4402 unsigned int len;
4403 id = SSL_SESSION_get_id(self->session, &len);
4404 return PyBytes_FromStringAndSize((const char *)id, len);
4405}
4406
4407PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4408"Session id");
4409
4410
4411static PyObject *
4412PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4413 if (SSL_SESSION_has_ticket(self->session)) {
4414 Py_RETURN_TRUE;
4415 } else {
4416 Py_RETURN_FALSE;
4417 }
4418}
4419
4420PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4421"Does the session contain a ticket?");
4422
4423
4424static PyGetSetDef PySSLSession_getsetlist[] = {
4425 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4426 PySSLSession_get_has_ticket_doc},
4427 {"id", (getter) PySSLSession_get_session_id, NULL,
4428 PySSLSession_get_session_id_doc},
4429 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4430 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4431 {"time", (getter) PySSLSession_get_time, NULL,
4432 PySSLSession_get_time_doc},
4433 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4434 PySSLSession_get_timeout_doc},
4435 {NULL}, /* sentinel */
4436};
4437
4438static PyTypeObject PySSLSession_Type = {
4439 PyVarObject_HEAD_INIT(NULL, 0)
4440 "_ssl.Session", /*tp_name*/
4441 sizeof(PySSLSession), /*tp_basicsize*/
4442 0, /*tp_itemsize*/
4443 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4444 0, /*tp_print*/
4445 0, /*tp_getattr*/
4446 0, /*tp_setattr*/
4447 0, /*tp_reserved*/
4448 0, /*tp_repr*/
4449 0, /*tp_as_number*/
4450 0, /*tp_as_sequence*/
4451 0, /*tp_as_mapping*/
4452 0, /*tp_hash*/
4453 0, /*tp_call*/
4454 0, /*tp_str*/
4455 0, /*tp_getattro*/
4456 0, /*tp_setattro*/
4457 0, /*tp_as_buffer*/
4458 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4459 0, /*tp_doc*/
4460 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4461 (inquiry)PySSLSession_clear, /*tp_clear*/
4462 PySSLSession_richcompare, /*tp_richcompare*/
4463 0, /*tp_weaklistoffset*/
4464 0, /*tp_iter*/
4465 0, /*tp_iternext*/
4466 0, /*tp_methods*/
4467 0, /*tp_members*/
4468 PySSLSession_getsetlist, /*tp_getset*/
4469};
4470
4471
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004472/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004473/*[clinic input]
4474_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004475 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004476 entropy: double
4477 /
4478
4479Mix string into the OpenSSL PRNG state.
4480
4481entropy (a float) is a lower bound on the entropy contained in
4482string. See RFC 1750.
4483[clinic start generated code]*/
4484
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004485static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004486_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
4487/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004488{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004489 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004490 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004491
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004492 buf = (const char *)view->buf;
4493 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004494 do {
4495 written = Py_MIN(len, INT_MAX);
4496 RAND_add(buf, (int)written, entropy);
4497 buf += written;
4498 len -= written;
4499 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004500 Py_INCREF(Py_None);
4501 return Py_None;
4502}
4503
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004504static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004505PySSL_RAND(int len, int pseudo)
4506{
4507 int ok;
4508 PyObject *bytes;
4509 unsigned long err;
4510 const char *errstr;
4511 PyObject *v;
4512
Victor Stinner1e81a392013-12-19 16:47:04 +01004513 if (len < 0) {
4514 PyErr_SetString(PyExc_ValueError, "num must be positive");
4515 return NULL;
4516 }
4517
Victor Stinner99c8b162011-05-24 12:05:19 +02004518 bytes = PyBytes_FromStringAndSize(NULL, len);
4519 if (bytes == NULL)
4520 return NULL;
4521 if (pseudo) {
4522 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4523 if (ok == 0 || ok == 1)
4524 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4525 }
4526 else {
4527 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4528 if (ok == 1)
4529 return bytes;
4530 }
4531 Py_DECREF(bytes);
4532
4533 err = ERR_get_error();
4534 errstr = ERR_reason_error_string(err);
4535 v = Py_BuildValue("(ks)", err, errstr);
4536 if (v != NULL) {
4537 PyErr_SetObject(PySSLErrorObject, v);
4538 Py_DECREF(v);
4539 }
4540 return NULL;
4541}
4542
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004543/*[clinic input]
4544_ssl.RAND_bytes
4545 n: int
4546 /
4547
4548Generate n cryptographically strong pseudo-random bytes.
4549[clinic start generated code]*/
4550
Victor Stinner99c8b162011-05-24 12:05:19 +02004551static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004552_ssl_RAND_bytes_impl(PyObject *module, int n)
4553/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004554{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004555 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004556}
4557
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004558/*[clinic input]
4559_ssl.RAND_pseudo_bytes
4560 n: int
4561 /
4562
4563Generate n pseudo-random bytes.
4564
4565Return a pair (bytes, is_cryptographic). is_cryptographic is True
4566if the bytes generated are cryptographically strong.
4567[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004568
4569static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004570_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4571/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004572{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004573 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004574}
4575
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004576/*[clinic input]
4577_ssl.RAND_status
4578
4579Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4580
4581It is necessary to seed the PRNG with RAND_add() on some platforms before
4582using the ssl() function.
4583[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004584
4585static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004586_ssl_RAND_status_impl(PyObject *module)
4587/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004588{
Christian Heimes217cfd12007-12-02 14:31:20 +00004589 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004590}
4591
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004592#ifndef OPENSSL_NO_EGD
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004593/*[clinic input]
4594_ssl.RAND_egd
4595 path: object(converter="PyUnicode_FSConverter")
4596 /
4597
4598Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4599
4600Returns number of bytes read. Raises SSLError if connection to EGD
4601fails or if it does not provide enough data to seed PRNG.
4602[clinic start generated code]*/
4603
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004604static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004605_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4606/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004607{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004608 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004609 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004610 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004611 PyErr_SetString(PySSLErrorObject,
4612 "EGD connection failed or EGD did not return "
4613 "enough data to seed the PRNG");
4614 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004615 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004616 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004617}
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004618#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004619
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004620
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004621
4622/*[clinic input]
4623_ssl.get_default_verify_paths
4624
4625Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4626
4627The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4628[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004629
4630static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004631_ssl_get_default_verify_paths_impl(PyObject *module)
4632/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004633{
4634 PyObject *ofile_env = NULL;
4635 PyObject *ofile = NULL;
4636 PyObject *odir_env = NULL;
4637 PyObject *odir = NULL;
4638
Benjamin Petersond113c962015-07-18 10:59:13 -07004639#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004640 const char *tmp = (info); \
4641 target = NULL; \
4642 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4643 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4644 target = PyBytes_FromString(tmp); } \
4645 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004646 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004647
Benjamin Petersond113c962015-07-18 10:59:13 -07004648 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4649 CONVERT(X509_get_default_cert_file(), ofile);
4650 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4651 CONVERT(X509_get_default_cert_dir(), odir);
4652#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004653
Christian Heimes200bb1b2013-06-14 15:14:29 +02004654 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004655
4656 error:
4657 Py_XDECREF(ofile_env);
4658 Py_XDECREF(ofile);
4659 Py_XDECREF(odir_env);
4660 Py_XDECREF(odir);
4661 return NULL;
4662}
4663
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004664static PyObject*
4665asn1obj2py(ASN1_OBJECT *obj)
4666{
4667 int nid;
4668 const char *ln, *sn;
4669 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004670 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004671
4672 nid = OBJ_obj2nid(obj);
4673 if (nid == NID_undef) {
4674 PyErr_Format(PyExc_ValueError, "Unknown object");
4675 return NULL;
4676 }
4677 sn = OBJ_nid2sn(nid);
4678 ln = OBJ_nid2ln(nid);
4679 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4680 if (buflen < 0) {
4681 _setSSLError(NULL, 0, __FILE__, __LINE__);
4682 return NULL;
4683 }
4684 if (buflen) {
4685 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4686 } else {
4687 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4688 }
4689}
4690
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004691/*[clinic input]
4692_ssl.txt2obj
4693 txt: str
4694 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004695
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004696Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4697
4698By default objects are looked up by OID. With name=True short and
4699long name are also matched.
4700[clinic start generated code]*/
4701
4702static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004703_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4704/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004705{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004706 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004707 ASN1_OBJECT *obj;
4708
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004709 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4710 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004711 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004712 return NULL;
4713 }
4714 result = asn1obj2py(obj);
4715 ASN1_OBJECT_free(obj);
4716 return result;
4717}
4718
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004719/*[clinic input]
4720_ssl.nid2obj
4721 nid: int
4722 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004723
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004724Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4725[clinic start generated code]*/
4726
4727static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004728_ssl_nid2obj_impl(PyObject *module, int nid)
4729/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004730{
4731 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004732 ASN1_OBJECT *obj;
4733
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004734 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004735 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004736 return NULL;
4737 }
4738 obj = OBJ_nid2obj(nid);
4739 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004740 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004741 return NULL;
4742 }
4743 result = asn1obj2py(obj);
4744 ASN1_OBJECT_free(obj);
4745 return result;
4746}
4747
Christian Heimes46bebee2013-06-09 19:03:31 +02004748#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004749
4750static PyObject*
4751certEncodingType(DWORD encodingType)
4752{
4753 static PyObject *x509_asn = NULL;
4754 static PyObject *pkcs_7_asn = NULL;
4755
4756 if (x509_asn == NULL) {
4757 x509_asn = PyUnicode_InternFromString("x509_asn");
4758 if (x509_asn == NULL)
4759 return NULL;
4760 }
4761 if (pkcs_7_asn == NULL) {
4762 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4763 if (pkcs_7_asn == NULL)
4764 return NULL;
4765 }
4766 switch(encodingType) {
4767 case X509_ASN_ENCODING:
4768 Py_INCREF(x509_asn);
4769 return x509_asn;
4770 case PKCS_7_ASN_ENCODING:
4771 Py_INCREF(pkcs_7_asn);
4772 return pkcs_7_asn;
4773 default:
4774 return PyLong_FromLong(encodingType);
4775 }
4776}
4777
4778static PyObject*
4779parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4780{
4781 CERT_ENHKEY_USAGE *usage;
4782 DWORD size, error, i;
4783 PyObject *retval;
4784
4785 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4786 error = GetLastError();
4787 if (error == CRYPT_E_NOT_FOUND) {
4788 Py_RETURN_TRUE;
4789 }
4790 return PyErr_SetFromWindowsErr(error);
4791 }
4792
4793 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4794 if (usage == NULL) {
4795 return PyErr_NoMemory();
4796 }
4797
4798 /* Now get the actual enhanced usage property */
4799 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4800 PyMem_Free(usage);
4801 error = GetLastError();
4802 if (error == CRYPT_E_NOT_FOUND) {
4803 Py_RETURN_TRUE;
4804 }
4805 return PyErr_SetFromWindowsErr(error);
4806 }
4807 retval = PySet_New(NULL);
4808 if (retval == NULL) {
4809 goto error;
4810 }
4811 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4812 if (usage->rgpszUsageIdentifier[i]) {
4813 PyObject *oid;
4814 int err;
4815 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4816 if (oid == NULL) {
4817 Py_CLEAR(retval);
4818 goto error;
4819 }
4820 err = PySet_Add(retval, oid);
4821 Py_DECREF(oid);
4822 if (err == -1) {
4823 Py_CLEAR(retval);
4824 goto error;
4825 }
4826 }
4827 }
4828 error:
4829 PyMem_Free(usage);
4830 return retval;
4831}
4832
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004833/*[clinic input]
4834_ssl.enum_certificates
4835 store_name: str
4836
4837Retrieve certificates from Windows' cert store.
4838
4839store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4840more cert storages, too. The function returns a list of (bytes,
4841encoding_type, trust) tuples. The encoding_type flag can be interpreted
4842with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4843a set of OIDs or the boolean True.
4844[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004845
Christian Heimes46bebee2013-06-09 19:03:31 +02004846static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004847_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4848/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004849{
Christian Heimes46bebee2013-06-09 19:03:31 +02004850 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004851 PCCERT_CONTEXT pCertCtx = NULL;
4852 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004853 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004854
Christian Heimes44109d72013-11-22 01:51:30 +01004855 result = PyList_New(0);
4856 if (result == NULL) {
4857 return NULL;
4858 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004859 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4860 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4861 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004862 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004863 Py_DECREF(result);
4864 return PyErr_SetFromWindowsErr(GetLastError());
4865 }
4866
Christian Heimes44109d72013-11-22 01:51:30 +01004867 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4868 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4869 pCertCtx->cbCertEncoded);
4870 if (!cert) {
4871 Py_CLEAR(result);
4872 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004873 }
Christian Heimes44109d72013-11-22 01:51:30 +01004874 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4875 Py_CLEAR(result);
4876 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004877 }
Christian Heimes44109d72013-11-22 01:51:30 +01004878 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4879 if (keyusage == Py_True) {
4880 Py_DECREF(keyusage);
4881 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004882 }
Christian Heimes44109d72013-11-22 01:51:30 +01004883 if (keyusage == NULL) {
4884 Py_CLEAR(result);
4885 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004886 }
Christian Heimes44109d72013-11-22 01:51:30 +01004887 if ((tup = PyTuple_New(3)) == NULL) {
4888 Py_CLEAR(result);
4889 break;
4890 }
4891 PyTuple_SET_ITEM(tup, 0, cert);
4892 cert = NULL;
4893 PyTuple_SET_ITEM(tup, 1, enc);
4894 enc = NULL;
4895 PyTuple_SET_ITEM(tup, 2, keyusage);
4896 keyusage = NULL;
4897 if (PyList_Append(result, tup) < 0) {
4898 Py_CLEAR(result);
4899 break;
4900 }
4901 Py_CLEAR(tup);
4902 }
4903 if (pCertCtx) {
4904 /* loop ended with an error, need to clean up context manually */
4905 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004906 }
4907
4908 /* In error cases cert, enc and tup may not be NULL */
4909 Py_XDECREF(cert);
4910 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004911 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004912 Py_XDECREF(tup);
4913
4914 if (!CertCloseStore(hStore, 0)) {
4915 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004916 Py_XDECREF(result);
4917 return PyErr_SetFromWindowsErr(GetLastError());
4918 }
4919 return result;
4920}
4921
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004922/*[clinic input]
4923_ssl.enum_crls
4924 store_name: str
4925
4926Retrieve CRLs from Windows' cert store.
4927
4928store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4929more cert storages, too. The function returns a list of (bytes,
4930encoding_type) tuples. The encoding_type flag can be interpreted with
4931X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4932[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004933
4934static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004935_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4936/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004937{
Christian Heimes44109d72013-11-22 01:51:30 +01004938 HCERTSTORE hStore = NULL;
4939 PCCRL_CONTEXT pCrlCtx = NULL;
4940 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4941 PyObject *result = NULL;
4942
Christian Heimes44109d72013-11-22 01:51:30 +01004943 result = PyList_New(0);
4944 if (result == NULL) {
4945 return NULL;
4946 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004947 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4948 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4949 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004950 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004951 Py_DECREF(result);
4952 return PyErr_SetFromWindowsErr(GetLastError());
4953 }
Christian Heimes44109d72013-11-22 01:51:30 +01004954
4955 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4956 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4957 pCrlCtx->cbCrlEncoded);
4958 if (!crl) {
4959 Py_CLEAR(result);
4960 break;
4961 }
4962 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4963 Py_CLEAR(result);
4964 break;
4965 }
4966 if ((tup = PyTuple_New(2)) == NULL) {
4967 Py_CLEAR(result);
4968 break;
4969 }
4970 PyTuple_SET_ITEM(tup, 0, crl);
4971 crl = NULL;
4972 PyTuple_SET_ITEM(tup, 1, enc);
4973 enc = NULL;
4974
4975 if (PyList_Append(result, tup) < 0) {
4976 Py_CLEAR(result);
4977 break;
4978 }
4979 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004980 }
Christian Heimes44109d72013-11-22 01:51:30 +01004981 if (pCrlCtx) {
4982 /* loop ended with an error, need to clean up context manually */
4983 CertFreeCRLContext(pCrlCtx);
4984 }
4985
4986 /* In error cases cert, enc and tup may not be NULL */
4987 Py_XDECREF(crl);
4988 Py_XDECREF(enc);
4989 Py_XDECREF(tup);
4990
4991 if (!CertCloseStore(hStore, 0)) {
4992 /* This error case might shadow another exception.*/
4993 Py_XDECREF(result);
4994 return PyErr_SetFromWindowsErr(GetLastError());
4995 }
4996 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004997}
Christian Heimes44109d72013-11-22 01:51:30 +01004998
4999#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005000
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005001/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005002static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005003 _SSL__TEST_DECODE_CERT_METHODDEF
5004 _SSL_RAND_ADD_METHODDEF
5005 _SSL_RAND_BYTES_METHODDEF
5006 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5007 _SSL_RAND_EGD_METHODDEF
5008 _SSL_RAND_STATUS_METHODDEF
5009 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5010 _SSL_ENUM_CERTIFICATES_METHODDEF
5011 _SSL_ENUM_CRLS_METHODDEF
5012 _SSL_TXT2OBJ_METHODDEF
5013 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005014 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005015};
5016
5017
Christian Heimes598894f2016-09-05 23:19:05 +02005018#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005019
5020/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005021 * of the Python C thread library
5022 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5023 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005024
5025static PyThread_type_lock *_ssl_locks = NULL;
5026
Christian Heimes4d98ca92013-08-19 17:36:29 +02005027#if OPENSSL_VERSION_NUMBER >= 0x10000000
5028/* use new CRYPTO_THREADID API. */
5029static void
5030_ssl_threadid_callback(CRYPTO_THREADID *id)
5031{
5032 CRYPTO_THREADID_set_numeric(id,
5033 (unsigned long)PyThread_get_thread_ident());
5034}
5035#else
5036/* deprecated CRYPTO_set_id_callback() API. */
5037static unsigned long
5038_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005039 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005040}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005041#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005042
Bill Janssen6e027db2007-11-15 22:23:56 +00005043static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005044 (int mode, int n, const char *file, int line) {
5045 /* this function is needed to perform locking on shared data
5046 structures. (Note that OpenSSL uses a number of global data
5047 structures that will be implicitly shared whenever multiple
5048 threads use OpenSSL.) Multi-threaded applications will
5049 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005050
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005051 locking_function() must be able to handle up to
5052 CRYPTO_num_locks() different mutex locks. It sets the n-th
5053 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005054
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005055 file and line are the file number of the function setting the
5056 lock. They can be useful for debugging.
5057 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005058
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005059 if ((_ssl_locks == NULL) ||
5060 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5061 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005062
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005063 if (mode & CRYPTO_LOCK) {
5064 PyThread_acquire_lock(_ssl_locks[n], 1);
5065 } else {
5066 PyThread_release_lock(_ssl_locks[n]);
5067 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005068}
5069
5070static int _setup_ssl_threads(void) {
5071
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005072 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005073
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005074 if (_ssl_locks == NULL) {
5075 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005076 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
5077 if (_ssl_locks == NULL) {
5078 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005079 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005080 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005081 memset(_ssl_locks, 0,
5082 sizeof(PyThread_type_lock) * _ssl_locks_count);
5083 for (i = 0; i < _ssl_locks_count; i++) {
5084 _ssl_locks[i] = PyThread_allocate_lock();
5085 if (_ssl_locks[i] == NULL) {
5086 unsigned int j;
5087 for (j = 0; j < i; j++) {
5088 PyThread_free_lock(_ssl_locks[j]);
5089 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005090 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005091 return 0;
5092 }
5093 }
5094 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005095#if OPENSSL_VERSION_NUMBER >= 0x10000000
5096 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5097#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005098 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005099#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005100 }
5101 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005102}
5103
Christian Heimes598894f2016-09-05 23:19:05 +02005104#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005105
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005106PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005107"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005108for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005109
Martin v. Löwis1a214512008-06-11 05:26:20 +00005110
5111static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005112 PyModuleDef_HEAD_INIT,
5113 "_ssl",
5114 module_doc,
5115 -1,
5116 PySSL_methods,
5117 NULL,
5118 NULL,
5119 NULL,
5120 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005121};
5122
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005123
5124static void
5125parse_openssl_version(unsigned long libver,
5126 unsigned int *major, unsigned int *minor,
5127 unsigned int *fix, unsigned int *patch,
5128 unsigned int *status)
5129{
5130 *status = libver & 0xF;
5131 libver >>= 4;
5132 *patch = libver & 0xFF;
5133 libver >>= 8;
5134 *fix = libver & 0xFF;
5135 libver >>= 8;
5136 *minor = libver & 0xFF;
5137 libver >>= 8;
5138 *major = libver & 0xFF;
5139}
5140
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005141PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005142PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005143{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005144 PyObject *m, *d, *r;
5145 unsigned long libver;
5146 unsigned int major, minor, fix, patch, status;
5147 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005148 struct py_ssl_error_code *errcode;
5149 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005150
Antoine Pitrou152efa22010-05-16 18:19:27 +00005151 if (PyType_Ready(&PySSLContext_Type) < 0)
5152 return NULL;
5153 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005154 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005155 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5156 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005157 if (PyType_Ready(&PySSLSession_Type) < 0)
5158 return NULL;
5159
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005160
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005161 m = PyModule_Create(&_sslmodule);
5162 if (m == NULL)
5163 return NULL;
5164 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005165
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005166 /* Load _socket module and its C API */
5167 socket_api = PySocketModule_ImportModuleAndAPI();
5168 if (!socket_api)
5169 return NULL;
5170 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005171
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005172 /* Init OpenSSL */
5173 SSL_load_error_strings();
5174 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005175#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02005176#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005177 /* note that this will start threading if not already started */
5178 if (!_setup_ssl_threads()) {
5179 return NULL;
5180 }
Christian Heimes598894f2016-09-05 23:19:05 +02005181#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5182 /* OpenSSL 1.1.0 builtin thread support is enabled */
5183 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005184#endif
Christian Heimes598894f2016-09-05 23:19:05 +02005185#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005186 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005187
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005188 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005189 sslerror_type_slots[0].pfunc = PyExc_OSError;
5190 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005191 if (PySSLErrorObject == NULL)
5192 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005193
Antoine Pitrou41032a62011-10-27 23:56:55 +02005194 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5195 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5196 PySSLErrorObject, NULL);
5197 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5198 "ssl.SSLWantReadError", SSLWantReadError_doc,
5199 PySSLErrorObject, NULL);
5200 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5201 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5202 PySSLErrorObject, NULL);
5203 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5204 "ssl.SSLSyscallError", SSLSyscallError_doc,
5205 PySSLErrorObject, NULL);
5206 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5207 "ssl.SSLEOFError", SSLEOFError_doc,
5208 PySSLErrorObject, NULL);
5209 if (PySSLZeroReturnErrorObject == NULL
5210 || PySSLWantReadErrorObject == NULL
5211 || PySSLWantWriteErrorObject == NULL
5212 || PySSLSyscallErrorObject == NULL
5213 || PySSLEOFErrorObject == NULL)
5214 return NULL;
5215 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5216 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5217 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5218 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5219 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5220 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005221 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005222 if (PyDict_SetItemString(d, "_SSLContext",
5223 (PyObject *)&PySSLContext_Type) != 0)
5224 return NULL;
5225 if (PyDict_SetItemString(d, "_SSLSocket",
5226 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005227 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005228 if (PyDict_SetItemString(d, "MemoryBIO",
5229 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5230 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005231 if (PyDict_SetItemString(d, "SSLSession",
5232 (PyObject *)&PySSLSession_Type) != 0)
5233 return NULL;
5234
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005235 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5236 PY_SSL_ERROR_ZERO_RETURN);
5237 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5238 PY_SSL_ERROR_WANT_READ);
5239 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5240 PY_SSL_ERROR_WANT_WRITE);
5241 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5242 PY_SSL_ERROR_WANT_X509_LOOKUP);
5243 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5244 PY_SSL_ERROR_SYSCALL);
5245 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5246 PY_SSL_ERROR_SSL);
5247 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5248 PY_SSL_ERROR_WANT_CONNECT);
5249 /* non ssl.h errorcodes */
5250 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5251 PY_SSL_ERROR_EOF);
5252 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5253 PY_SSL_ERROR_INVALID_ERROR_CODE);
5254 /* cert requirements */
5255 PyModule_AddIntConstant(m, "CERT_NONE",
5256 PY_SSL_CERT_NONE);
5257 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5258 PY_SSL_CERT_OPTIONAL);
5259 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5260 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005261 /* CRL verification for verification_flags */
5262 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5263 0);
5264 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5265 X509_V_FLAG_CRL_CHECK);
5266 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5267 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5268 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5269 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005270#ifdef X509_V_FLAG_TRUSTED_FIRST
5271 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5272 X509_V_FLAG_TRUSTED_FIRST);
5273#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005274
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005275 /* Alert Descriptions from ssl.h */
5276 /* note RESERVED constants no longer intended for use have been removed */
5277 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5278
5279#define ADD_AD_CONSTANT(s) \
5280 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5281 SSL_AD_##s)
5282
5283 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5284 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5285 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5286 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5287 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5288 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5289 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5290 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5291 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5292 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5293 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5294 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5295 ADD_AD_CONSTANT(UNKNOWN_CA);
5296 ADD_AD_CONSTANT(ACCESS_DENIED);
5297 ADD_AD_CONSTANT(DECODE_ERROR);
5298 ADD_AD_CONSTANT(DECRYPT_ERROR);
5299 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5300 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5301 ADD_AD_CONSTANT(INTERNAL_ERROR);
5302 ADD_AD_CONSTANT(USER_CANCELLED);
5303 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005304 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005305#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5306 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5307#endif
5308#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5309 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5310#endif
5311#ifdef SSL_AD_UNRECOGNIZED_NAME
5312 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5313#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005314#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5315 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5316#endif
5317#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5318 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5319#endif
5320#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5321 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5322#endif
5323
5324#undef ADD_AD_CONSTANT
5325
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005326 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005327#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005328 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5329 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005330#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005331#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005332 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5333 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005334#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005335 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005336 PY_SSL_VERSION_TLS);
5337 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5338 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005339 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5340 PY_SSL_VERSION_TLS_CLIENT);
5341 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5342 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005343 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5344 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005345#if HAVE_TLSv1_2
5346 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5347 PY_SSL_VERSION_TLS1_1);
5348 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5349 PY_SSL_VERSION_TLS1_2);
5350#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005351
Antoine Pitroub5218772010-05-21 09:56:06 +00005352 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005353 PyModule_AddIntConstant(m, "OP_ALL",
5354 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005355 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5356 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5357 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005358#if HAVE_TLSv1_2
5359 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5360 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5361#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005362 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5363 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005364 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005365 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005366#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005367 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005368#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005369#ifdef SSL_OP_NO_COMPRESSION
5370 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5371 SSL_OP_NO_COMPRESSION);
5372#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005373
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005374#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005375 r = Py_True;
5376#else
5377 r = Py_False;
5378#endif
5379 Py_INCREF(r);
5380 PyModule_AddObject(m, "HAS_SNI", r);
5381
Antoine Pitroud6494802011-07-21 01:11:30 +02005382 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005383 Py_INCREF(r);
5384 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5385
Antoine Pitrou501da612011-12-21 09:27:41 +01005386#ifdef OPENSSL_NO_ECDH
5387 r = Py_False;
5388#else
5389 r = Py_True;
5390#endif
5391 Py_INCREF(r);
5392 PyModule_AddObject(m, "HAS_ECDH", r);
5393
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005394#ifdef OPENSSL_NPN_NEGOTIATED
5395 r = Py_True;
5396#else
5397 r = Py_False;
5398#endif
5399 Py_INCREF(r);
5400 PyModule_AddObject(m, "HAS_NPN", r);
5401
Benjamin Petersoncca27322015-01-23 16:35:37 -05005402#ifdef HAVE_ALPN
5403 r = Py_True;
5404#else
5405 r = Py_False;
5406#endif
5407 Py_INCREF(r);
5408 PyModule_AddObject(m, "HAS_ALPN", r);
5409
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005410 /* Mappings for error codes */
5411 err_codes_to_names = PyDict_New();
5412 err_names_to_codes = PyDict_New();
5413 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5414 return NULL;
5415 errcode = error_codes;
5416 while (errcode->mnemonic != NULL) {
5417 PyObject *mnemo, *key;
5418 mnemo = PyUnicode_FromString(errcode->mnemonic);
5419 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5420 if (mnemo == NULL || key == NULL)
5421 return NULL;
5422 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5423 return NULL;
5424 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5425 return NULL;
5426 Py_DECREF(key);
5427 Py_DECREF(mnemo);
5428 errcode++;
5429 }
5430 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5431 return NULL;
5432 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5433 return NULL;
5434
5435 lib_codes_to_names = PyDict_New();
5436 if (lib_codes_to_names == NULL)
5437 return NULL;
5438 libcode = library_codes;
5439 while (libcode->library != NULL) {
5440 PyObject *mnemo, *key;
5441 key = PyLong_FromLong(libcode->code);
5442 mnemo = PyUnicode_FromString(libcode->library);
5443 if (key == NULL || mnemo == NULL)
5444 return NULL;
5445 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5446 return NULL;
5447 Py_DECREF(key);
5448 Py_DECREF(mnemo);
5449 libcode++;
5450 }
5451 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5452 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005453
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005454 /* OpenSSL version */
5455 /* SSLeay() gives us the version of the library linked against,
5456 which could be different from the headers version.
5457 */
5458 libver = SSLeay();
5459 r = PyLong_FromUnsignedLong(libver);
5460 if (r == NULL)
5461 return NULL;
5462 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5463 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005464 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005465 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5466 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5467 return NULL;
5468 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5469 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5470 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005471
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005472 libver = OPENSSL_VERSION_NUMBER;
5473 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5474 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5475 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5476 return NULL;
5477
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005478 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005479}