blob: c0a7b8e1052c337627974df55f7d93af36f0ab6c [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#ifdef WITH_THREAD
22#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020023
Christian Heimesf77b4b22013-08-21 13:26:05 +020024
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020025#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
26 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
27#define PySSL_END_ALLOW_THREADS_S(save) \
28 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000029#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000030 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020031 PySSL_BEGIN_ALLOW_THREADS_S(_save);
32#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
33#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
34#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000035
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000036#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000037
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020038#define PySSL_BEGIN_ALLOW_THREADS_S(save)
39#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000040#define PySSL_BEGIN_ALLOW_THREADS
41#define PySSL_BLOCK_THREADS
42#define PySSL_UNBLOCK_THREADS
43#define PySSL_END_ALLOW_THREADS
44
45#endif
46
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010047/* Include symbols from _socket module */
48#include "socketmodule.h"
49
50static PySocketModule_APIObject PySocketModule;
51
52#if defined(HAVE_POLL_H)
53#include <poll.h>
54#elif defined(HAVE_SYS_POLL_H)
55#include <sys/poll.h>
56#endif
57
Christian Heimes598894f2016-09-05 23:19:05 +020058/* Don't warn about deprecated functions */
59#ifdef __GNUC__
60#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
61#endif
62#ifdef __clang__
63#pragma clang diagnostic ignored "-Wdeprecated-declarations"
64#endif
65
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010066/* Include OpenSSL header files */
67#include "openssl/rsa.h"
68#include "openssl/crypto.h"
69#include "openssl/x509.h"
70#include "openssl/x509v3.h"
71#include "openssl/pem.h"
72#include "openssl/ssl.h"
73#include "openssl/err.h"
74#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020075#include "openssl/bio.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010076
77/* SSL error object */
78static PyObject *PySSLErrorObject;
79static PyObject *PySSLZeroReturnErrorObject;
80static PyObject *PySSLWantReadErrorObject;
81static PyObject *PySSLWantWriteErrorObject;
82static PyObject *PySSLSyscallErrorObject;
83static PyObject *PySSLEOFErrorObject;
84
85/* Error mappings */
86static PyObject *err_codes_to_names;
87static PyObject *err_names_to_codes;
88static PyObject *lib_codes_to_names;
89
90struct py_ssl_error_code {
91 const char *mnemonic;
92 int library, reason;
93};
94struct py_ssl_library_code {
95 const char *library;
96 int code;
97};
98
99/* Include generated data (error codes) */
100#include "_ssl_data.h"
101
Christian Heimes598894f2016-09-05 23:19:05 +0200102#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
103# define OPENSSL_VERSION_1_1 1
104#endif
105
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100106/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
107 http://www.openssl.org/news/changelog.html
108 */
109#if OPENSSL_VERSION_NUMBER >= 0x10001000L
110# define HAVE_TLSv1_2 1
111#else
112# define HAVE_TLSv1_2 0
113#endif
114
Christian Heimes470fba12013-11-28 15:12:15 +0100115/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100116 * This includes the SSL_set_SSL_CTX() function.
117 */
118#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
119# define HAVE_SNI 1
120#else
121# define HAVE_SNI 0
122#endif
123
Benjamin Petersond3308222015-09-27 00:09:02 -0700124#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Benjamin Petersoncca27322015-01-23 16:35:37 -0500125# define HAVE_ALPN
126#endif
127
Victor Stinner524714e2016-07-22 17:43:59 +0200128#ifndef INVALID_SOCKET /* MS defines this */
129#define INVALID_SOCKET (-1)
130#endif
131
Christian Heimes598894f2016-09-05 23:19:05 +0200132#ifdef OPENSSL_VERSION_1_1
133/* OpenSSL 1.1.0+ */
134#ifndef OPENSSL_NO_SSL2
135#define OPENSSL_NO_SSL2
136#endif
137#else /* OpenSSL < 1.1.0 */
138#if defined(WITH_THREAD)
139#define HAVE_OPENSSL_CRYPTO_LOCK
140#endif
141
142#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200143#define TLS_client_method SSLv23_client_method
144#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200145
146static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
147{
148 return ne->set;
149}
150
151#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200152/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200153static int COMP_get_type(const COMP_METHOD *meth)
154{
155 return meth->type;
156}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200157/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200158#endif
159
160static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
161{
162 return ctx->default_passwd_callback;
163}
164
165static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
166{
167 return ctx->default_passwd_callback_userdata;
168}
169
170static int X509_OBJECT_get_type(X509_OBJECT *x)
171{
172 return x->type;
173}
174
175static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
176{
177 return x->data.x509;
178}
179
180static int BIO_up_ref(BIO *b)
181{
182 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
183 return 1;
184}
185
186static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
187 return store->objs;
188}
189
190static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
191{
192 return store->param;
193}
Christian Heimes99a65702016-09-10 23:44:53 +0200194
195static int
196SSL_SESSION_has_ticket(const SSL_SESSION *s)
197{
198 return (s->tlsext_ticklen > 0) ? 1 : 0;
199}
200
201static unsigned long
202SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
203{
204 return s->tlsext_tick_lifetime_hint;
205}
206
Christian Heimes598894f2016-09-05 23:19:05 +0200207#endif /* OpenSSL < 1.1.0 or LibreSSL */
208
209
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000210enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000211 /* these mirror ssl.h */
212 PY_SSL_ERROR_NONE,
213 PY_SSL_ERROR_SSL,
214 PY_SSL_ERROR_WANT_READ,
215 PY_SSL_ERROR_WANT_WRITE,
216 PY_SSL_ERROR_WANT_X509_LOOKUP,
217 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
218 PY_SSL_ERROR_ZERO_RETURN,
219 PY_SSL_ERROR_WANT_CONNECT,
220 /* start of non ssl.h errorcodes */
221 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
222 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
223 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000224};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000225
Thomas Woutersed03b412007-08-28 21:37:11 +0000226enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000227 PY_SSL_CLIENT,
228 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000229};
230
231enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000232 PY_SSL_CERT_NONE,
233 PY_SSL_CERT_OPTIONAL,
234 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000235};
236
237enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000238 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200239 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200240 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100241#if HAVE_TLSv1_2
242 PY_SSL_VERSION_TLS1,
243 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200244 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100245#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200246 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000247#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200248 PY_SSL_VERSION_TLS_CLIENT=0x10,
249 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100250};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200251
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000252#ifdef WITH_THREAD
253
254/* serves as a flag to see whether we've initialized the SSL thread support. */
255/* 0 means no, greater than 0 means yes */
256
257static unsigned int _ssl_locks_count = 0;
258
259#endif /* def WITH_THREAD */
260
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000261/* SSL socket object */
262
263#define X509_NAME_MAXLEN 256
264
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000265/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
266 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
267 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
268#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000269# define HAVE_SSL_CTX_CLEAR_OPTIONS
270#else
271# undef HAVE_SSL_CTX_CLEAR_OPTIONS
272#endif
273
Antoine Pitroud6494802011-07-21 01:11:30 +0200274/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
275 * older SSL, but let's be safe */
276#define PySSL_CB_MAXLEN 128
277
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100278
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000279typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000280 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000281 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100282#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -0500283 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100284 int npn_protocols_len;
285#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500286#ifdef HAVE_ALPN
287 unsigned char *alpn_protocols;
288 int alpn_protocols_len;
289#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100290#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200291 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100292#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100293 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000294} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000295
Antoine Pitrou152efa22010-05-16 18:19:27 +0000296typedef struct {
297 PyObject_HEAD
298 PyObject *Socket; /* weakref to socket on which we're layered */
299 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100300 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000301 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200302 char shutdown_seen_zero;
303 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200304 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200305 PyObject *owner; /* Python level "owner" passed to servername callback */
306 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000307} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000308
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200309typedef struct {
310 PyObject_HEAD
311 BIO *bio;
312 int eof_written;
313} PySSLMemoryBIO;
314
Christian Heimes99a65702016-09-10 23:44:53 +0200315typedef struct {
316 PyObject_HEAD
317 SSL_SESSION *session;
318 PySSLContext *ctx;
319} PySSLSession;
320
Antoine Pitrou152efa22010-05-16 18:19:27 +0000321static PyTypeObject PySSLContext_Type;
322static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200323static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200324static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000325
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300326/*[clinic input]
327module _ssl
328class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
329class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
330class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200331class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300332[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200333/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300334
335#include "clinic/_ssl.c.h"
336
Victor Stinner14690702015-04-06 22:46:13 +0200337static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000338
Christian Heimes99a65702016-09-10 23:44:53 +0200339
Antoine Pitrou152efa22010-05-16 18:19:27 +0000340#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
341#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200342#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200343#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000344
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000345typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000346 SOCKET_IS_NONBLOCKING,
347 SOCKET_IS_BLOCKING,
348 SOCKET_HAS_TIMED_OUT,
349 SOCKET_HAS_BEEN_CLOSED,
350 SOCKET_TOO_LARGE_FOR_SELECT,
351 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000352} timeout_state;
353
Thomas Woutersed03b412007-08-28 21:37:11 +0000354/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000355#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200356#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000357
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200358/* Get the socket from a PySSLSocket, if it has one */
359#define GET_SOCKET(obj) ((obj)->Socket ? \
360 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200361
Victor Stinner14690702015-04-06 22:46:13 +0200362/* If sock is NULL, use a timeout of 0 second */
363#define GET_SOCKET_TIMEOUT(sock) \
364 ((sock != NULL) ? (sock)->sock_timeout : 0)
365
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200366/*
367 * SSL errors.
368 */
369
370PyDoc_STRVAR(SSLError_doc,
371"An error occurred in the SSL implementation.");
372
373PyDoc_STRVAR(SSLZeroReturnError_doc,
374"SSL/TLS session closed cleanly.");
375
376PyDoc_STRVAR(SSLWantReadError_doc,
377"Non-blocking SSL socket needs to read more data\n"
378"before the requested operation can be completed.");
379
380PyDoc_STRVAR(SSLWantWriteError_doc,
381"Non-blocking SSL socket needs to write more data\n"
382"before the requested operation can be completed.");
383
384PyDoc_STRVAR(SSLSyscallError_doc,
385"System error when attempting SSL operation.");
386
387PyDoc_STRVAR(SSLEOFError_doc,
388"SSL/TLS connection terminated abruptly.");
389
390static PyObject *
391SSLError_str(PyOSErrorObject *self)
392{
393 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
394 Py_INCREF(self->strerror);
395 return self->strerror;
396 }
397 else
398 return PyObject_Str(self->args);
399}
400
401static PyType_Slot sslerror_type_slots[] = {
402 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
403 {Py_tp_doc, SSLError_doc},
404 {Py_tp_str, SSLError_str},
405 {0, 0},
406};
407
408static PyType_Spec sslerror_type_spec = {
409 "ssl.SSLError",
410 sizeof(PyOSErrorObject),
411 0,
412 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
413 sslerror_type_slots
414};
415
416static void
417fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
418 int lineno, unsigned long errcode)
419{
420 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
421 PyObject *init_value, *msg, *key;
422 _Py_IDENTIFIER(reason);
423 _Py_IDENTIFIER(library);
424
425 if (errcode != 0) {
426 int lib, reason;
427
428 lib = ERR_GET_LIB(errcode);
429 reason = ERR_GET_REASON(errcode);
430 key = Py_BuildValue("ii", lib, reason);
431 if (key == NULL)
432 goto fail;
433 reason_obj = PyDict_GetItem(err_codes_to_names, key);
434 Py_DECREF(key);
435 if (reason_obj == NULL) {
436 /* XXX if reason < 100, it might reflect a library number (!!) */
437 PyErr_Clear();
438 }
439 key = PyLong_FromLong(lib);
440 if (key == NULL)
441 goto fail;
442 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
443 Py_DECREF(key);
444 if (lib_obj == NULL) {
445 PyErr_Clear();
446 }
447 if (errstr == NULL)
448 errstr = ERR_reason_error_string(errcode);
449 }
450 if (errstr == NULL)
451 errstr = "unknown error";
452
453 if (reason_obj && lib_obj)
454 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
455 lib_obj, reason_obj, errstr, lineno);
456 else if (lib_obj)
457 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
458 lib_obj, errstr, lineno);
459 else
460 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200461 if (msg == NULL)
462 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100463
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200464 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100465 if (init_value == NULL)
466 goto fail;
467
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200468 err_value = PyObject_CallObject(type, init_value);
469 Py_DECREF(init_value);
470 if (err_value == NULL)
471 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100472
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200473 if (reason_obj == NULL)
474 reason_obj = Py_None;
475 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
476 goto fail;
477 if (lib_obj == NULL)
478 lib_obj = Py_None;
479 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
480 goto fail;
481 PyErr_SetObject(type, err_value);
482fail:
483 Py_XDECREF(err_value);
484}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000485
486static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200487PySSL_SetError(PySSLSocket *obj, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000488{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200489 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200490 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000491 int err;
492 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200493 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000494
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000495 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200496 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000497
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000498 if (obj->ssl != NULL) {
499 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000500
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000501 switch (err) {
502 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200503 errstr = "TLS/SSL connection has been closed (EOF)";
504 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000505 p = PY_SSL_ERROR_ZERO_RETURN;
506 break;
507 case SSL_ERROR_WANT_READ:
508 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200509 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000510 p = PY_SSL_ERROR_WANT_READ;
511 break;
512 case SSL_ERROR_WANT_WRITE:
513 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200514 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000515 errstr = "The operation did not complete (write)";
516 break;
517 case SSL_ERROR_WANT_X509_LOOKUP:
518 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000519 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000520 break;
521 case SSL_ERROR_WANT_CONNECT:
522 p = PY_SSL_ERROR_WANT_CONNECT;
523 errstr = "The operation did not complete (connect)";
524 break;
525 case SSL_ERROR_SYSCALL:
526 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000527 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200528 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000529 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000530 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200531 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000532 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200533 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000534 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000535 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000536 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200537 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000538 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200539 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000540 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000541 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200542 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000543 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000544 }
545 } else {
546 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000547 }
548 break;
549 }
550 case SSL_ERROR_SSL:
551 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000552 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200553 if (e == 0)
554 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000555 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000556 break;
557 }
558 default:
559 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
560 errstr = "Invalid error code";
561 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000562 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200563 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000564 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000565 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000566}
567
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000568static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200569_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000570
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200571 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000572 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200573 else
574 errcode = 0;
575 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000576 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000577 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000578}
579
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200580/*
581 * SSL objects
582 */
583
Antoine Pitrou152efa22010-05-16 18:19:27 +0000584static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100585newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000586 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200587 char *server_hostname,
588 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000589{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000590 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100591 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200592 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000593
Antoine Pitrou152efa22010-05-16 18:19:27 +0000594 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000595 if (self == NULL)
596 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000597
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000598 self->peer_cert = NULL;
599 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000600 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100601 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200602 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200603 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200604 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700605 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200606 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700607 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
608 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200609 if (hostname == NULL) {
610 Py_DECREF(self);
611 return NULL;
612 }
613 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700614 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200615
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100616 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 /* Make sure the SSL error state is initialized */
619 (void) ERR_get_state();
620 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000621
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000622 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000623 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000624 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200625 SSL_set_app_data(self->ssl, self);
626 if (sock) {
627 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
628 } else {
629 /* BIOs are reference counted and SSL_set_bio borrows our reference.
630 * To prevent a double free in memory_bio_dealloc() we need to take an
631 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200632 BIO_up_ref(inbio->bio);
633 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200634 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
635 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200636 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000637#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200638 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000639#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200640 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000641
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100642#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000643 if (server_hostname != NULL)
644 SSL_set_tlsext_host_name(self->ssl, server_hostname);
645#endif
646
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000647 /* If the socket is in non-blocking mode or timeout mode, set the BIO
648 * to non-blocking mode (blocking is the default)
649 */
Victor Stinnere2452312015-03-28 03:00:46 +0100650 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000651 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
652 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
653 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000654
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000655 PySSL_BEGIN_ALLOW_THREADS
656 if (socket_type == PY_SSL_CLIENT)
657 SSL_set_connect_state(self->ssl);
658 else
659 SSL_set_accept_state(self->ssl);
660 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000661
Antoine Pitroud6494802011-07-21 01:11:30 +0200662 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200663 if (sock != NULL) {
664 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
665 if (self->Socket == NULL) {
666 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200667 return NULL;
668 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100669 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000670 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000671}
672
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000673/* SSL object methods */
674
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300675/*[clinic input]
676_ssl._SSLSocket.do_handshake
677[clinic start generated code]*/
678
679static PyObject *
680_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
681/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000682{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000683 int ret;
684 int err;
685 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200686 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200687 _PyTime_t timeout, deadline = 0;
688 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000689
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200690 if (sock) {
691 if (((PyObject*)sock) == Py_None) {
692 _setSSLError("Underlying socket connection gone",
693 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
694 return NULL;
695 }
696 Py_INCREF(sock);
697
698 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100699 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200700 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
701 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000702 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000703
Victor Stinner14690702015-04-06 22:46:13 +0200704 timeout = GET_SOCKET_TIMEOUT(sock);
705 has_timeout = (timeout > 0);
706 if (has_timeout)
707 deadline = _PyTime_GetMonotonicClock() + timeout;
708
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000709 /* Actually negotiate SSL connection */
710 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000711 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000712 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000713 ret = SSL_do_handshake(self->ssl);
714 err = SSL_get_error(self->ssl, ret);
715 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200716
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000717 if (PyErr_CheckSignals())
718 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200719
Victor Stinner14690702015-04-06 22:46:13 +0200720 if (has_timeout)
721 timeout = deadline - _PyTime_GetMonotonicClock();
722
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200724 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000725 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200726 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000727 } else {
728 sockstate = SOCKET_OPERATION_OK;
729 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200730
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000731 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000732 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000733 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000734 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
736 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000737 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000738 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000739 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
740 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000741 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000742 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
744 break;
745 }
746 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200747 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000748 if (ret < 1)
749 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000750
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000751 if (self->peer_cert)
752 X509_free (self->peer_cert);
753 PySSL_BEGIN_ALLOW_THREADS
754 self->peer_cert = SSL_get_peer_certificate(self->ssl);
755 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200756 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000757
758 Py_INCREF(Py_None);
759 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000760
761error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200762 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000763 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000764}
765
Thomas Woutersed03b412007-08-28 21:37:11 +0000766static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000767_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000768
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 char namebuf[X509_NAME_MAXLEN];
770 int buflen;
771 PyObject *name_obj;
772 PyObject *value_obj;
773 PyObject *attr;
774 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000775
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000776 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
777 if (buflen < 0) {
778 _setSSLError(NULL, 0, __FILE__, __LINE__);
779 goto fail;
780 }
781 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
782 if (name_obj == NULL)
783 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000784
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
786 if (buflen < 0) {
787 _setSSLError(NULL, 0, __FILE__, __LINE__);
788 Py_DECREF(name_obj);
789 goto fail;
790 }
791 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000792 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000793 OPENSSL_free(valuebuf);
794 if (value_obj == NULL) {
795 Py_DECREF(name_obj);
796 goto fail;
797 }
798 attr = PyTuple_New(2);
799 if (attr == NULL) {
800 Py_DECREF(name_obj);
801 Py_DECREF(value_obj);
802 goto fail;
803 }
804 PyTuple_SET_ITEM(attr, 0, name_obj);
805 PyTuple_SET_ITEM(attr, 1, value_obj);
806 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000807
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000808 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000809 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000810}
811
812static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000813_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000814{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000815 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
816 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
817 PyObject *rdnt;
818 PyObject *attr = NULL; /* tuple to hold an attribute */
819 int entry_count = X509_NAME_entry_count(xname);
820 X509_NAME_ENTRY *entry;
821 ASN1_OBJECT *name;
822 ASN1_STRING *value;
823 int index_counter;
824 int rdn_level = -1;
825 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000826
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000827 dn = PyList_New(0);
828 if (dn == NULL)
829 return NULL;
830 /* now create another tuple to hold the top-level RDN */
831 rdn = PyList_New(0);
832 if (rdn == NULL)
833 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000834
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000835 for (index_counter = 0;
836 index_counter < entry_count;
837 index_counter++)
838 {
839 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000840
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000841 /* check to see if we've gotten to a new RDN */
842 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200843 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000844 /* yes, new RDN */
845 /* add old RDN to DN */
846 rdnt = PyList_AsTuple(rdn);
847 Py_DECREF(rdn);
848 if (rdnt == NULL)
849 goto fail0;
850 retcode = PyList_Append(dn, rdnt);
851 Py_DECREF(rdnt);
852 if (retcode < 0)
853 goto fail0;
854 /* create new RDN */
855 rdn = PyList_New(0);
856 if (rdn == NULL)
857 goto fail0;
858 }
859 }
Christian Heimes598894f2016-09-05 23:19:05 +0200860 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000861
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000862 /* now add this attribute to the current RDN */
863 name = X509_NAME_ENTRY_get_object(entry);
864 value = X509_NAME_ENTRY_get_data(entry);
865 attr = _create_tuple_for_attribute(name, value);
866 /*
867 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
868 entry->set,
869 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
870 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
871 */
872 if (attr == NULL)
873 goto fail1;
874 retcode = PyList_Append(rdn, attr);
875 Py_DECREF(attr);
876 if (retcode < 0)
877 goto fail1;
878 }
879 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100880 if (rdn != NULL) {
881 if (PyList_GET_SIZE(rdn) > 0) {
882 rdnt = PyList_AsTuple(rdn);
883 Py_DECREF(rdn);
884 if (rdnt == NULL)
885 goto fail0;
886 retcode = PyList_Append(dn, rdnt);
887 Py_DECREF(rdnt);
888 if (retcode < 0)
889 goto fail0;
890 }
891 else {
892 Py_DECREF(rdn);
893 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000894 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000895
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 /* convert list to tuple */
897 rdnt = PyList_AsTuple(dn);
898 Py_DECREF(dn);
899 if (rdnt == NULL)
900 return NULL;
901 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000902
903 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000904 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000905
906 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000907 Py_XDECREF(dn);
908 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000909}
910
911static PyObject *
912_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000913
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000914 /* this code follows the procedure outlined in
915 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
916 function to extract the STACK_OF(GENERAL_NAME),
917 then iterates through the stack to add the
918 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000919
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000920 int i, j;
921 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200922 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000923 X509_EXTENSION *ext = NULL;
924 GENERAL_NAMES *names = NULL;
925 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000926 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000927 BIO *biobuf = NULL;
928 char buf[2048];
929 char *vptr;
930 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000932
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 if (certificate == NULL)
934 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000935
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 /* get a memory buffer */
937 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000938
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200939 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 while ((i = X509_get_ext_by_NID(
941 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000942
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 if (peer_alt_names == Py_None) {
944 peer_alt_names = PyList_New(0);
945 if (peer_alt_names == NULL)
946 goto fail;
947 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000948
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000949 /* now decode the altName */
950 ext = X509_get_ext(certificate, i);
951 if(!(method = X509V3_EXT_get(ext))) {
952 PyErr_SetString
953 (PySSLErrorObject,
954 ERRSTR("No method for internalizing subjectAltName!"));
955 goto fail;
956 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000957
Christian Heimes598894f2016-09-05 23:19:05 +0200958 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 if (method->it)
960 names = (GENERAL_NAMES*)
961 (ASN1_item_d2i(NULL,
962 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200963 X509_EXTENSION_get_data(ext)->length,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000964 ASN1_ITEM_ptr(method->it)));
965 else
966 names = (GENERAL_NAMES*)
967 (method->d2i(NULL,
968 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200969 X509_EXTENSION_get_data(ext)->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000970
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000971 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000972 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200973 int gntype;
974 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000975
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000976 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200977 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200978 switch (gntype) {
979 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000980 /* we special-case DirName as a tuple of
981 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000982
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000983 t = PyTuple_New(2);
984 if (t == NULL) {
985 goto fail;
986 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000987
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000988 v = PyUnicode_FromString("DirName");
989 if (v == NULL) {
990 Py_DECREF(t);
991 goto fail;
992 }
993 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000994
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000995 v = _create_tuple_for_X509_NAME (name->d.dirn);
996 if (v == NULL) {
997 Py_DECREF(t);
998 goto fail;
999 }
1000 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001001 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001002
Christian Heimes824f7f32013-08-17 00:54:47 +02001003 case GEN_EMAIL:
1004 case GEN_DNS:
1005 case GEN_URI:
1006 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1007 correctly, CVE-2013-4238 */
1008 t = PyTuple_New(2);
1009 if (t == NULL)
1010 goto fail;
1011 switch (gntype) {
1012 case GEN_EMAIL:
1013 v = PyUnicode_FromString("email");
1014 as = name->d.rfc822Name;
1015 break;
1016 case GEN_DNS:
1017 v = PyUnicode_FromString("DNS");
1018 as = name->d.dNSName;
1019 break;
1020 case GEN_URI:
1021 v = PyUnicode_FromString("URI");
1022 as = name->d.uniformResourceIdentifier;
1023 break;
1024 }
1025 if (v == NULL) {
1026 Py_DECREF(t);
1027 goto fail;
1028 }
1029 PyTuple_SET_ITEM(t, 0, v);
1030 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1031 ASN1_STRING_length(as));
1032 if (v == NULL) {
1033 Py_DECREF(t);
1034 goto fail;
1035 }
1036 PyTuple_SET_ITEM(t, 1, v);
1037 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001038
Christian Heimes1c03abd2016-09-06 23:25:35 +02001039 case GEN_RID:
1040 t = PyTuple_New(2);
1041 if (t == NULL)
1042 goto fail;
1043
1044 v = PyUnicode_FromString("Registered ID");
1045 if (v == NULL) {
1046 Py_DECREF(t);
1047 goto fail;
1048 }
1049 PyTuple_SET_ITEM(t, 0, v);
1050
1051 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1052 if (len < 0) {
1053 Py_DECREF(t);
1054 _setSSLError(NULL, 0, __FILE__, __LINE__);
1055 goto fail;
1056 } else if (len >= (int)sizeof(buf)) {
1057 v = PyUnicode_FromString("<INVALID>");
1058 } else {
1059 v = PyUnicode_FromStringAndSize(buf, len);
1060 }
1061 if (v == NULL) {
1062 Py_DECREF(t);
1063 goto fail;
1064 }
1065 PyTuple_SET_ITEM(t, 1, v);
1066 break;
1067
Christian Heimes824f7f32013-08-17 00:54:47 +02001068 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001070 switch (gntype) {
1071 /* check for new general name type */
1072 case GEN_OTHERNAME:
1073 case GEN_X400:
1074 case GEN_EDIPARTY:
1075 case GEN_IPADD:
1076 case GEN_RID:
1077 break;
1078 default:
1079 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1080 "Unknown general name type %d",
1081 gntype) == -1) {
1082 goto fail;
1083 }
1084 break;
1085 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001086 (void) BIO_reset(biobuf);
1087 GENERAL_NAME_print(biobuf, name);
1088 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1089 if (len < 0) {
1090 _setSSLError(NULL, 0, __FILE__, __LINE__);
1091 goto fail;
1092 }
1093 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001094 if (vptr == NULL) {
1095 PyErr_Format(PyExc_ValueError,
1096 "Invalid value %.200s",
1097 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001098 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001099 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001100 t = PyTuple_New(2);
1101 if (t == NULL)
1102 goto fail;
1103 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1104 if (v == NULL) {
1105 Py_DECREF(t);
1106 goto fail;
1107 }
1108 PyTuple_SET_ITEM(t, 0, v);
1109 v = PyUnicode_FromStringAndSize((vptr + 1),
1110 (len - (vptr - buf + 1)));
1111 if (v == NULL) {
1112 Py_DECREF(t);
1113 goto fail;
1114 }
1115 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001116 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001117 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001118
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001119 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001120
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001121 if (PyList_Append(peer_alt_names, t) < 0) {
1122 Py_DECREF(t);
1123 goto fail;
1124 }
1125 Py_DECREF(t);
1126 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001127 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001128 }
1129 BIO_free(biobuf);
1130 if (peer_alt_names != Py_None) {
1131 v = PyList_AsTuple(peer_alt_names);
1132 Py_DECREF(peer_alt_names);
1133 return v;
1134 } else {
1135 return peer_alt_names;
1136 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001137
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001138
1139 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 if (biobuf != NULL)
1141 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001142
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001143 if (peer_alt_names != Py_None) {
1144 Py_XDECREF(peer_alt_names);
1145 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001146
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001148}
1149
1150static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001151_get_aia_uri(X509 *certificate, int nid) {
1152 PyObject *lst = NULL, *ostr = NULL;
1153 int i, result;
1154 AUTHORITY_INFO_ACCESS *info;
1155
1156 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001157 if (info == NULL)
1158 return Py_None;
1159 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1160 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001161 return Py_None;
1162 }
1163
1164 if ((lst = PyList_New(0)) == NULL) {
1165 goto fail;
1166 }
1167
1168 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1169 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1170 ASN1_IA5STRING *uri;
1171
1172 if ((OBJ_obj2nid(ad->method) != nid) ||
1173 (ad->location->type != GEN_URI)) {
1174 continue;
1175 }
1176 uri = ad->location->d.uniformResourceIdentifier;
1177 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1178 uri->length);
1179 if (ostr == NULL) {
1180 goto fail;
1181 }
1182 result = PyList_Append(lst, ostr);
1183 Py_DECREF(ostr);
1184 if (result < 0) {
1185 goto fail;
1186 }
1187 }
1188 AUTHORITY_INFO_ACCESS_free(info);
1189
1190 /* convert to tuple or None */
1191 if (PyList_Size(lst) == 0) {
1192 Py_DECREF(lst);
1193 return Py_None;
1194 } else {
1195 PyObject *tup;
1196 tup = PyList_AsTuple(lst);
1197 Py_DECREF(lst);
1198 return tup;
1199 }
1200
1201 fail:
1202 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001203 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001204 return NULL;
1205}
1206
1207static PyObject *
1208_get_crl_dp(X509 *certificate) {
1209 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001210 int i, j;
1211 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001212
Christian Heimes598894f2016-09-05 23:19:05 +02001213#if OPENSSL_VERSION_NUMBER >= 0x10001000L
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001214 /* Calls x509v3_cache_extensions and sets up crldp */
1215 X509_check_ca(certificate);
Christian Heimes949ec142013-11-21 16:26:51 +01001216#endif
Christian Heimes598894f2016-09-05 23:19:05 +02001217 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001218
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001219 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001220 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001221
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001222 lst = PyList_New(0);
1223 if (lst == NULL)
1224 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001225
1226 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1227 DIST_POINT *dp;
1228 STACK_OF(GENERAL_NAME) *gns;
1229
1230 dp = sk_DIST_POINT_value(dps, i);
1231 gns = dp->distpoint->name.fullname;
1232
1233 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1234 GENERAL_NAME *gn;
1235 ASN1_IA5STRING *uri;
1236 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001237 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001238
1239 gn = sk_GENERAL_NAME_value(gns, j);
1240 if (gn->type != GEN_URI) {
1241 continue;
1242 }
1243 uri = gn->d.uniformResourceIdentifier;
1244 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1245 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001246 if (ouri == NULL)
1247 goto done;
1248
1249 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001250 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001251 if (err < 0)
1252 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001253 }
1254 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001255
1256 /* Convert to tuple. */
1257 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1258
1259 done:
1260 Py_XDECREF(lst);
1261#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Peterson806fb252015-11-14 00:09:22 -08001262 sk_DIST_POINT_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001263#endif
1264 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001265}
1266
1267static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001268_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001269
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001270 PyObject *retval = NULL;
1271 BIO *biobuf = NULL;
1272 PyObject *peer;
1273 PyObject *peer_alt_names = NULL;
1274 PyObject *issuer;
1275 PyObject *version;
1276 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001277 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 ASN1_INTEGER *serialNumber;
1279 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001280 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 ASN1_TIME *notBefore, *notAfter;
1282 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001283
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001284 retval = PyDict_New();
1285 if (retval == NULL)
1286 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 peer = _create_tuple_for_X509_NAME(
1289 X509_get_subject_name(certificate));
1290 if (peer == NULL)
1291 goto fail0;
1292 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1293 Py_DECREF(peer);
1294 goto fail0;
1295 }
1296 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001297
Antoine Pitroufb046912010-11-09 20:21:19 +00001298 issuer = _create_tuple_for_X509_NAME(
1299 X509_get_issuer_name(certificate));
1300 if (issuer == NULL)
1301 goto fail0;
1302 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001303 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001304 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001305 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001306 Py_DECREF(issuer);
1307
1308 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001309 if (version == NULL)
1310 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001311 if (PyDict_SetItemString(retval, "version", version) < 0) {
1312 Py_DECREF(version);
1313 goto fail0;
1314 }
1315 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001316
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001317 /* get a memory buffer */
1318 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001319
Antoine Pitroufb046912010-11-09 20:21:19 +00001320 (void) BIO_reset(biobuf);
1321 serialNumber = X509_get_serialNumber(certificate);
1322 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1323 i2a_ASN1_INTEGER(biobuf, serialNumber);
1324 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1325 if (len < 0) {
1326 _setSSLError(NULL, 0, __FILE__, __LINE__);
1327 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001328 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001329 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1330 if (sn_obj == NULL)
1331 goto fail1;
1332 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1333 Py_DECREF(sn_obj);
1334 goto fail1;
1335 }
1336 Py_DECREF(sn_obj);
1337
1338 (void) BIO_reset(biobuf);
1339 notBefore = X509_get_notBefore(certificate);
1340 ASN1_TIME_print(biobuf, notBefore);
1341 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1342 if (len < 0) {
1343 _setSSLError(NULL, 0, __FILE__, __LINE__);
1344 goto fail1;
1345 }
1346 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1347 if (pnotBefore == NULL)
1348 goto fail1;
1349 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1350 Py_DECREF(pnotBefore);
1351 goto fail1;
1352 }
1353 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001354
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001355 (void) BIO_reset(biobuf);
1356 notAfter = X509_get_notAfter(certificate);
1357 ASN1_TIME_print(biobuf, notAfter);
1358 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1359 if (len < 0) {
1360 _setSSLError(NULL, 0, __FILE__, __LINE__);
1361 goto fail1;
1362 }
1363 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1364 if (pnotAfter == NULL)
1365 goto fail1;
1366 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1367 Py_DECREF(pnotAfter);
1368 goto fail1;
1369 }
1370 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001371
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001372 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001373
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001374 peer_alt_names = _get_peer_alt_names(certificate);
1375 if (peer_alt_names == NULL)
1376 goto fail1;
1377 else if (peer_alt_names != Py_None) {
1378 if (PyDict_SetItemString(retval, "subjectAltName",
1379 peer_alt_names) < 0) {
1380 Py_DECREF(peer_alt_names);
1381 goto fail1;
1382 }
1383 Py_DECREF(peer_alt_names);
1384 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001385
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001386 /* Authority Information Access: OCSP URIs */
1387 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1388 if (obj == NULL) {
1389 goto fail1;
1390 } else if (obj != Py_None) {
1391 result = PyDict_SetItemString(retval, "OCSP", obj);
1392 Py_DECREF(obj);
1393 if (result < 0) {
1394 goto fail1;
1395 }
1396 }
1397
1398 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1399 if (obj == NULL) {
1400 goto fail1;
1401 } else if (obj != Py_None) {
1402 result = PyDict_SetItemString(retval, "caIssuers", obj);
1403 Py_DECREF(obj);
1404 if (result < 0) {
1405 goto fail1;
1406 }
1407 }
1408
1409 /* CDP (CRL distribution points) */
1410 obj = _get_crl_dp(certificate);
1411 if (obj == NULL) {
1412 goto fail1;
1413 } else if (obj != Py_None) {
1414 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1415 Py_DECREF(obj);
1416 if (result < 0) {
1417 goto fail1;
1418 }
1419 }
1420
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001421 BIO_free(biobuf);
1422 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001423
1424 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001425 if (biobuf != NULL)
1426 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001427 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001428 Py_XDECREF(retval);
1429 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001430}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001431
Christian Heimes9a5395a2013-06-17 15:44:12 +02001432static PyObject *
1433_certificate_to_der(X509 *certificate)
1434{
1435 unsigned char *bytes_buf = NULL;
1436 int len;
1437 PyObject *retval;
1438
1439 bytes_buf = NULL;
1440 len = i2d_X509(certificate, &bytes_buf);
1441 if (len < 0) {
1442 _setSSLError(NULL, 0, __FILE__, __LINE__);
1443 return NULL;
1444 }
1445 /* this is actually an immutable bytes sequence */
1446 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1447 OPENSSL_free(bytes_buf);
1448 return retval;
1449}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001450
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001451/*[clinic input]
1452_ssl._test_decode_cert
1453 path: object(converter="PyUnicode_FSConverter")
1454 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001455
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001456[clinic start generated code]*/
1457
1458static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001459_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1460/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001461{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001462 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001463 X509 *x=NULL;
1464 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001465
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001466 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1467 PyErr_SetString(PySSLErrorObject,
1468 "Can't malloc memory to read file");
1469 goto fail0;
1470 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001471
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001472 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001473 PyErr_SetString(PySSLErrorObject,
1474 "Can't open file");
1475 goto fail0;
1476 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001477
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001478 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1479 if (x == NULL) {
1480 PyErr_SetString(PySSLErrorObject,
1481 "Error decoding PEM-encoded file");
1482 goto fail0;
1483 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001484
Antoine Pitroufb046912010-11-09 20:21:19 +00001485 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001486 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001487
1488 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001489 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001490 if (cert != NULL) BIO_free(cert);
1491 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001492}
1493
1494
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001495/*[clinic input]
1496_ssl._SSLSocket.peer_certificate
1497 der as binary_mode: bool = False
1498 /
1499
1500Returns the certificate for the peer.
1501
1502If no certificate was provided, returns None. If a certificate was
1503provided, but not validated, returns an empty dictionary. Otherwise
1504returns a dict containing information about the peer certificate.
1505
1506If the optional argument is True, returns a DER-encoded copy of the
1507peer certificate, or None if no certificate was provided. This will
1508return the certificate even if it wasn't validated.
1509[clinic start generated code]*/
1510
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001511static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001512_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1513/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001514{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001515 int verification;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001516
Antoine Pitrou20b85552013-09-29 19:50:53 +02001517 if (!self->handshake_done) {
1518 PyErr_SetString(PyExc_ValueError,
1519 "handshake not done yet");
1520 return NULL;
1521 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522 if (!self->peer_cert)
1523 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001524
Antoine Pitrou721738f2012-08-15 23:20:39 +02001525 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001526 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001527 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001529 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001530 if ((verification & SSL_VERIFY_PEER) == 0)
1531 return PyDict_New();
1532 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001533 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001534 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001535}
1536
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001537static PyObject *
1538cipher_to_tuple(const SSL_CIPHER *cipher)
1539{
1540 const char *cipher_name, *cipher_protocol;
1541 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001542 if (retval == NULL)
1543 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001544
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001545 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001546 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001547 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001548 PyTuple_SET_ITEM(retval, 0, Py_None);
1549 } else {
1550 v = PyUnicode_FromString(cipher_name);
1551 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001552 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001553 PyTuple_SET_ITEM(retval, 0, v);
1554 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001555
1556 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001557 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001558 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001559 PyTuple_SET_ITEM(retval, 1, Py_None);
1560 } else {
1561 v = PyUnicode_FromString(cipher_protocol);
1562 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001563 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001564 PyTuple_SET_ITEM(retval, 1, v);
1565 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001566
1567 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001569 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001570 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001571
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001572 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001573
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001574 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001575 Py_DECREF(retval);
1576 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001577}
1578
Christian Heimes25bfcd52016-09-06 00:04:45 +02001579#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1580static PyObject *
1581cipher_to_dict(const SSL_CIPHER *cipher)
1582{
1583 const char *cipher_name, *cipher_protocol;
1584
1585 unsigned long cipher_id;
1586 int alg_bits, strength_bits, len;
1587 char buf[512] = {0};
1588#if OPENSSL_VERSION_1_1
1589 int aead, nid;
1590 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1591#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001592
1593 /* can be NULL */
1594 cipher_name = SSL_CIPHER_get_name(cipher);
1595 cipher_protocol = SSL_CIPHER_get_version(cipher);
1596 cipher_id = SSL_CIPHER_get_id(cipher);
1597 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1598 len = strlen(buf);
1599 if (len > 1 && buf[len-1] == '\n')
1600 buf[len-1] = '\0';
1601 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1602
1603#if OPENSSL_VERSION_1_1
1604 aead = SSL_CIPHER_is_aead(cipher);
1605 nid = SSL_CIPHER_get_cipher_nid(cipher);
1606 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1607 nid = SSL_CIPHER_get_digest_nid(cipher);
1608 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1609 nid = SSL_CIPHER_get_kx_nid(cipher);
1610 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1611 nid = SSL_CIPHER_get_auth_nid(cipher);
1612 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1613#endif
1614
Victor Stinner410b9882016-09-12 12:00:23 +02001615 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001616 "{sksssssssisi"
1617#if OPENSSL_VERSION_1_1
1618 "sOssssssss"
1619#endif
1620 "}",
1621 "id", cipher_id,
1622 "name", cipher_name,
1623 "protocol", cipher_protocol,
1624 "description", buf,
1625 "strength_bits", strength_bits,
1626 "alg_bits", alg_bits
1627#if OPENSSL_VERSION_1_1
1628 ,"aead", aead ? Py_True : Py_False,
1629 "symmetric", skcipher,
1630 "digest", digest,
1631 "kea", kx,
1632 "auth", auth
1633#endif
1634 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001635}
1636#endif
1637
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001638/*[clinic input]
1639_ssl._SSLSocket.shared_ciphers
1640[clinic start generated code]*/
1641
1642static PyObject *
1643_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1644/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001645{
1646 STACK_OF(SSL_CIPHER) *ciphers;
1647 int i;
1648 PyObject *res;
1649
Christian Heimes598894f2016-09-05 23:19:05 +02001650 ciphers = SSL_get_ciphers(self->ssl);
1651 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001652 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001653 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1654 if (!res)
1655 return NULL;
1656 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1657 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1658 if (!tup) {
1659 Py_DECREF(res);
1660 return NULL;
1661 }
1662 PyList_SET_ITEM(res, i, tup);
1663 }
1664 return res;
1665}
1666
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001667/*[clinic input]
1668_ssl._SSLSocket.cipher
1669[clinic start generated code]*/
1670
1671static PyObject *
1672_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1673/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001674{
1675 const SSL_CIPHER *current;
1676
1677 if (self->ssl == NULL)
1678 Py_RETURN_NONE;
1679 current = SSL_get_current_cipher(self->ssl);
1680 if (current == NULL)
1681 Py_RETURN_NONE;
1682 return cipher_to_tuple(current);
1683}
1684
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001685/*[clinic input]
1686_ssl._SSLSocket.version
1687[clinic start generated code]*/
1688
1689static PyObject *
1690_ssl__SSLSocket_version_impl(PySSLSocket *self)
1691/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001692{
1693 const char *version;
1694
1695 if (self->ssl == NULL)
1696 Py_RETURN_NONE;
1697 version = SSL_get_version(self->ssl);
1698 if (!strcmp(version, "unknown"))
1699 Py_RETURN_NONE;
1700 return PyUnicode_FromString(version);
1701}
1702
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001703#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001704/*[clinic input]
1705_ssl._SSLSocket.selected_npn_protocol
1706[clinic start generated code]*/
1707
1708static PyObject *
1709_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1710/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1711{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001712 const unsigned char *out;
1713 unsigned int outlen;
1714
Victor Stinner4569cd52013-06-23 14:58:43 +02001715 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001716 &out, &outlen);
1717
1718 if (out == NULL)
1719 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001720 return PyUnicode_FromStringAndSize((char *)out, outlen);
1721}
1722#endif
1723
1724#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001725/*[clinic input]
1726_ssl._SSLSocket.selected_alpn_protocol
1727[clinic start generated code]*/
1728
1729static PyObject *
1730_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1731/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1732{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001733 const unsigned char *out;
1734 unsigned int outlen;
1735
1736 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1737
1738 if (out == NULL)
1739 Py_RETURN_NONE;
1740 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001741}
1742#endif
1743
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001744/*[clinic input]
1745_ssl._SSLSocket.compression
1746[clinic start generated code]*/
1747
1748static PyObject *
1749_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1750/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1751{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001752#ifdef OPENSSL_NO_COMP
1753 Py_RETURN_NONE;
1754#else
1755 const COMP_METHOD *comp_method;
1756 const char *short_name;
1757
1758 if (self->ssl == NULL)
1759 Py_RETURN_NONE;
1760 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001761 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001762 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001763 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001764 if (short_name == NULL)
1765 Py_RETURN_NONE;
1766 return PyUnicode_DecodeFSDefault(short_name);
1767#endif
1768}
1769
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001770static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1771 Py_INCREF(self->ctx);
1772 return self->ctx;
1773}
1774
1775static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1776 void *closure) {
1777
1778 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001779#if !HAVE_SNI
1780 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1781 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001782 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001783#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001784 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001785 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001786 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001787#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001788 } else {
1789 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1790 return -1;
1791 }
1792
1793 return 0;
1794}
1795
1796PyDoc_STRVAR(PySSL_set_context_doc,
1797"_setter_context(ctx)\n\
1798\
1799This changes the context associated with the SSLSocket. This is typically\n\
1800used from within a callback function set by the set_servername_callback\n\
1801on the SSLContext to change the certificate information associated with the\n\
1802SSLSocket before the cryptographic exchange handshake messages\n");
1803
1804
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001805static PyObject *
1806PySSL_get_server_side(PySSLSocket *self, void *c)
1807{
1808 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1809}
1810
1811PyDoc_STRVAR(PySSL_get_server_side_doc,
1812"Whether this is a server-side socket.");
1813
1814static PyObject *
1815PySSL_get_server_hostname(PySSLSocket *self, void *c)
1816{
1817 if (self->server_hostname == NULL)
1818 Py_RETURN_NONE;
1819 Py_INCREF(self->server_hostname);
1820 return self->server_hostname;
1821}
1822
1823PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1824"The currently set server hostname (for SNI).");
1825
1826static PyObject *
1827PySSL_get_owner(PySSLSocket *self, void *c)
1828{
1829 PyObject *owner;
1830
1831 if (self->owner == NULL)
1832 Py_RETURN_NONE;
1833
1834 owner = PyWeakref_GetObject(self->owner);
1835 Py_INCREF(owner);
1836 return owner;
1837}
1838
1839static int
1840PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1841{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001842 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001843 if (self->owner == NULL)
1844 return -1;
1845 return 0;
1846}
1847
1848PyDoc_STRVAR(PySSL_get_owner_doc,
1849"The Python-level owner of this object.\
1850Passed as \"self\" in servername callback.");
1851
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001852
Antoine Pitrou152efa22010-05-16 18:19:27 +00001853static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001854{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001855 if (self->peer_cert) /* Possible not to have one? */
1856 X509_free (self->peer_cert);
1857 if (self->ssl)
1858 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001859 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001860 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001861 Py_XDECREF(self->server_hostname);
1862 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001863 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001864}
1865
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001866/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001867 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001868 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001869 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001870
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001871static int
Victor Stinner14690702015-04-06 22:46:13 +02001872PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001873{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001874 int rc;
1875#ifdef HAVE_POLL
1876 struct pollfd pollfd;
1877 _PyTime_t ms;
1878#else
1879 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001880 fd_set fds;
1881 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001882#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001883
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001884 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001885 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001886 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001887 else if (timeout < 0) {
1888 if (s->sock_timeout > 0)
1889 return SOCKET_HAS_TIMED_OUT;
1890 else
1891 return SOCKET_IS_BLOCKING;
1892 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001893
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001894 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001895 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001896 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001897
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001898 /* Prefer poll, if available, since you can poll() any fd
1899 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001900#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001901 pollfd.fd = s->sock_fd;
1902 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001903
Victor Stinner14690702015-04-06 22:46:13 +02001904 /* timeout is in seconds, poll() uses milliseconds */
1905 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001906 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001907
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001908 PySSL_BEGIN_ALLOW_THREADS
1909 rc = poll(&pollfd, 1, (int)ms);
1910 PySSL_END_ALLOW_THREADS
1911#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001912 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001913 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001914 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001915
Victor Stinner14690702015-04-06 22:46:13 +02001916 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001917
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001918 FD_ZERO(&fds);
1919 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001920
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001921 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001922 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001923 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001924 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001925 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001926 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001927 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001928 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001929#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001930
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001931 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1932 (when we are able to write or when there's something to read) */
1933 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001934}
1935
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001936/*[clinic input]
1937_ssl._SSLSocket.write
1938 b: Py_buffer
1939 /
1940
1941Writes the bytes-like object b into the SSL object.
1942
1943Returns the number of bytes written.
1944[clinic start generated code]*/
1945
1946static PyObject *
1947_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1948/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001949{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001950 int len;
1951 int sockstate;
1952 int err;
1953 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001954 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001955 _PyTime_t timeout, deadline = 0;
1956 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001957
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001958 if (sock != NULL) {
1959 if (((PyObject*)sock) == Py_None) {
1960 _setSSLError("Underlying socket connection gone",
1961 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1962 return NULL;
1963 }
1964 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001965 }
1966
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001967 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001968 PyErr_Format(PyExc_OverflowError,
1969 "string longer than %d bytes", INT_MAX);
1970 goto error;
1971 }
1972
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001973 if (sock != NULL) {
1974 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001975 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001976 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1977 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1978 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001979
Victor Stinner14690702015-04-06 22:46:13 +02001980 timeout = GET_SOCKET_TIMEOUT(sock);
1981 has_timeout = (timeout > 0);
1982 if (has_timeout)
1983 deadline = _PyTime_GetMonotonicClock() + timeout;
1984
1985 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001986 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001987 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001988 "The write operation timed out");
1989 goto error;
1990 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1991 PyErr_SetString(PySSLErrorObject,
1992 "Underlying socket has been closed.");
1993 goto error;
1994 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1995 PyErr_SetString(PySSLErrorObject,
1996 "Underlying socket too large for select().");
1997 goto error;
1998 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001999
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002000 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002001 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002002 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002003 err = SSL_get_error(self->ssl, len);
2004 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002005
2006 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002007 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002008
Victor Stinner14690702015-04-06 22:46:13 +02002009 if (has_timeout)
2010 timeout = deadline - _PyTime_GetMonotonicClock();
2011
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002012 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002013 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002014 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002015 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002016 } else {
2017 sockstate = SOCKET_OPERATION_OK;
2018 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002019
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002020 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002021 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002022 "The write operation timed out");
2023 goto error;
2024 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2025 PyErr_SetString(PySSLErrorObject,
2026 "Underlying socket has been closed.");
2027 goto error;
2028 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2029 break;
2030 }
2031 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002032
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002033 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002034 if (len > 0)
2035 return PyLong_FromLong(len);
2036 else
2037 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002038
2039error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002040 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002041 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002042}
2043
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002044/*[clinic input]
2045_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002046
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002047Returns the number of already decrypted bytes available for read, pending on the connection.
2048[clinic start generated code]*/
2049
2050static PyObject *
2051_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2052/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002053{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002054 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002055
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002056 PySSL_BEGIN_ALLOW_THREADS
2057 count = SSL_pending(self->ssl);
2058 PySSL_END_ALLOW_THREADS
2059 if (count < 0)
2060 return PySSL_SetError(self, count, __FILE__, __LINE__);
2061 else
2062 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002063}
2064
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002065/*[clinic input]
2066_ssl._SSLSocket.read
2067 size as len: int
2068 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002069 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002070 ]
2071 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002072
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002073Read up to size bytes from the SSL socket.
2074[clinic start generated code]*/
2075
2076static PyObject *
2077_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2078 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002079/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002080{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002081 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002082 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002083 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002084 int sockstate;
2085 int err;
2086 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002087 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002088 _PyTime_t timeout, deadline = 0;
2089 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002090
Martin Panter5503d472016-03-27 05:35:19 +00002091 if (!group_right_1 && len < 0) {
2092 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2093 return NULL;
2094 }
2095
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002096 if (sock != NULL) {
2097 if (((PyObject*)sock) == Py_None) {
2098 _setSSLError("Underlying socket connection gone",
2099 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2100 return NULL;
2101 }
2102 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002103 }
2104
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002105 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002106 dest = PyBytes_FromStringAndSize(NULL, len);
2107 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002108 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002109 if (len == 0) {
2110 Py_XDECREF(sock);
2111 return dest;
2112 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002113 mem = PyBytes_AS_STRING(dest);
2114 }
2115 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002116 mem = buffer->buf;
2117 if (len <= 0 || len > buffer->len) {
2118 len = (int) buffer->len;
2119 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002120 PyErr_SetString(PyExc_OverflowError,
2121 "maximum length can't fit in a C 'int'");
2122 goto error;
2123 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002124 if (len == 0) {
2125 count = 0;
2126 goto done;
2127 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002128 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002129 }
2130
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002131 if (sock != NULL) {
2132 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002133 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002134 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2135 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2136 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002137
Victor Stinner14690702015-04-06 22:46:13 +02002138 timeout = GET_SOCKET_TIMEOUT(sock);
2139 has_timeout = (timeout > 0);
2140 if (has_timeout)
2141 deadline = _PyTime_GetMonotonicClock() + timeout;
2142
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002143 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002144 PySSL_BEGIN_ALLOW_THREADS
2145 count = SSL_read(self->ssl, mem, len);
2146 err = SSL_get_error(self->ssl, count);
2147 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002148
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002149 if (PyErr_CheckSignals())
2150 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002151
Victor Stinner14690702015-04-06 22:46:13 +02002152 if (has_timeout)
2153 timeout = deadline - _PyTime_GetMonotonicClock();
2154
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002155 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002156 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002157 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002158 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002159 } else if (err == SSL_ERROR_ZERO_RETURN &&
2160 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002161 {
2162 count = 0;
2163 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002164 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002165 else
2166 sockstate = SOCKET_OPERATION_OK;
2167
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002168 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002169 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002170 "The read operation timed out");
2171 goto error;
2172 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2173 break;
2174 }
2175 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002176
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002177 if (count <= 0) {
2178 PySSL_SetError(self, count, __FILE__, __LINE__);
2179 goto error;
2180 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002181
2182done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002183 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002184 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002185 _PyBytes_Resize(&dest, count);
2186 return dest;
2187 }
2188 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002189 return PyLong_FromLong(count);
2190 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002191
2192error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002193 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002194 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002195 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002196 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002197}
2198
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002199/*[clinic input]
2200_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002201
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002202Does the SSL shutdown handshake with the remote end.
2203
2204Returns the underlying socket object.
2205[clinic start generated code]*/
2206
2207static PyObject *
2208_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2209/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002210{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002211 int err, ssl_err, sockstate, nonblocking;
2212 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002213 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002214 _PyTime_t timeout, deadline = 0;
2215 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002216
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002217 if (sock != NULL) {
2218 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002219 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002220 _setSSLError("Underlying socket connection gone",
2221 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2222 return NULL;
2223 }
2224 Py_INCREF(sock);
2225
2226 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002227 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002228 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2229 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002230 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002231
Victor Stinner14690702015-04-06 22:46:13 +02002232 timeout = GET_SOCKET_TIMEOUT(sock);
2233 has_timeout = (timeout > 0);
2234 if (has_timeout)
2235 deadline = _PyTime_GetMonotonicClock() + timeout;
2236
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002237 while (1) {
2238 PySSL_BEGIN_ALLOW_THREADS
2239 /* Disable read-ahead so that unwrap can work correctly.
2240 * Otherwise OpenSSL might read in too much data,
2241 * eating clear text data that happens to be
2242 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002243 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002244 * function is used and the shutdown_seen_zero != 0
2245 * condition is met.
2246 */
2247 if (self->shutdown_seen_zero)
2248 SSL_set_read_ahead(self->ssl, 0);
2249 err = SSL_shutdown(self->ssl);
2250 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002251
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002252 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2253 if (err > 0)
2254 break;
2255 if (err == 0) {
2256 /* Don't loop endlessly; instead preserve legacy
2257 behaviour of trying SSL_shutdown() only twice.
2258 This looks necessary for OpenSSL < 0.9.8m */
2259 if (++zeros > 1)
2260 break;
2261 /* Shutdown was sent, now try receiving */
2262 self->shutdown_seen_zero = 1;
2263 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002264 }
2265
Victor Stinner14690702015-04-06 22:46:13 +02002266 if (has_timeout)
2267 timeout = deadline - _PyTime_GetMonotonicClock();
2268
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002269 /* Possibly retry shutdown until timeout or failure */
2270 ssl_err = SSL_get_error(self->ssl, err);
2271 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002272 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002273 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002274 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002275 else
2276 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002278 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2279 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002280 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002281 "The read operation timed out");
2282 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002283 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002284 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002285 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002286 }
2287 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2288 PyErr_SetString(PySSLErrorObject,
2289 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002290 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002291 }
2292 else if (sockstate != SOCKET_OPERATION_OK)
2293 /* Retain the SSL error code */
2294 break;
2295 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002296
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002297 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002298 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002299 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002300 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002301 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002302 /* It's already INCREF'ed */
2303 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002304 else
2305 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002306
2307error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002308 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002309 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002310}
2311
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002312/*[clinic input]
2313_ssl._SSLSocket.tls_unique_cb
2314
2315Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2316
2317If the TLS handshake is not yet complete, None is returned.
2318[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002319
Antoine Pitroud6494802011-07-21 01:11:30 +02002320static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002321_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2322/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002323{
2324 PyObject *retval = NULL;
2325 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002326 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002327
2328 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2329 /* if session is resumed XOR we are the client */
2330 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2331 }
2332 else {
2333 /* if a new session XOR we are the server */
2334 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2335 }
2336
2337 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002338 if (len == 0)
2339 Py_RETURN_NONE;
2340
2341 retval = PyBytes_FromStringAndSize(buf, len);
2342
2343 return retval;
2344}
2345
Christian Heimes99a65702016-09-10 23:44:53 +02002346#ifdef OPENSSL_VERSION_1_1
2347
2348static SSL_SESSION*
2349_ssl_session_dup(SSL_SESSION *session) {
2350 SSL_SESSION *newsession = NULL;
2351 int slen;
2352 unsigned char *senc = NULL, *p;
2353 const unsigned char *const_p;
2354
2355 if (session == NULL) {
2356 PyErr_SetString(PyExc_ValueError, "Invalid session");
2357 goto error;
2358 }
2359
2360 /* get length */
2361 slen = i2d_SSL_SESSION(session, NULL);
2362 if (slen == 0 || slen > 0xFF00) {
2363 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2364 goto error;
2365 }
2366 if ((senc = PyMem_Malloc(slen)) == NULL) {
2367 PyErr_NoMemory();
2368 goto error;
2369 }
2370 p = senc;
2371 if (!i2d_SSL_SESSION(session, &p)) {
2372 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2373 goto error;
2374 }
2375 const_p = senc;
2376 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2377 if (session == NULL) {
2378 goto error;
2379 }
2380 PyMem_Free(senc);
2381 return newsession;
2382 error:
2383 if (senc != NULL) {
2384 PyMem_Free(senc);
2385 }
2386 return NULL;
2387}
2388#endif
2389
2390static PyObject *
2391PySSL_get_session(PySSLSocket *self, void *closure) {
2392 /* get_session can return sessions from a server-side connection,
2393 * it does not check for handshake done or client socket. */
2394 PySSLSession *pysess;
2395 SSL_SESSION *session;
2396
2397#ifdef OPENSSL_VERSION_1_1
2398 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2399 * https://github.com/openssl/openssl/issues/1550 */
2400 session = SSL_get0_session(self->ssl); /* borrowed reference */
2401 if (session == NULL) {
2402 Py_RETURN_NONE;
2403 }
2404 if ((session = _ssl_session_dup(session)) == NULL) {
2405 return NULL;
2406 }
2407#else
2408 session = SSL_get1_session(self->ssl);
2409 if (session == NULL) {
2410 Py_RETURN_NONE;
2411 }
2412#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002413 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002414 if (pysess == NULL) {
2415 SSL_SESSION_free(session);
2416 return NULL;
2417 }
2418
2419 assert(self->ctx);
2420 pysess->ctx = self->ctx;
2421 Py_INCREF(pysess->ctx);
2422 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002423 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002424 return (PyObject *)pysess;
2425}
2426
2427static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2428 void *closure)
2429 {
2430 PySSLSession *pysess;
2431#ifdef OPENSSL_VERSION_1_1
2432 SSL_SESSION *session;
2433#endif
2434 int result;
2435
2436 if (!PySSLSession_Check(value)) {
2437 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2438 return -1;
2439 }
2440 pysess = (PySSLSession *)value;
2441
2442 if (self->ctx->ctx != pysess->ctx->ctx) {
2443 PyErr_SetString(PyExc_ValueError,
2444 "Session refers to a different SSLContext.");
2445 return -1;
2446 }
2447 if (self->socket_type != PY_SSL_CLIENT) {
2448 PyErr_SetString(PyExc_ValueError,
2449 "Cannot set session for server-side SSLSocket.");
2450 return -1;
2451 }
2452 if (self->handshake_done) {
2453 PyErr_SetString(PyExc_ValueError,
2454 "Cannot set session after handshake.");
2455 return -1;
2456 }
2457#ifdef OPENSSL_VERSION_1_1
2458 /* duplicate session */
2459 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2460 return -1;
2461 }
2462 result = SSL_set_session(self->ssl, session);
2463 /* free duplicate, SSL_set_session() bumps ref count */
2464 SSL_SESSION_free(session);
2465#else
2466 result = SSL_set_session(self->ssl, pysess->session);
2467#endif
2468 if (result == 0) {
2469 _setSSLError(NULL, 0, __FILE__, __LINE__);
2470 return -1;
2471 }
2472 return 0;
2473}
2474
2475PyDoc_STRVAR(PySSL_set_session_doc,
2476"_setter_session(session)\n\
2477\
2478Get / set SSLSession.");
2479
2480static PyObject *
2481PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2482 if (SSL_session_reused(self->ssl)) {
2483 Py_RETURN_TRUE;
2484 } else {
2485 Py_RETURN_FALSE;
2486 }
2487}
2488
2489PyDoc_STRVAR(PySSL_get_session_reused_doc,
2490"Was the client session reused during handshake?");
2491
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002492static PyGetSetDef ssl_getsetlist[] = {
2493 {"context", (getter) PySSL_get_context,
2494 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002495 {"server_side", (getter) PySSL_get_server_side, NULL,
2496 PySSL_get_server_side_doc},
2497 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2498 PySSL_get_server_hostname_doc},
2499 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2500 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002501 {"session", (getter) PySSL_get_session,
2502 (setter) PySSL_set_session, PySSL_set_session_doc},
2503 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2504 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002505 {NULL}, /* sentinel */
2506};
2507
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002508static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002509 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2510 _SSL__SSLSOCKET_WRITE_METHODDEF
2511 _SSL__SSLSOCKET_READ_METHODDEF
2512 _SSL__SSLSOCKET_PENDING_METHODDEF
2513 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2514 _SSL__SSLSOCKET_CIPHER_METHODDEF
2515 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2516 _SSL__SSLSOCKET_VERSION_METHODDEF
2517 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2518 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2519 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2520 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2521 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002522 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002523};
2524
Antoine Pitrou152efa22010-05-16 18:19:27 +00002525static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002526 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002527 "_ssl._SSLSocket", /*tp_name*/
2528 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002529 0, /*tp_itemsize*/
2530 /* methods */
2531 (destructor)PySSL_dealloc, /*tp_dealloc*/
2532 0, /*tp_print*/
2533 0, /*tp_getattr*/
2534 0, /*tp_setattr*/
2535 0, /*tp_reserved*/
2536 0, /*tp_repr*/
2537 0, /*tp_as_number*/
2538 0, /*tp_as_sequence*/
2539 0, /*tp_as_mapping*/
2540 0, /*tp_hash*/
2541 0, /*tp_call*/
2542 0, /*tp_str*/
2543 0, /*tp_getattro*/
2544 0, /*tp_setattro*/
2545 0, /*tp_as_buffer*/
2546 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2547 0, /*tp_doc*/
2548 0, /*tp_traverse*/
2549 0, /*tp_clear*/
2550 0, /*tp_richcompare*/
2551 0, /*tp_weaklistoffset*/
2552 0, /*tp_iter*/
2553 0, /*tp_iternext*/
2554 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002555 0, /*tp_members*/
2556 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002557};
2558
Antoine Pitrou152efa22010-05-16 18:19:27 +00002559
2560/*
2561 * _SSLContext objects
2562 */
2563
Christian Heimes5fe668c2016-09-12 00:01:11 +02002564static int
2565_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2566{
2567 int mode;
2568 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2569
2570 switch(n) {
2571 case PY_SSL_CERT_NONE:
2572 mode = SSL_VERIFY_NONE;
2573 break;
2574 case PY_SSL_CERT_OPTIONAL:
2575 mode = SSL_VERIFY_PEER;
2576 break;
2577 case PY_SSL_CERT_REQUIRED:
2578 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2579 break;
2580 default:
2581 PyErr_SetString(PyExc_ValueError,
2582 "invalid value for verify_mode");
2583 return -1;
2584 }
2585 /* keep current verify cb */
2586 verify_cb = SSL_CTX_get_verify_callback(ctx);
2587 SSL_CTX_set_verify(ctx, mode, verify_cb);
2588 return 0;
2589}
2590
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002591/*[clinic input]
2592@classmethod
2593_ssl._SSLContext.__new__
2594 protocol as proto_version: int
2595 /
2596[clinic start generated code]*/
2597
Antoine Pitrou152efa22010-05-16 18:19:27 +00002598static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002599_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2600/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002601{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002602 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002603 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002604 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002605 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002606#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002607 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002608#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002609
Antoine Pitrou152efa22010-05-16 18:19:27 +00002610 PySSL_BEGIN_ALLOW_THREADS
2611 if (proto_version == PY_SSL_VERSION_TLS1)
2612 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002613#if HAVE_TLSv1_2
2614 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2615 ctx = SSL_CTX_new(TLSv1_1_method());
2616 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2617 ctx = SSL_CTX_new(TLSv1_2_method());
2618#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002619#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002620 else if (proto_version == PY_SSL_VERSION_SSL3)
2621 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002622#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002623#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002624 else if (proto_version == PY_SSL_VERSION_SSL2)
2625 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002626#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002627 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002628 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002629 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2630 ctx = SSL_CTX_new(TLS_client_method());
2631 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2632 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002633 else
2634 proto_version = -1;
2635 PySSL_END_ALLOW_THREADS
2636
2637 if (proto_version == -1) {
2638 PyErr_SetString(PyExc_ValueError,
2639 "invalid protocol version");
2640 return NULL;
2641 }
2642 if (ctx == NULL) {
2643 PyErr_SetString(PySSLErrorObject,
2644 "failed to allocate SSL context");
2645 return NULL;
2646 }
2647
2648 assert(type != NULL && type->tp_alloc != NULL);
2649 self = (PySSLContext *) type->tp_alloc(type, 0);
2650 if (self == NULL) {
2651 SSL_CTX_free(ctx);
2652 return NULL;
2653 }
2654 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002655#ifdef OPENSSL_NPN_NEGOTIATED
2656 self->npn_protocols = NULL;
2657#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002658#ifdef HAVE_ALPN
2659 self->alpn_protocols = NULL;
2660#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002661#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002662 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002663#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002664 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002665 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2666 self->check_hostname = 1;
2667 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2668 Py_DECREF(self);
2669 return NULL;
2670 }
2671 } else {
2672 self->check_hostname = 0;
2673 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2674 Py_DECREF(self);
2675 return NULL;
2676 }
2677 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002678 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002679 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2680 if (proto_version != PY_SSL_VERSION_SSL2)
2681 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002682 if (proto_version != PY_SSL_VERSION_SSL3)
2683 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002684 /* Minimal security flags for server and client side context.
2685 * Client sockets ignore server-side parameters. */
2686#ifdef SSL_OP_NO_COMPRESSION
2687 options |= SSL_OP_NO_COMPRESSION;
2688#endif
2689#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2690 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2691#endif
2692#ifdef SSL_OP_SINGLE_DH_USE
2693 options |= SSL_OP_SINGLE_DH_USE;
2694#endif
2695#ifdef SSL_OP_SINGLE_ECDH_USE
2696 options |= SSL_OP_SINGLE_ECDH_USE;
2697#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002698 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002699
Christian Heimes358cfd42016-09-10 22:43:48 +02002700 /* A bare minimum cipher list without completly broken cipher suites.
2701 * It's far from perfect but gives users a better head start. */
2702 if (proto_version != PY_SSL_VERSION_SSL2) {
2703 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2704 } else {
2705 /* SSLv2 needs MD5 */
2706 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2707 }
2708 if (result == 0) {
2709 Py_DECREF(self);
2710 ERR_clear_error();
2711 PyErr_SetString(PySSLErrorObject,
2712 "No cipher can be selected.");
2713 return NULL;
2714 }
2715
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002716#if defined(SSL_MODE_RELEASE_BUFFERS)
2717 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2718 usage for no cost at all. However, don't do this for OpenSSL versions
2719 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2720 2014-0198. I can't find exactly which beta fixed this CVE, so be
2721 conservative and assume it wasn't fixed until release. We do this check
2722 at runtime to avoid problems from the dynamic linker.
2723 See #25672 for more on this. */
2724 libver = SSLeay();
2725 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2726 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2727 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2728 }
2729#endif
2730
2731
Donald Stufft784ba7c2017-03-02 12:32:13 -05002732#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002733 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2734 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002735 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2736 */
Donald Stufft784ba7c2017-03-02 12:32:13 -05002737#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002738 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2739#else
2740 {
2741 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2742 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2743 EC_KEY_free(key);
2744 }
2745#endif
2746#endif
2747
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002748#define SID_CTX "Python"
2749 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2750 sizeof(SID_CTX));
2751#undef SID_CTX
2752
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002753#ifdef X509_V_FLAG_TRUSTED_FIRST
2754 {
2755 /* Improve trust chain building when cross-signed intermediate
2756 certificates are present. See https://bugs.python.org/issue23476. */
2757 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2758 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2759 }
2760#endif
2761
Antoine Pitrou152efa22010-05-16 18:19:27 +00002762 return (PyObject *)self;
2763}
2764
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002765static int
2766context_traverse(PySSLContext *self, visitproc visit, void *arg)
2767{
2768#ifndef OPENSSL_NO_TLSEXT
2769 Py_VISIT(self->set_hostname);
2770#endif
2771 return 0;
2772}
2773
2774static int
2775context_clear(PySSLContext *self)
2776{
2777#ifndef OPENSSL_NO_TLSEXT
2778 Py_CLEAR(self->set_hostname);
2779#endif
2780 return 0;
2781}
2782
Antoine Pitrou152efa22010-05-16 18:19:27 +00002783static void
2784context_dealloc(PySSLContext *self)
2785{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002786 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002787 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002788#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002789 PyMem_FREE(self->npn_protocols);
2790#endif
2791#ifdef HAVE_ALPN
2792 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002793#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002794 Py_TYPE(self)->tp_free(self);
2795}
2796
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002797/*[clinic input]
2798_ssl._SSLContext.set_ciphers
2799 cipherlist: str
2800 /
2801[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002802
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002803static PyObject *
2804_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2805/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2806{
2807 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002808 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002809 /* Clearing the error queue is necessary on some OpenSSL versions,
2810 otherwise the error will be reported again when another SSL call
2811 is done. */
2812 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002813 PyErr_SetString(PySSLErrorObject,
2814 "No cipher can be selected.");
2815 return NULL;
2816 }
2817 Py_RETURN_NONE;
2818}
2819
Christian Heimes25bfcd52016-09-06 00:04:45 +02002820#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2821/*[clinic input]
2822_ssl._SSLContext.get_ciphers
2823[clinic start generated code]*/
2824
2825static PyObject *
2826_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2827/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2828{
2829 SSL *ssl = NULL;
2830 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002831 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002832 int i=0;
2833 PyObject *result = NULL, *dct;
2834
2835 ssl = SSL_new(self->ctx);
2836 if (ssl == NULL) {
2837 _setSSLError(NULL, 0, __FILE__, __LINE__);
2838 goto exit;
2839 }
2840 sk = SSL_get_ciphers(ssl);
2841
2842 result = PyList_New(sk_SSL_CIPHER_num(sk));
2843 if (result == NULL) {
2844 goto exit;
2845 }
2846
2847 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2848 cipher = sk_SSL_CIPHER_value(sk, i);
2849 dct = cipher_to_dict(cipher);
2850 if (dct == NULL) {
2851 Py_CLEAR(result);
2852 goto exit;
2853 }
2854 PyList_SET_ITEM(result, i, dct);
2855 }
2856
2857 exit:
2858 if (ssl != NULL)
2859 SSL_free(ssl);
2860 return result;
2861
2862}
2863#endif
2864
2865
Benjamin Petersonc54de472015-01-28 12:06:39 -05002866#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002867static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002868do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2869 const unsigned char *server_protocols, unsigned int server_protocols_len,
2870 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002871{
Benjamin Peterson88615022015-01-23 17:30:26 -05002872 int ret;
2873 if (client_protocols == NULL) {
2874 client_protocols = (unsigned char *)"";
2875 client_protocols_len = 0;
2876 }
2877 if (server_protocols == NULL) {
2878 server_protocols = (unsigned char *)"";
2879 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002880 }
2881
Benjamin Peterson88615022015-01-23 17:30:26 -05002882 ret = SSL_select_next_proto(out, outlen,
2883 server_protocols, server_protocols_len,
2884 client_protocols, client_protocols_len);
2885 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2886 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002887
2888 return SSL_TLSEXT_ERR_OK;
2889}
2890
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002891/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2892static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002893_advertiseNPN_cb(SSL *s,
2894 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002895 void *args)
2896{
2897 PySSLContext *ssl_ctx = (PySSLContext *) args;
2898
2899 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002900 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002901 *len = 0;
2902 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002903 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002904 *len = ssl_ctx->npn_protocols_len;
2905 }
2906
2907 return SSL_TLSEXT_ERR_OK;
2908}
2909/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2910static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002911_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002912 unsigned char **out, unsigned char *outlen,
2913 const unsigned char *server, unsigned int server_len,
2914 void *args)
2915{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002916 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002917 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002918 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002919}
2920#endif
2921
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002922/*[clinic input]
2923_ssl._SSLContext._set_npn_protocols
2924 protos: Py_buffer
2925 /
2926[clinic start generated code]*/
2927
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002928static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002929_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2930 Py_buffer *protos)
2931/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002932{
2933#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002934 PyMem_Free(self->npn_protocols);
2935 self->npn_protocols = PyMem_Malloc(protos->len);
2936 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002937 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002938 memcpy(self->npn_protocols, protos->buf, protos->len);
2939 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002940
2941 /* set both server and client callbacks, because the context can
2942 * be used to create both types of sockets */
2943 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2944 _advertiseNPN_cb,
2945 self);
2946 SSL_CTX_set_next_proto_select_cb(self->ctx,
2947 _selectNPN_cb,
2948 self);
2949
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002950 Py_RETURN_NONE;
2951#else
2952 PyErr_SetString(PyExc_NotImplementedError,
2953 "The NPN extension requires OpenSSL 1.0.1 or later.");
2954 return NULL;
2955#endif
2956}
2957
Benjamin Petersoncca27322015-01-23 16:35:37 -05002958#ifdef HAVE_ALPN
2959static int
2960_selectALPN_cb(SSL *s,
2961 const unsigned char **out, unsigned char *outlen,
2962 const unsigned char *client_protocols, unsigned int client_protocols_len,
2963 void *args)
2964{
2965 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002966 return do_protocol_selection(1, (unsigned char **)out, outlen,
2967 ctx->alpn_protocols, ctx->alpn_protocols_len,
2968 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002969}
2970#endif
2971
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002972/*[clinic input]
2973_ssl._SSLContext._set_alpn_protocols
2974 protos: Py_buffer
2975 /
2976[clinic start generated code]*/
2977
Benjamin Petersoncca27322015-01-23 16:35:37 -05002978static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002979_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2980 Py_buffer *protos)
2981/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002982{
2983#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002984 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002985 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002986 if (!self->alpn_protocols)
2987 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002988 memcpy(self->alpn_protocols, protos->buf, protos->len);
2989 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002990
2991 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2992 return PyErr_NoMemory();
2993 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2994
Benjamin Petersoncca27322015-01-23 16:35:37 -05002995 Py_RETURN_NONE;
2996#else
2997 PyErr_SetString(PyExc_NotImplementedError,
2998 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2999 return NULL;
3000#endif
3001}
3002
Antoine Pitrou152efa22010-05-16 18:19:27 +00003003static PyObject *
3004get_verify_mode(PySSLContext *self, void *c)
3005{
3006 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3007 case SSL_VERIFY_NONE:
3008 return PyLong_FromLong(PY_SSL_CERT_NONE);
3009 case SSL_VERIFY_PEER:
3010 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3011 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3012 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3013 }
3014 PyErr_SetString(PySSLErrorObject,
3015 "invalid return value from SSL_CTX_get_verify_mode");
3016 return NULL;
3017}
3018
3019static int
3020set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3021{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003022 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003023 if (!PyArg_Parse(arg, "i", &n))
3024 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003025 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003026 PyErr_SetString(PyExc_ValueError,
3027 "Cannot set verify_mode to CERT_NONE when "
3028 "check_hostname is enabled.");
3029 return -1;
3030 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003031 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003032}
3033
3034static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003035get_verify_flags(PySSLContext *self, void *c)
3036{
3037 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003038 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003039 unsigned long flags;
3040
3041 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003042 param = X509_STORE_get0_param(store);
3043 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003044 return PyLong_FromUnsignedLong(flags);
3045}
3046
3047static int
3048set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3049{
3050 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003051 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003052 unsigned long new_flags, flags, set, clear;
3053
3054 if (!PyArg_Parse(arg, "k", &new_flags))
3055 return -1;
3056 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003057 param = X509_STORE_get0_param(store);
3058 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003059 clear = flags & ~new_flags;
3060 set = ~flags & new_flags;
3061 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003062 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003063 _setSSLError(NULL, 0, __FILE__, __LINE__);
3064 return -1;
3065 }
3066 }
3067 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003068 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003069 _setSSLError(NULL, 0, __FILE__, __LINE__);
3070 return -1;
3071 }
3072 }
3073 return 0;
3074}
3075
3076static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003077get_options(PySSLContext *self, void *c)
3078{
3079 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3080}
3081
3082static int
3083set_options(PySSLContext *self, PyObject *arg, void *c)
3084{
3085 long new_opts, opts, set, clear;
3086 if (!PyArg_Parse(arg, "l", &new_opts))
3087 return -1;
3088 opts = SSL_CTX_get_options(self->ctx);
3089 clear = opts & ~new_opts;
3090 set = ~opts & new_opts;
3091 if (clear) {
3092#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3093 SSL_CTX_clear_options(self->ctx, clear);
3094#else
3095 PyErr_SetString(PyExc_ValueError,
3096 "can't clear options before OpenSSL 0.9.8m");
3097 return -1;
3098#endif
3099 }
3100 if (set)
3101 SSL_CTX_set_options(self->ctx, set);
3102 return 0;
3103}
3104
Christian Heimes1aa9a752013-12-02 02:41:19 +01003105static PyObject *
3106get_check_hostname(PySSLContext *self, void *c)
3107{
3108 return PyBool_FromLong(self->check_hostname);
3109}
3110
3111static int
3112set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3113{
3114 int check_hostname;
3115 if (!PyArg_Parse(arg, "p", &check_hostname))
3116 return -1;
3117 if (check_hostname &&
3118 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3119 PyErr_SetString(PyExc_ValueError,
3120 "check_hostname needs a SSL context with either "
3121 "CERT_OPTIONAL or CERT_REQUIRED");
3122 return -1;
3123 }
3124 self->check_hostname = check_hostname;
3125 return 0;
3126}
3127
3128
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003129typedef struct {
3130 PyThreadState *thread_state;
3131 PyObject *callable;
3132 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003133 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003134 int error;
3135} _PySSLPasswordInfo;
3136
3137static int
3138_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3139 const char *bad_type_error)
3140{
3141 /* Set the password and size fields of a _PySSLPasswordInfo struct
3142 from a unicode, bytes, or byte array object.
3143 The password field will be dynamically allocated and must be freed
3144 by the caller */
3145 PyObject *password_bytes = NULL;
3146 const char *data = NULL;
3147 Py_ssize_t size;
3148
3149 if (PyUnicode_Check(password)) {
3150 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3151 if (!password_bytes) {
3152 goto error;
3153 }
3154 data = PyBytes_AS_STRING(password_bytes);
3155 size = PyBytes_GET_SIZE(password_bytes);
3156 } else if (PyBytes_Check(password)) {
3157 data = PyBytes_AS_STRING(password);
3158 size = PyBytes_GET_SIZE(password);
3159 } else if (PyByteArray_Check(password)) {
3160 data = PyByteArray_AS_STRING(password);
3161 size = PyByteArray_GET_SIZE(password);
3162 } else {
3163 PyErr_SetString(PyExc_TypeError, bad_type_error);
3164 goto error;
3165 }
3166
Victor Stinner9ee02032013-06-23 15:08:23 +02003167 if (size > (Py_ssize_t)INT_MAX) {
3168 PyErr_Format(PyExc_ValueError,
3169 "password cannot be longer than %d bytes", INT_MAX);
3170 goto error;
3171 }
3172
Victor Stinner11ebff22013-07-07 17:07:52 +02003173 PyMem_Free(pw_info->password);
3174 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003175 if (!pw_info->password) {
3176 PyErr_SetString(PyExc_MemoryError,
3177 "unable to allocate password buffer");
3178 goto error;
3179 }
3180 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003181 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003182
3183 Py_XDECREF(password_bytes);
3184 return 1;
3185
3186error:
3187 Py_XDECREF(password_bytes);
3188 return 0;
3189}
3190
3191static int
3192_password_callback(char *buf, int size, int rwflag, void *userdata)
3193{
3194 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3195 PyObject *fn_ret = NULL;
3196
3197 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3198
3199 if (pw_info->callable) {
3200 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
3201 if (!fn_ret) {
3202 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3203 core python API, so we could use it to add a frame here */
3204 goto error;
3205 }
3206
3207 if (!_pwinfo_set(pw_info, fn_ret,
3208 "password callback must return a string")) {
3209 goto error;
3210 }
3211 Py_CLEAR(fn_ret);
3212 }
3213
3214 if (pw_info->size > size) {
3215 PyErr_Format(PyExc_ValueError,
3216 "password cannot be longer than %d bytes", size);
3217 goto error;
3218 }
3219
3220 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3221 memcpy(buf, pw_info->password, pw_info->size);
3222 return pw_info->size;
3223
3224error:
3225 Py_XDECREF(fn_ret);
3226 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3227 pw_info->error = 1;
3228 return -1;
3229}
3230
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003231/*[clinic input]
3232_ssl._SSLContext.load_cert_chain
3233 certfile: object
3234 keyfile: object = NULL
3235 password: object = NULL
3236
3237[clinic start generated code]*/
3238
Antoine Pitroub5218772010-05-21 09:56:06 +00003239static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003240_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3241 PyObject *keyfile, PyObject *password)
3242/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003243{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003244 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003245 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3246 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003247 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003248 int r;
3249
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003250 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003251 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003252 if (keyfile == Py_None)
3253 keyfile = NULL;
3254 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3255 PyErr_SetString(PyExc_TypeError,
3256 "certfile should be a valid filesystem path");
3257 return NULL;
3258 }
3259 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3260 PyErr_SetString(PyExc_TypeError,
3261 "keyfile should be a valid filesystem path");
3262 goto error;
3263 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003264 if (password && password != Py_None) {
3265 if (PyCallable_Check(password)) {
3266 pw_info.callable = password;
3267 } else if (!_pwinfo_set(&pw_info, password,
3268 "password should be a string or callable")) {
3269 goto error;
3270 }
3271 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3272 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3273 }
3274 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003275 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3276 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003277 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003278 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003279 if (pw_info.error) {
3280 ERR_clear_error();
3281 /* the password callback has already set the error information */
3282 }
3283 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003284 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003285 PyErr_SetFromErrno(PyExc_IOError);
3286 }
3287 else {
3288 _setSSLError(NULL, 0, __FILE__, __LINE__);
3289 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003290 goto error;
3291 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003292 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003293 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003294 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3295 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003296 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3297 Py_CLEAR(keyfile_bytes);
3298 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003299 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003300 if (pw_info.error) {
3301 ERR_clear_error();
3302 /* the password callback has already set the error information */
3303 }
3304 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003305 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003306 PyErr_SetFromErrno(PyExc_IOError);
3307 }
3308 else {
3309 _setSSLError(NULL, 0, __FILE__, __LINE__);
3310 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003311 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003312 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003313 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003314 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003315 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003316 if (r != 1) {
3317 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003318 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003319 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003320 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3321 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003322 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003323 Py_RETURN_NONE;
3324
3325error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003326 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3327 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003328 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003329 Py_XDECREF(keyfile_bytes);
3330 Py_XDECREF(certfile_bytes);
3331 return NULL;
3332}
3333
Christian Heimesefff7062013-11-21 03:35:02 +01003334/* internal helper function, returns -1 on error
3335 */
3336static int
3337_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3338 int filetype)
3339{
3340 BIO *biobuf = NULL;
3341 X509_STORE *store;
3342 int retval = 0, err, loaded = 0;
3343
3344 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3345
3346 if (len <= 0) {
3347 PyErr_SetString(PyExc_ValueError,
3348 "Empty certificate data");
3349 return -1;
3350 } else if (len > INT_MAX) {
3351 PyErr_SetString(PyExc_OverflowError,
3352 "Certificate data is too long.");
3353 return -1;
3354 }
3355
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003356 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003357 if (biobuf == NULL) {
3358 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3359 return -1;
3360 }
3361
3362 store = SSL_CTX_get_cert_store(self->ctx);
3363 assert(store != NULL);
3364
3365 while (1) {
3366 X509 *cert = NULL;
3367 int r;
3368
3369 if (filetype == SSL_FILETYPE_ASN1) {
3370 cert = d2i_X509_bio(biobuf, NULL);
3371 } else {
3372 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003373 SSL_CTX_get_default_passwd_cb(self->ctx),
3374 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3375 );
Christian Heimesefff7062013-11-21 03:35:02 +01003376 }
3377 if (cert == NULL) {
3378 break;
3379 }
3380 r = X509_STORE_add_cert(store, cert);
3381 X509_free(cert);
3382 if (!r) {
3383 err = ERR_peek_last_error();
3384 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3385 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3386 /* cert already in hash table, not an error */
3387 ERR_clear_error();
3388 } else {
3389 break;
3390 }
3391 }
3392 loaded++;
3393 }
3394
3395 err = ERR_peek_last_error();
3396 if ((filetype == SSL_FILETYPE_ASN1) &&
3397 (loaded > 0) &&
3398 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3399 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3400 /* EOF ASN1 file, not an error */
3401 ERR_clear_error();
3402 retval = 0;
3403 } else if ((filetype == SSL_FILETYPE_PEM) &&
3404 (loaded > 0) &&
3405 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3406 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3407 /* EOF PEM file, not an error */
3408 ERR_clear_error();
3409 retval = 0;
3410 } else {
3411 _setSSLError(NULL, 0, __FILE__, __LINE__);
3412 retval = -1;
3413 }
3414
3415 BIO_free(biobuf);
3416 return retval;
3417}
3418
3419
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003420/*[clinic input]
3421_ssl._SSLContext.load_verify_locations
3422 cafile: object = NULL
3423 capath: object = NULL
3424 cadata: object = NULL
3425
3426[clinic start generated code]*/
3427
Antoine Pitrou152efa22010-05-16 18:19:27 +00003428static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003429_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3430 PyObject *cafile,
3431 PyObject *capath,
3432 PyObject *cadata)
3433/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003434{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003435 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3436 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003437 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003438
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003439 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003440 if (cafile == Py_None)
3441 cafile = NULL;
3442 if (capath == Py_None)
3443 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003444 if (cadata == Py_None)
3445 cadata = NULL;
3446
3447 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003448 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003449 "cafile, capath and cadata cannot be all omitted");
3450 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003451 }
3452 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3453 PyErr_SetString(PyExc_TypeError,
3454 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003455 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003456 }
3457 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003458 PyErr_SetString(PyExc_TypeError,
3459 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003460 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003461 }
Christian Heimesefff7062013-11-21 03:35:02 +01003462
3463 /* validata cadata type and load cadata */
3464 if (cadata) {
3465 Py_buffer buf;
3466 PyObject *cadata_ascii = NULL;
3467
3468 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3469 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3470 PyBuffer_Release(&buf);
3471 PyErr_SetString(PyExc_TypeError,
3472 "cadata should be a contiguous buffer with "
3473 "a single dimension");
3474 goto error;
3475 }
3476 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3477 PyBuffer_Release(&buf);
3478 if (r == -1) {
3479 goto error;
3480 }
3481 } else {
3482 PyErr_Clear();
3483 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3484 if (cadata_ascii == NULL) {
3485 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003486 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003487 "bytes-like object");
3488 goto error;
3489 }
3490 r = _add_ca_certs(self,
3491 PyBytes_AS_STRING(cadata_ascii),
3492 PyBytes_GET_SIZE(cadata_ascii),
3493 SSL_FILETYPE_PEM);
3494 Py_DECREF(cadata_ascii);
3495 if (r == -1) {
3496 goto error;
3497 }
3498 }
3499 }
3500
3501 /* load cafile or capath */
3502 if (cafile || capath) {
3503 if (cafile)
3504 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3505 if (capath)
3506 capath_buf = PyBytes_AS_STRING(capath_bytes);
3507 PySSL_BEGIN_ALLOW_THREADS
3508 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3509 PySSL_END_ALLOW_THREADS
3510 if (r != 1) {
3511 ok = 0;
3512 if (errno != 0) {
3513 ERR_clear_error();
3514 PyErr_SetFromErrno(PyExc_IOError);
3515 }
3516 else {
3517 _setSSLError(NULL, 0, __FILE__, __LINE__);
3518 }
3519 goto error;
3520 }
3521 }
3522 goto end;
3523
3524 error:
3525 ok = 0;
3526 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003527 Py_XDECREF(cafile_bytes);
3528 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003529 if (ok) {
3530 Py_RETURN_NONE;
3531 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003532 return NULL;
3533 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003534}
3535
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003536/*[clinic input]
3537_ssl._SSLContext.load_dh_params
3538 path as filepath: object
3539 /
3540
3541[clinic start generated code]*/
3542
Antoine Pitrou152efa22010-05-16 18:19:27 +00003543static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003544_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3545/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003546{
3547 FILE *f;
3548 DH *dh;
3549
Victor Stinnerdaf45552013-08-28 00:53:59 +02003550 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003551 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003552 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003553
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003554 errno = 0;
3555 PySSL_BEGIN_ALLOW_THREADS
3556 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003557 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003558 PySSL_END_ALLOW_THREADS
3559 if (dh == NULL) {
3560 if (errno != 0) {
3561 ERR_clear_error();
3562 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3563 }
3564 else {
3565 _setSSLError(NULL, 0, __FILE__, __LINE__);
3566 }
3567 return NULL;
3568 }
3569 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3570 _setSSLError(NULL, 0, __FILE__, __LINE__);
3571 DH_free(dh);
3572 Py_RETURN_NONE;
3573}
3574
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003575/*[clinic input]
3576_ssl._SSLContext._wrap_socket
3577 sock: object(subclass_of="PySocketModule.Sock_Type")
3578 server_side: int
3579 server_hostname as hostname_obj: object = None
3580
3581[clinic start generated code]*/
3582
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003583static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003584_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3585 int server_side, PyObject *hostname_obj)
3586/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003587{
Antoine Pitroud5323212010-10-22 18:19:07 +00003588 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003589 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003590
Antoine Pitroud5323212010-10-22 18:19:07 +00003591 /* server_hostname is either None (or absent), or to be encoded
3592 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003593 if (hostname_obj != Py_None) {
3594 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003595 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003596 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003597
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003598 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3599 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003600 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003601 if (hostname != NULL)
3602 PyMem_Free(hostname);
3603 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003604}
3605
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003606/*[clinic input]
3607_ssl._SSLContext._wrap_bio
3608 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3609 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3610 server_side: int
3611 server_hostname as hostname_obj: object = None
3612
3613[clinic start generated code]*/
3614
Antoine Pitroub0182c82010-10-12 20:09:02 +00003615static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003616_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3617 PySSLMemoryBIO *outgoing, int server_side,
3618 PyObject *hostname_obj)
3619/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003620{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003621 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003622 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003623
3624 /* server_hostname is either None (or absent), or to be encoded
3625 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003626 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003627 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3628 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003629 }
3630
3631 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3632 incoming, outgoing);
3633
3634 PyMem_Free(hostname);
3635 return res;
3636}
3637
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003638/*[clinic input]
3639_ssl._SSLContext.session_stats
3640[clinic start generated code]*/
3641
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003642static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003643_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3644/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003645{
3646 int r;
3647 PyObject *value, *stats = PyDict_New();
3648 if (!stats)
3649 return NULL;
3650
3651#define ADD_STATS(SSL_NAME, KEY_NAME) \
3652 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3653 if (value == NULL) \
3654 goto error; \
3655 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3656 Py_DECREF(value); \
3657 if (r < 0) \
3658 goto error;
3659
3660 ADD_STATS(number, "number");
3661 ADD_STATS(connect, "connect");
3662 ADD_STATS(connect_good, "connect_good");
3663 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3664 ADD_STATS(accept, "accept");
3665 ADD_STATS(accept_good, "accept_good");
3666 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3667 ADD_STATS(accept, "accept");
3668 ADD_STATS(hits, "hits");
3669 ADD_STATS(misses, "misses");
3670 ADD_STATS(timeouts, "timeouts");
3671 ADD_STATS(cache_full, "cache_full");
3672
3673#undef ADD_STATS
3674
3675 return stats;
3676
3677error:
3678 Py_DECREF(stats);
3679 return NULL;
3680}
3681
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003682/*[clinic input]
3683_ssl._SSLContext.set_default_verify_paths
3684[clinic start generated code]*/
3685
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003686static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003687_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3688/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003689{
3690 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3691 _setSSLError(NULL, 0, __FILE__, __LINE__);
3692 return NULL;
3693 }
3694 Py_RETURN_NONE;
3695}
3696
Antoine Pitrou501da612011-12-21 09:27:41 +01003697#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003698/*[clinic input]
3699_ssl._SSLContext.set_ecdh_curve
3700 name: object
3701 /
3702
3703[clinic start generated code]*/
3704
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003705static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003706_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3707/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003708{
3709 PyObject *name_bytes;
3710 int nid;
3711 EC_KEY *key;
3712
3713 if (!PyUnicode_FSConverter(name, &name_bytes))
3714 return NULL;
3715 assert(PyBytes_Check(name_bytes));
3716 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3717 Py_DECREF(name_bytes);
3718 if (nid == 0) {
3719 PyErr_Format(PyExc_ValueError,
3720 "unknown elliptic curve name %R", name);
3721 return NULL;
3722 }
3723 key = EC_KEY_new_by_curve_name(nid);
3724 if (key == NULL) {
3725 _setSSLError(NULL, 0, __FILE__, __LINE__);
3726 return NULL;
3727 }
3728 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3729 EC_KEY_free(key);
3730 Py_RETURN_NONE;
3731}
Antoine Pitrou501da612011-12-21 09:27:41 +01003732#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003733
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003734#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003735static int
3736_servername_callback(SSL *s, int *al, void *args)
3737{
3738 int ret;
3739 PySSLContext *ssl_ctx = (PySSLContext *) args;
3740 PySSLSocket *ssl;
3741 PyObject *servername_o;
3742 PyObject *servername_idna;
3743 PyObject *result;
3744 /* The high-level ssl.SSLSocket object */
3745 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003746 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003747#ifdef WITH_THREAD
3748 PyGILState_STATE gstate = PyGILState_Ensure();
3749#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003750
3751 if (ssl_ctx->set_hostname == NULL) {
3752 /* remove race condition in this the call back while if removing the
3753 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003754#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003755 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003756#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003757 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003758 }
3759
3760 ssl = SSL_get_app_data(s);
3761 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003762
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003763 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003764 * SSL connection and that has a .context attribute that can be changed to
3765 * identify the requested hostname. Since the official API is the Python
3766 * level API we want to pass the callback a Python level object rather than
3767 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3768 * SSLObject) that will be passed. Otherwise if there's a socket then that
3769 * will be passed. If both do not exist only then the C-level object is
3770 * passed. */
3771 if (ssl->owner)
3772 ssl_socket = PyWeakref_GetObject(ssl->owner);
3773 else if (ssl->Socket)
3774 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3775 else
3776 ssl_socket = (PyObject *) ssl;
3777
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003778 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003779 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003780 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003781
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003782 if (servername == NULL) {
3783 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3784 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003785 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003786 else {
3787 servername_o = PyBytes_FromString(servername);
3788 if (servername_o == NULL) {
3789 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3790 goto error;
3791 }
3792 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3793 if (servername_idna == NULL) {
3794 PyErr_WriteUnraisable(servername_o);
3795 Py_DECREF(servername_o);
3796 goto error;
3797 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003798 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003799 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3800 servername_idna, ssl_ctx, NULL);
3801 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003802 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003803 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003804
3805 if (result == NULL) {
3806 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3807 *al = SSL_AD_HANDSHAKE_FAILURE;
3808 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3809 }
3810 else {
3811 if (result != Py_None) {
3812 *al = (int) PyLong_AsLong(result);
3813 if (PyErr_Occurred()) {
3814 PyErr_WriteUnraisable(result);
3815 *al = SSL_AD_INTERNAL_ERROR;
3816 }
3817 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3818 }
3819 else {
3820 ret = SSL_TLSEXT_ERR_OK;
3821 }
3822 Py_DECREF(result);
3823 }
3824
Stefan Krah20d60802013-01-17 17:07:17 +01003825#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003826 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003827#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003828 return ret;
3829
3830error:
3831 Py_DECREF(ssl_socket);
3832 *al = SSL_AD_INTERNAL_ERROR;
3833 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003834#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003835 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003836#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003837 return ret;
3838}
Antoine Pitroua5963382013-03-30 16:39:00 +01003839#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003840
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003841/*[clinic input]
3842_ssl._SSLContext.set_servername_callback
3843 method as cb: object
3844 /
3845
3846Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3847
3848If the argument is None then the callback is disabled. The method is called
3849with the SSLSocket, the server name as a string, and the SSLContext object.
3850See RFC 6066 for details of the SNI extension.
3851[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003852
3853static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003854_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3855/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003856{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003857#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003858 Py_CLEAR(self->set_hostname);
3859 if (cb == Py_None) {
3860 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3861 }
3862 else {
3863 if (!PyCallable_Check(cb)) {
3864 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3865 PyErr_SetString(PyExc_TypeError,
3866 "not a callable object");
3867 return NULL;
3868 }
3869 Py_INCREF(cb);
3870 self->set_hostname = cb;
3871 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3872 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3873 }
3874 Py_RETURN_NONE;
3875#else
3876 PyErr_SetString(PyExc_NotImplementedError,
3877 "The TLS extension servername callback, "
3878 "SSL_CTX_set_tlsext_servername_callback, "
3879 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003880 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003881#endif
3882}
3883
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003884/*[clinic input]
3885_ssl._SSLContext.cert_store_stats
3886
3887Returns quantities of loaded X.509 certificates.
3888
3889X.509 certificates with a CA extension and certificate revocation lists
3890inside the context's cert store.
3891
3892NOTE: Certificates in a capath directory aren't loaded unless they have
3893been used at least once.
3894[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003895
3896static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003897_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3898/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003899{
3900 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003901 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003902 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003903 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003904
3905 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003906 objs = X509_STORE_get0_objects(store);
3907 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3908 obj = sk_X509_OBJECT_value(objs, i);
3909 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003910 case X509_LU_X509:
3911 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003912 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003913 ca++;
3914 }
3915 break;
3916 case X509_LU_CRL:
3917 crl++;
3918 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003919 default:
3920 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3921 * As far as I can tell they are internal states and never
3922 * stored in a cert store */
3923 break;
3924 }
3925 }
3926 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3927 "x509_ca", ca);
3928}
3929
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003930/*[clinic input]
3931_ssl._SSLContext.get_ca_certs
3932 binary_form: bool = False
3933
3934Returns a list of dicts with information of loaded CA certs.
3935
3936If the optional argument is True, returns a DER-encoded copy of the CA
3937certificate.
3938
3939NOTE: Certificates in a capath directory aren't loaded unless they have
3940been used at least once.
3941[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003942
3943static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003944_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3945/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003946{
3947 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003948 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003949 PyObject *ci = NULL, *rlist = NULL;
3950 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003951
3952 if ((rlist = PyList_New(0)) == NULL) {
3953 return NULL;
3954 }
3955
3956 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003957 objs = X509_STORE_get0_objects(store);
3958 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003959 X509_OBJECT *obj;
3960 X509 *cert;
3961
Christian Heimes598894f2016-09-05 23:19:05 +02003962 obj = sk_X509_OBJECT_value(objs, i);
3963 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003964 /* not a x509 cert */
3965 continue;
3966 }
3967 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003968 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003969 if (!X509_check_ca(cert)) {
3970 continue;
3971 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003972 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003973 ci = _certificate_to_der(cert);
3974 } else {
3975 ci = _decode_certificate(cert);
3976 }
3977 if (ci == NULL) {
3978 goto error;
3979 }
3980 if (PyList_Append(rlist, ci) == -1) {
3981 goto error;
3982 }
3983 Py_CLEAR(ci);
3984 }
3985 return rlist;
3986
3987 error:
3988 Py_XDECREF(ci);
3989 Py_XDECREF(rlist);
3990 return NULL;
3991}
3992
3993
Antoine Pitrou152efa22010-05-16 18:19:27 +00003994static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003995 {"check_hostname", (getter) get_check_hostname,
3996 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003997 {"options", (getter) get_options,
3998 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003999 {"verify_flags", (getter) get_verify_flags,
4000 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004001 {"verify_mode", (getter) get_verify_mode,
4002 (setter) set_verify_mode, NULL},
4003 {NULL}, /* sentinel */
4004};
4005
4006static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004007 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4008 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4009 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4010 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4011 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4012 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4013 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4014 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4015 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4016 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4017 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4018 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4019 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4020 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004021 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004022 {NULL, NULL} /* sentinel */
4023};
4024
4025static PyTypeObject PySSLContext_Type = {
4026 PyVarObject_HEAD_INIT(NULL, 0)
4027 "_ssl._SSLContext", /*tp_name*/
4028 sizeof(PySSLContext), /*tp_basicsize*/
4029 0, /*tp_itemsize*/
4030 (destructor)context_dealloc, /*tp_dealloc*/
4031 0, /*tp_print*/
4032 0, /*tp_getattr*/
4033 0, /*tp_setattr*/
4034 0, /*tp_reserved*/
4035 0, /*tp_repr*/
4036 0, /*tp_as_number*/
4037 0, /*tp_as_sequence*/
4038 0, /*tp_as_mapping*/
4039 0, /*tp_hash*/
4040 0, /*tp_call*/
4041 0, /*tp_str*/
4042 0, /*tp_getattro*/
4043 0, /*tp_setattro*/
4044 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004045 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004046 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004047 (traverseproc) context_traverse, /*tp_traverse*/
4048 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004049 0, /*tp_richcompare*/
4050 0, /*tp_weaklistoffset*/
4051 0, /*tp_iter*/
4052 0, /*tp_iternext*/
4053 context_methods, /*tp_methods*/
4054 0, /*tp_members*/
4055 context_getsetlist, /*tp_getset*/
4056 0, /*tp_base*/
4057 0, /*tp_dict*/
4058 0, /*tp_descr_get*/
4059 0, /*tp_descr_set*/
4060 0, /*tp_dictoffset*/
4061 0, /*tp_init*/
4062 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004063 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004064};
4065
4066
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004067/*
4068 * MemoryBIO objects
4069 */
4070
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004071/*[clinic input]
4072@classmethod
4073_ssl.MemoryBIO.__new__
4074
4075[clinic start generated code]*/
4076
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004077static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004078_ssl_MemoryBIO_impl(PyTypeObject *type)
4079/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004080{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004081 BIO *bio;
4082 PySSLMemoryBIO *self;
4083
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004084 bio = BIO_new(BIO_s_mem());
4085 if (bio == NULL) {
4086 PyErr_SetString(PySSLErrorObject,
4087 "failed to allocate BIO");
4088 return NULL;
4089 }
4090 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4091 * just that no data is currently available. The SSL routines should retry
4092 * the read, which we can achieve by calling BIO_set_retry_read(). */
4093 BIO_set_retry_read(bio);
4094 BIO_set_mem_eof_return(bio, -1);
4095
4096 assert(type != NULL && type->tp_alloc != NULL);
4097 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4098 if (self == NULL) {
4099 BIO_free(bio);
4100 return NULL;
4101 }
4102 self->bio = bio;
4103 self->eof_written = 0;
4104
4105 return (PyObject *) self;
4106}
4107
4108static void
4109memory_bio_dealloc(PySSLMemoryBIO *self)
4110{
4111 BIO_free(self->bio);
4112 Py_TYPE(self)->tp_free(self);
4113}
4114
4115static PyObject *
4116memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4117{
4118 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
4119}
4120
4121PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4122"The number of bytes pending in the memory BIO.");
4123
4124static PyObject *
4125memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4126{
4127 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4128 && self->eof_written);
4129}
4130
4131PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4132"Whether the memory BIO is at EOF.");
4133
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004134/*[clinic input]
4135_ssl.MemoryBIO.read
4136 size as len: int = -1
4137 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004138
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004139Read up to size bytes from the memory BIO.
4140
4141If size is not specified, read the entire buffer.
4142If the return value is an empty bytes instance, this means either
4143EOF or that no data is available. Use the "eof" property to
4144distinguish between the two.
4145[clinic start generated code]*/
4146
4147static PyObject *
4148_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4149/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4150{
4151 int avail, nbytes;
4152 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004153
4154 avail = BIO_ctrl_pending(self->bio);
4155 if ((len < 0) || (len > avail))
4156 len = avail;
4157
4158 result = PyBytes_FromStringAndSize(NULL, len);
4159 if ((result == NULL) || (len == 0))
4160 return result;
4161
4162 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4163 /* There should never be any short reads but check anyway. */
4164 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4165 Py_DECREF(result);
4166 return NULL;
4167 }
4168
4169 return result;
4170}
4171
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004172/*[clinic input]
4173_ssl.MemoryBIO.write
4174 b: Py_buffer
4175 /
4176
4177Writes the bytes b into the memory BIO.
4178
4179Returns the number of bytes written.
4180[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004181
4182static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004183_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4184/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004185{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004186 int nbytes;
4187
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004188 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004189 PyErr_Format(PyExc_OverflowError,
4190 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004191 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004192 }
4193
4194 if (self->eof_written) {
4195 PyErr_SetString(PySSLErrorObject,
4196 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004197 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004198 }
4199
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004200 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004201 if (nbytes < 0) {
4202 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004203 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004204 }
4205
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004206 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004207}
4208
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004209/*[clinic input]
4210_ssl.MemoryBIO.write_eof
4211
4212Write an EOF marker to the memory BIO.
4213
4214When all data has been read, the "eof" property will be True.
4215[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004216
4217static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004218_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4219/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004220{
4221 self->eof_written = 1;
4222 /* After an EOF is written, a zero return from read() should be a real EOF
4223 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4224 BIO_clear_retry_flags(self->bio);
4225 BIO_set_mem_eof_return(self->bio, 0);
4226
4227 Py_RETURN_NONE;
4228}
4229
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004230static PyGetSetDef memory_bio_getsetlist[] = {
4231 {"pending", (getter) memory_bio_get_pending, NULL,
4232 PySSL_memory_bio_pending_doc},
4233 {"eof", (getter) memory_bio_get_eof, NULL,
4234 PySSL_memory_bio_eof_doc},
4235 {NULL}, /* sentinel */
4236};
4237
4238static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004239 _SSL_MEMORYBIO_READ_METHODDEF
4240 _SSL_MEMORYBIO_WRITE_METHODDEF
4241 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004242 {NULL, NULL} /* sentinel */
4243};
4244
4245static PyTypeObject PySSLMemoryBIO_Type = {
4246 PyVarObject_HEAD_INIT(NULL, 0)
4247 "_ssl.MemoryBIO", /*tp_name*/
4248 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4249 0, /*tp_itemsize*/
4250 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4251 0, /*tp_print*/
4252 0, /*tp_getattr*/
4253 0, /*tp_setattr*/
4254 0, /*tp_reserved*/
4255 0, /*tp_repr*/
4256 0, /*tp_as_number*/
4257 0, /*tp_as_sequence*/
4258 0, /*tp_as_mapping*/
4259 0, /*tp_hash*/
4260 0, /*tp_call*/
4261 0, /*tp_str*/
4262 0, /*tp_getattro*/
4263 0, /*tp_setattro*/
4264 0, /*tp_as_buffer*/
4265 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4266 0, /*tp_doc*/
4267 0, /*tp_traverse*/
4268 0, /*tp_clear*/
4269 0, /*tp_richcompare*/
4270 0, /*tp_weaklistoffset*/
4271 0, /*tp_iter*/
4272 0, /*tp_iternext*/
4273 memory_bio_methods, /*tp_methods*/
4274 0, /*tp_members*/
4275 memory_bio_getsetlist, /*tp_getset*/
4276 0, /*tp_base*/
4277 0, /*tp_dict*/
4278 0, /*tp_descr_get*/
4279 0, /*tp_descr_set*/
4280 0, /*tp_dictoffset*/
4281 0, /*tp_init*/
4282 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004283 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004284};
4285
Antoine Pitrou152efa22010-05-16 18:19:27 +00004286
Christian Heimes99a65702016-09-10 23:44:53 +02004287/*
4288 * SSL Session object
4289 */
4290
4291static void
4292PySSLSession_dealloc(PySSLSession *self)
4293{
Christian Heimesa5d07652016-09-24 10:48:05 +02004294 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004295 Py_XDECREF(self->ctx);
4296 if (self->session != NULL) {
4297 SSL_SESSION_free(self->session);
4298 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004299 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004300}
4301
4302static PyObject *
4303PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4304{
4305 int result;
4306
4307 if (left == NULL || right == NULL) {
4308 PyErr_BadInternalCall();
4309 return NULL;
4310 }
4311
4312 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4313 Py_RETURN_NOTIMPLEMENTED;
4314 }
4315
4316 if (left == right) {
4317 result = 0;
4318 } else {
4319 const unsigned char *left_id, *right_id;
4320 unsigned int left_len, right_len;
4321 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4322 &left_len);
4323 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4324 &right_len);
4325 if (left_len == right_len) {
4326 result = memcmp(left_id, right_id, left_len);
4327 } else {
4328 result = 1;
4329 }
4330 }
4331
4332 switch (op) {
4333 case Py_EQ:
4334 if (result == 0) {
4335 Py_RETURN_TRUE;
4336 } else {
4337 Py_RETURN_FALSE;
4338 }
4339 break;
4340 case Py_NE:
4341 if (result != 0) {
4342 Py_RETURN_TRUE;
4343 } else {
4344 Py_RETURN_FALSE;
4345 }
4346 break;
4347 case Py_LT:
4348 case Py_LE:
4349 case Py_GT:
4350 case Py_GE:
4351 Py_RETURN_NOTIMPLEMENTED;
4352 break;
4353 default:
4354 PyErr_BadArgument();
4355 return NULL;
4356 }
4357}
4358
4359static int
4360PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4361{
4362 Py_VISIT(self->ctx);
4363 return 0;
4364}
4365
4366static int
4367PySSLSession_clear(PySSLSession *self)
4368{
4369 Py_CLEAR(self->ctx);
4370 return 0;
4371}
4372
4373
4374static PyObject *
4375PySSLSession_get_time(PySSLSession *self, void *closure) {
4376 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4377}
4378
4379PyDoc_STRVAR(PySSLSession_get_time_doc,
4380"Session creation time (seconds since epoch).");
4381
4382
4383static PyObject *
4384PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4385 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4386}
4387
4388PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4389"Session timeout (delta in seconds).");
4390
4391
4392static PyObject *
4393PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4394 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4395 return PyLong_FromUnsignedLong(hint);
4396}
4397
4398PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4399"Ticket life time hint.");
4400
4401
4402static PyObject *
4403PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4404 const unsigned char *id;
4405 unsigned int len;
4406 id = SSL_SESSION_get_id(self->session, &len);
4407 return PyBytes_FromStringAndSize((const char *)id, len);
4408}
4409
4410PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4411"Session id");
4412
4413
4414static PyObject *
4415PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4416 if (SSL_SESSION_has_ticket(self->session)) {
4417 Py_RETURN_TRUE;
4418 } else {
4419 Py_RETURN_FALSE;
4420 }
4421}
4422
4423PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4424"Does the session contain a ticket?");
4425
4426
4427static PyGetSetDef PySSLSession_getsetlist[] = {
4428 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4429 PySSLSession_get_has_ticket_doc},
4430 {"id", (getter) PySSLSession_get_session_id, NULL,
4431 PySSLSession_get_session_id_doc},
4432 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4433 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4434 {"time", (getter) PySSLSession_get_time, NULL,
4435 PySSLSession_get_time_doc},
4436 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4437 PySSLSession_get_timeout_doc},
4438 {NULL}, /* sentinel */
4439};
4440
4441static PyTypeObject PySSLSession_Type = {
4442 PyVarObject_HEAD_INIT(NULL, 0)
4443 "_ssl.Session", /*tp_name*/
4444 sizeof(PySSLSession), /*tp_basicsize*/
4445 0, /*tp_itemsize*/
4446 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4447 0, /*tp_print*/
4448 0, /*tp_getattr*/
4449 0, /*tp_setattr*/
4450 0, /*tp_reserved*/
4451 0, /*tp_repr*/
4452 0, /*tp_as_number*/
4453 0, /*tp_as_sequence*/
4454 0, /*tp_as_mapping*/
4455 0, /*tp_hash*/
4456 0, /*tp_call*/
4457 0, /*tp_str*/
4458 0, /*tp_getattro*/
4459 0, /*tp_setattro*/
4460 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004461 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004462 0, /*tp_doc*/
4463 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4464 (inquiry)PySSLSession_clear, /*tp_clear*/
4465 PySSLSession_richcompare, /*tp_richcompare*/
4466 0, /*tp_weaklistoffset*/
4467 0, /*tp_iter*/
4468 0, /*tp_iternext*/
4469 0, /*tp_methods*/
4470 0, /*tp_members*/
4471 PySSLSession_getsetlist, /*tp_getset*/
4472};
4473
4474
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004475/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004476/*[clinic input]
4477_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004478 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004479 entropy: double
4480 /
4481
4482Mix string into the OpenSSL PRNG state.
4483
4484entropy (a float) is a lower bound on the entropy contained in
4485string. See RFC 1750.
4486[clinic start generated code]*/
4487
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004488static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004489_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
4490/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004491{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004492 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004493 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004494
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004495 buf = (const char *)view->buf;
4496 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004497 do {
4498 written = Py_MIN(len, INT_MAX);
4499 RAND_add(buf, (int)written, entropy);
4500 buf += written;
4501 len -= written;
4502 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004503 Py_INCREF(Py_None);
4504 return Py_None;
4505}
4506
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004507static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004508PySSL_RAND(int len, int pseudo)
4509{
4510 int ok;
4511 PyObject *bytes;
4512 unsigned long err;
4513 const char *errstr;
4514 PyObject *v;
4515
Victor Stinner1e81a392013-12-19 16:47:04 +01004516 if (len < 0) {
4517 PyErr_SetString(PyExc_ValueError, "num must be positive");
4518 return NULL;
4519 }
4520
Victor Stinner99c8b162011-05-24 12:05:19 +02004521 bytes = PyBytes_FromStringAndSize(NULL, len);
4522 if (bytes == NULL)
4523 return NULL;
4524 if (pseudo) {
4525 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4526 if (ok == 0 || ok == 1)
4527 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4528 }
4529 else {
4530 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4531 if (ok == 1)
4532 return bytes;
4533 }
4534 Py_DECREF(bytes);
4535
4536 err = ERR_get_error();
4537 errstr = ERR_reason_error_string(err);
4538 v = Py_BuildValue("(ks)", err, errstr);
4539 if (v != NULL) {
4540 PyErr_SetObject(PySSLErrorObject, v);
4541 Py_DECREF(v);
4542 }
4543 return NULL;
4544}
4545
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004546/*[clinic input]
4547_ssl.RAND_bytes
4548 n: int
4549 /
4550
4551Generate n cryptographically strong pseudo-random bytes.
4552[clinic start generated code]*/
4553
Victor Stinner99c8b162011-05-24 12:05:19 +02004554static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004555_ssl_RAND_bytes_impl(PyObject *module, int n)
4556/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004557{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004558 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004559}
4560
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004561/*[clinic input]
4562_ssl.RAND_pseudo_bytes
4563 n: int
4564 /
4565
4566Generate n pseudo-random bytes.
4567
4568Return a pair (bytes, is_cryptographic). is_cryptographic is True
4569if the bytes generated are cryptographically strong.
4570[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004571
4572static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004573_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4574/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004575{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004576 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004577}
4578
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004579/*[clinic input]
4580_ssl.RAND_status
4581
4582Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4583
4584It is necessary to seed the PRNG with RAND_add() on some platforms before
4585using the ssl() function.
4586[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004587
4588static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004589_ssl_RAND_status_impl(PyObject *module)
4590/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004591{
Christian Heimes217cfd12007-12-02 14:31:20 +00004592 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004593}
4594
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004595#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004596/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004597/*[clinic input]
4598_ssl.RAND_egd
4599 path: object(converter="PyUnicode_FSConverter")
4600 /
4601
4602Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4603
4604Returns number of bytes read. Raises SSLError if connection to EGD
4605fails or if it does not provide enough data to seed PRNG.
4606[clinic start generated code]*/
4607
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004608static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004609_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4610/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004611{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004612 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004613 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004614 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004615 PyErr_SetString(PySSLErrorObject,
4616 "EGD connection failed or EGD did not return "
4617 "enough data to seed the PRNG");
4618 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004619 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004620 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004621}
Christian Heimesa5d07652016-09-24 10:48:05 +02004622/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004623#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004624
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004625
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004626
4627/*[clinic input]
4628_ssl.get_default_verify_paths
4629
4630Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4631
4632The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4633[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004634
4635static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004636_ssl_get_default_verify_paths_impl(PyObject *module)
4637/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004638{
4639 PyObject *ofile_env = NULL;
4640 PyObject *ofile = NULL;
4641 PyObject *odir_env = NULL;
4642 PyObject *odir = NULL;
4643
Benjamin Petersond113c962015-07-18 10:59:13 -07004644#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004645 const char *tmp = (info); \
4646 target = NULL; \
4647 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4648 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4649 target = PyBytes_FromString(tmp); } \
4650 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004651 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004652
Benjamin Petersond113c962015-07-18 10:59:13 -07004653 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4654 CONVERT(X509_get_default_cert_file(), ofile);
4655 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4656 CONVERT(X509_get_default_cert_dir(), odir);
4657#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004658
Christian Heimes200bb1b2013-06-14 15:14:29 +02004659 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004660
4661 error:
4662 Py_XDECREF(ofile_env);
4663 Py_XDECREF(ofile);
4664 Py_XDECREF(odir_env);
4665 Py_XDECREF(odir);
4666 return NULL;
4667}
4668
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004669static PyObject*
4670asn1obj2py(ASN1_OBJECT *obj)
4671{
4672 int nid;
4673 const char *ln, *sn;
4674 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004675 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004676
4677 nid = OBJ_obj2nid(obj);
4678 if (nid == NID_undef) {
4679 PyErr_Format(PyExc_ValueError, "Unknown object");
4680 return NULL;
4681 }
4682 sn = OBJ_nid2sn(nid);
4683 ln = OBJ_nid2ln(nid);
4684 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4685 if (buflen < 0) {
4686 _setSSLError(NULL, 0, __FILE__, __LINE__);
4687 return NULL;
4688 }
4689 if (buflen) {
4690 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4691 } else {
4692 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4693 }
4694}
4695
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004696/*[clinic input]
4697_ssl.txt2obj
4698 txt: str
4699 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004700
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004701Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4702
4703By default objects are looked up by OID. With name=True short and
4704long name are also matched.
4705[clinic start generated code]*/
4706
4707static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004708_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4709/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004710{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004711 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004712 ASN1_OBJECT *obj;
4713
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004714 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4715 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004716 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004717 return NULL;
4718 }
4719 result = asn1obj2py(obj);
4720 ASN1_OBJECT_free(obj);
4721 return result;
4722}
4723
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004724/*[clinic input]
4725_ssl.nid2obj
4726 nid: int
4727 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004728
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004729Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4730[clinic start generated code]*/
4731
4732static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004733_ssl_nid2obj_impl(PyObject *module, int nid)
4734/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004735{
4736 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004737 ASN1_OBJECT *obj;
4738
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004739 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004740 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004741 return NULL;
4742 }
4743 obj = OBJ_nid2obj(nid);
4744 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004745 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004746 return NULL;
4747 }
4748 result = asn1obj2py(obj);
4749 ASN1_OBJECT_free(obj);
4750 return result;
4751}
4752
Christian Heimes46bebee2013-06-09 19:03:31 +02004753#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004754
4755static PyObject*
4756certEncodingType(DWORD encodingType)
4757{
4758 static PyObject *x509_asn = NULL;
4759 static PyObject *pkcs_7_asn = NULL;
4760
4761 if (x509_asn == NULL) {
4762 x509_asn = PyUnicode_InternFromString("x509_asn");
4763 if (x509_asn == NULL)
4764 return NULL;
4765 }
4766 if (pkcs_7_asn == NULL) {
4767 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4768 if (pkcs_7_asn == NULL)
4769 return NULL;
4770 }
4771 switch(encodingType) {
4772 case X509_ASN_ENCODING:
4773 Py_INCREF(x509_asn);
4774 return x509_asn;
4775 case PKCS_7_ASN_ENCODING:
4776 Py_INCREF(pkcs_7_asn);
4777 return pkcs_7_asn;
4778 default:
4779 return PyLong_FromLong(encodingType);
4780 }
4781}
4782
4783static PyObject*
4784parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4785{
4786 CERT_ENHKEY_USAGE *usage;
4787 DWORD size, error, i;
4788 PyObject *retval;
4789
4790 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4791 error = GetLastError();
4792 if (error == CRYPT_E_NOT_FOUND) {
4793 Py_RETURN_TRUE;
4794 }
4795 return PyErr_SetFromWindowsErr(error);
4796 }
4797
4798 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4799 if (usage == NULL) {
4800 return PyErr_NoMemory();
4801 }
4802
4803 /* Now get the actual enhanced usage property */
4804 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4805 PyMem_Free(usage);
4806 error = GetLastError();
4807 if (error == CRYPT_E_NOT_FOUND) {
4808 Py_RETURN_TRUE;
4809 }
4810 return PyErr_SetFromWindowsErr(error);
4811 }
4812 retval = PySet_New(NULL);
4813 if (retval == NULL) {
4814 goto error;
4815 }
4816 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4817 if (usage->rgpszUsageIdentifier[i]) {
4818 PyObject *oid;
4819 int err;
4820 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4821 if (oid == NULL) {
4822 Py_CLEAR(retval);
4823 goto error;
4824 }
4825 err = PySet_Add(retval, oid);
4826 Py_DECREF(oid);
4827 if (err == -1) {
4828 Py_CLEAR(retval);
4829 goto error;
4830 }
4831 }
4832 }
4833 error:
4834 PyMem_Free(usage);
4835 return retval;
4836}
4837
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004838/*[clinic input]
4839_ssl.enum_certificates
4840 store_name: str
4841
4842Retrieve certificates from Windows' cert store.
4843
4844store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4845more cert storages, too. The function returns a list of (bytes,
4846encoding_type, trust) tuples. The encoding_type flag can be interpreted
4847with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4848a set of OIDs or the boolean True.
4849[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004850
Christian Heimes46bebee2013-06-09 19:03:31 +02004851static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004852_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4853/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004854{
Christian Heimes46bebee2013-06-09 19:03:31 +02004855 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004856 PCCERT_CONTEXT pCertCtx = NULL;
4857 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004858 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004859
Christian Heimes44109d72013-11-22 01:51:30 +01004860 result = PyList_New(0);
4861 if (result == NULL) {
4862 return NULL;
4863 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004864 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4865 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4866 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004867 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004868 Py_DECREF(result);
4869 return PyErr_SetFromWindowsErr(GetLastError());
4870 }
4871
Christian Heimes44109d72013-11-22 01:51:30 +01004872 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4873 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4874 pCertCtx->cbCertEncoded);
4875 if (!cert) {
4876 Py_CLEAR(result);
4877 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004878 }
Christian Heimes44109d72013-11-22 01:51:30 +01004879 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4880 Py_CLEAR(result);
4881 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004882 }
Christian Heimes44109d72013-11-22 01:51:30 +01004883 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4884 if (keyusage == Py_True) {
4885 Py_DECREF(keyusage);
4886 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004887 }
Christian Heimes44109d72013-11-22 01:51:30 +01004888 if (keyusage == NULL) {
4889 Py_CLEAR(result);
4890 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004891 }
Christian Heimes44109d72013-11-22 01:51:30 +01004892 if ((tup = PyTuple_New(3)) == NULL) {
4893 Py_CLEAR(result);
4894 break;
4895 }
4896 PyTuple_SET_ITEM(tup, 0, cert);
4897 cert = NULL;
4898 PyTuple_SET_ITEM(tup, 1, enc);
4899 enc = NULL;
4900 PyTuple_SET_ITEM(tup, 2, keyusage);
4901 keyusage = NULL;
4902 if (PyList_Append(result, tup) < 0) {
4903 Py_CLEAR(result);
4904 break;
4905 }
4906 Py_CLEAR(tup);
4907 }
4908 if (pCertCtx) {
4909 /* loop ended with an error, need to clean up context manually */
4910 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004911 }
4912
4913 /* In error cases cert, enc and tup may not be NULL */
4914 Py_XDECREF(cert);
4915 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004916 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004917 Py_XDECREF(tup);
4918
4919 if (!CertCloseStore(hStore, 0)) {
4920 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004921 Py_XDECREF(result);
4922 return PyErr_SetFromWindowsErr(GetLastError());
4923 }
4924 return result;
4925}
4926
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004927/*[clinic input]
4928_ssl.enum_crls
4929 store_name: str
4930
4931Retrieve CRLs from Windows' cert store.
4932
4933store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4934more cert storages, too. The function returns a list of (bytes,
4935encoding_type) tuples. The encoding_type flag can be interpreted with
4936X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4937[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004938
4939static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004940_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4941/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004942{
Christian Heimes44109d72013-11-22 01:51:30 +01004943 HCERTSTORE hStore = NULL;
4944 PCCRL_CONTEXT pCrlCtx = NULL;
4945 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4946 PyObject *result = NULL;
4947
Christian Heimes44109d72013-11-22 01:51:30 +01004948 result = PyList_New(0);
4949 if (result == NULL) {
4950 return NULL;
4951 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004952 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4953 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4954 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004955 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004956 Py_DECREF(result);
4957 return PyErr_SetFromWindowsErr(GetLastError());
4958 }
Christian Heimes44109d72013-11-22 01:51:30 +01004959
4960 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4961 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4962 pCrlCtx->cbCrlEncoded);
4963 if (!crl) {
4964 Py_CLEAR(result);
4965 break;
4966 }
4967 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4968 Py_CLEAR(result);
4969 break;
4970 }
4971 if ((tup = PyTuple_New(2)) == NULL) {
4972 Py_CLEAR(result);
4973 break;
4974 }
4975 PyTuple_SET_ITEM(tup, 0, crl);
4976 crl = NULL;
4977 PyTuple_SET_ITEM(tup, 1, enc);
4978 enc = NULL;
4979
4980 if (PyList_Append(result, tup) < 0) {
4981 Py_CLEAR(result);
4982 break;
4983 }
4984 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004985 }
Christian Heimes44109d72013-11-22 01:51:30 +01004986 if (pCrlCtx) {
4987 /* loop ended with an error, need to clean up context manually */
4988 CertFreeCRLContext(pCrlCtx);
4989 }
4990
4991 /* In error cases cert, enc and tup may not be NULL */
4992 Py_XDECREF(crl);
4993 Py_XDECREF(enc);
4994 Py_XDECREF(tup);
4995
4996 if (!CertCloseStore(hStore, 0)) {
4997 /* This error case might shadow another exception.*/
4998 Py_XDECREF(result);
4999 return PyErr_SetFromWindowsErr(GetLastError());
5000 }
5001 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005002}
Christian Heimes44109d72013-11-22 01:51:30 +01005003
5004#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005005
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005006/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005007static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005008 _SSL__TEST_DECODE_CERT_METHODDEF
5009 _SSL_RAND_ADD_METHODDEF
5010 _SSL_RAND_BYTES_METHODDEF
5011 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5012 _SSL_RAND_EGD_METHODDEF
5013 _SSL_RAND_STATUS_METHODDEF
5014 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5015 _SSL_ENUM_CERTIFICATES_METHODDEF
5016 _SSL_ENUM_CRLS_METHODDEF
5017 _SSL_TXT2OBJ_METHODDEF
5018 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005019 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005020};
5021
5022
Christian Heimes598894f2016-09-05 23:19:05 +02005023#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005024
5025/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005026 * of the Python C thread library
5027 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5028 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005029
5030static PyThread_type_lock *_ssl_locks = NULL;
5031
Christian Heimes4d98ca92013-08-19 17:36:29 +02005032#if OPENSSL_VERSION_NUMBER >= 0x10000000
5033/* use new CRYPTO_THREADID API. */
5034static void
5035_ssl_threadid_callback(CRYPTO_THREADID *id)
5036{
5037 CRYPTO_THREADID_set_numeric(id,
5038 (unsigned long)PyThread_get_thread_ident());
5039}
5040#else
5041/* deprecated CRYPTO_set_id_callback() API. */
5042static unsigned long
5043_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005044 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005045}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005046#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005047
Bill Janssen6e027db2007-11-15 22:23:56 +00005048static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005049 (int mode, int n, const char *file, int line) {
5050 /* this function is needed to perform locking on shared data
5051 structures. (Note that OpenSSL uses a number of global data
5052 structures that will be implicitly shared whenever multiple
5053 threads use OpenSSL.) Multi-threaded applications will
5054 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005055
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005056 locking_function() must be able to handle up to
5057 CRYPTO_num_locks() different mutex locks. It sets the n-th
5058 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005059
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005060 file and line are the file number of the function setting the
5061 lock. They can be useful for debugging.
5062 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005063
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005064 if ((_ssl_locks == NULL) ||
5065 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5066 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005067
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005068 if (mode & CRYPTO_LOCK) {
5069 PyThread_acquire_lock(_ssl_locks[n], 1);
5070 } else {
5071 PyThread_release_lock(_ssl_locks[n]);
5072 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005073}
5074
5075static int _setup_ssl_threads(void) {
5076
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005077 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005078
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005079 if (_ssl_locks == NULL) {
5080 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005081 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5082 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005083 if (_ssl_locks == NULL) {
5084 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005085 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005086 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005087 for (i = 0; i < _ssl_locks_count; i++) {
5088 _ssl_locks[i] = PyThread_allocate_lock();
5089 if (_ssl_locks[i] == NULL) {
5090 unsigned int j;
5091 for (j = 0; j < i; j++) {
5092 PyThread_free_lock(_ssl_locks[j]);
5093 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005094 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005095 return 0;
5096 }
5097 }
5098 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005099#if OPENSSL_VERSION_NUMBER >= 0x10000000
5100 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5101#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005102 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005103#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005104 }
5105 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005106}
5107
Christian Heimes598894f2016-09-05 23:19:05 +02005108#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005109
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005110PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005111"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005112for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005113
Martin v. Löwis1a214512008-06-11 05:26:20 +00005114
5115static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005116 PyModuleDef_HEAD_INIT,
5117 "_ssl",
5118 module_doc,
5119 -1,
5120 PySSL_methods,
5121 NULL,
5122 NULL,
5123 NULL,
5124 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005125};
5126
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005127
5128static void
5129parse_openssl_version(unsigned long libver,
5130 unsigned int *major, unsigned int *minor,
5131 unsigned int *fix, unsigned int *patch,
5132 unsigned int *status)
5133{
5134 *status = libver & 0xF;
5135 libver >>= 4;
5136 *patch = libver & 0xFF;
5137 libver >>= 8;
5138 *fix = libver & 0xFF;
5139 libver >>= 8;
5140 *minor = libver & 0xFF;
5141 libver >>= 8;
5142 *major = libver & 0xFF;
5143}
5144
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005145PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005146PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005147{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005148 PyObject *m, *d, *r;
5149 unsigned long libver;
5150 unsigned int major, minor, fix, patch, status;
5151 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005152 struct py_ssl_error_code *errcode;
5153 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005154
Antoine Pitrou152efa22010-05-16 18:19:27 +00005155 if (PyType_Ready(&PySSLContext_Type) < 0)
5156 return NULL;
5157 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005158 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005159 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5160 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005161 if (PyType_Ready(&PySSLSession_Type) < 0)
5162 return NULL;
5163
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005164
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005165 m = PyModule_Create(&_sslmodule);
5166 if (m == NULL)
5167 return NULL;
5168 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005169
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005170 /* Load _socket module and its C API */
5171 socket_api = PySocketModule_ImportModuleAndAPI();
5172 if (!socket_api)
5173 return NULL;
5174 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005175
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005176 /* Init OpenSSL */
5177 SSL_load_error_strings();
5178 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005179#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02005180#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005181 /* note that this will start threading if not already started */
5182 if (!_setup_ssl_threads()) {
5183 return NULL;
5184 }
Christian Heimes598894f2016-09-05 23:19:05 +02005185#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5186 /* OpenSSL 1.1.0 builtin thread support is enabled */
5187 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005188#endif
Christian Heimes598894f2016-09-05 23:19:05 +02005189#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005190 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005191
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005192 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005193 sslerror_type_slots[0].pfunc = PyExc_OSError;
5194 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005195 if (PySSLErrorObject == NULL)
5196 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005197
Antoine Pitrou41032a62011-10-27 23:56:55 +02005198 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5199 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5200 PySSLErrorObject, NULL);
5201 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5202 "ssl.SSLWantReadError", SSLWantReadError_doc,
5203 PySSLErrorObject, NULL);
5204 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5205 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5206 PySSLErrorObject, NULL);
5207 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5208 "ssl.SSLSyscallError", SSLSyscallError_doc,
5209 PySSLErrorObject, NULL);
5210 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5211 "ssl.SSLEOFError", SSLEOFError_doc,
5212 PySSLErrorObject, NULL);
5213 if (PySSLZeroReturnErrorObject == NULL
5214 || PySSLWantReadErrorObject == NULL
5215 || PySSLWantWriteErrorObject == NULL
5216 || PySSLSyscallErrorObject == NULL
5217 || PySSLEOFErrorObject == NULL)
5218 return NULL;
5219 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5220 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5221 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5222 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5223 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5224 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005225 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005226 if (PyDict_SetItemString(d, "_SSLContext",
5227 (PyObject *)&PySSLContext_Type) != 0)
5228 return NULL;
5229 if (PyDict_SetItemString(d, "_SSLSocket",
5230 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005231 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005232 if (PyDict_SetItemString(d, "MemoryBIO",
5233 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5234 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005235 if (PyDict_SetItemString(d, "SSLSession",
5236 (PyObject *)&PySSLSession_Type) != 0)
5237 return NULL;
5238
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005239 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5240 PY_SSL_ERROR_ZERO_RETURN);
5241 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5242 PY_SSL_ERROR_WANT_READ);
5243 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5244 PY_SSL_ERROR_WANT_WRITE);
5245 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5246 PY_SSL_ERROR_WANT_X509_LOOKUP);
5247 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5248 PY_SSL_ERROR_SYSCALL);
5249 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5250 PY_SSL_ERROR_SSL);
5251 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5252 PY_SSL_ERROR_WANT_CONNECT);
5253 /* non ssl.h errorcodes */
5254 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5255 PY_SSL_ERROR_EOF);
5256 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5257 PY_SSL_ERROR_INVALID_ERROR_CODE);
5258 /* cert requirements */
5259 PyModule_AddIntConstant(m, "CERT_NONE",
5260 PY_SSL_CERT_NONE);
5261 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5262 PY_SSL_CERT_OPTIONAL);
5263 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5264 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005265 /* CRL verification for verification_flags */
5266 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5267 0);
5268 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5269 X509_V_FLAG_CRL_CHECK);
5270 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5271 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5272 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5273 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005274#ifdef X509_V_FLAG_TRUSTED_FIRST
5275 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5276 X509_V_FLAG_TRUSTED_FIRST);
5277#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005278
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005279 /* Alert Descriptions from ssl.h */
5280 /* note RESERVED constants no longer intended for use have been removed */
5281 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5282
5283#define ADD_AD_CONSTANT(s) \
5284 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5285 SSL_AD_##s)
5286
5287 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5288 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5289 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5290 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5291 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5292 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5293 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5294 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5295 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5296 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5297 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5298 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5299 ADD_AD_CONSTANT(UNKNOWN_CA);
5300 ADD_AD_CONSTANT(ACCESS_DENIED);
5301 ADD_AD_CONSTANT(DECODE_ERROR);
5302 ADD_AD_CONSTANT(DECRYPT_ERROR);
5303 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5304 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5305 ADD_AD_CONSTANT(INTERNAL_ERROR);
5306 ADD_AD_CONSTANT(USER_CANCELLED);
5307 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005308 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005309#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5310 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5311#endif
5312#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5313 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5314#endif
5315#ifdef SSL_AD_UNRECOGNIZED_NAME
5316 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5317#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005318#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5319 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5320#endif
5321#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5322 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5323#endif
5324#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5325 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5326#endif
5327
5328#undef ADD_AD_CONSTANT
5329
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005330 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005331#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005332 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5333 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005334#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005335#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005336 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5337 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005338#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005339 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005340 PY_SSL_VERSION_TLS);
5341 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5342 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005343 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5344 PY_SSL_VERSION_TLS_CLIENT);
5345 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5346 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005347 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5348 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005349#if HAVE_TLSv1_2
5350 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5351 PY_SSL_VERSION_TLS1_1);
5352 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5353 PY_SSL_VERSION_TLS1_2);
5354#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005355
Antoine Pitroub5218772010-05-21 09:56:06 +00005356 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005357 PyModule_AddIntConstant(m, "OP_ALL",
5358 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005359 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5360 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5361 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005362#if HAVE_TLSv1_2
5363 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5364 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5365#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005366 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5367 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005368 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005369 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005370#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005371 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005372#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005373#ifdef SSL_OP_NO_COMPRESSION
5374 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5375 SSL_OP_NO_COMPRESSION);
5376#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005377
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005378#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005379 r = Py_True;
5380#else
5381 r = Py_False;
5382#endif
5383 Py_INCREF(r);
5384 PyModule_AddObject(m, "HAS_SNI", r);
5385
Antoine Pitroud6494802011-07-21 01:11:30 +02005386 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005387 Py_INCREF(r);
5388 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5389
Antoine Pitrou501da612011-12-21 09:27:41 +01005390#ifdef OPENSSL_NO_ECDH
5391 r = Py_False;
5392#else
5393 r = Py_True;
5394#endif
5395 Py_INCREF(r);
5396 PyModule_AddObject(m, "HAS_ECDH", r);
5397
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005398#ifdef OPENSSL_NPN_NEGOTIATED
5399 r = Py_True;
5400#else
5401 r = Py_False;
5402#endif
5403 Py_INCREF(r);
5404 PyModule_AddObject(m, "HAS_NPN", r);
5405
Benjamin Petersoncca27322015-01-23 16:35:37 -05005406#ifdef HAVE_ALPN
5407 r = Py_True;
5408#else
5409 r = Py_False;
5410#endif
5411 Py_INCREF(r);
5412 PyModule_AddObject(m, "HAS_ALPN", r);
5413
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005414 /* Mappings for error codes */
5415 err_codes_to_names = PyDict_New();
5416 err_names_to_codes = PyDict_New();
5417 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5418 return NULL;
5419 errcode = error_codes;
5420 while (errcode->mnemonic != NULL) {
5421 PyObject *mnemo, *key;
5422 mnemo = PyUnicode_FromString(errcode->mnemonic);
5423 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5424 if (mnemo == NULL || key == NULL)
5425 return NULL;
5426 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5427 return NULL;
5428 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5429 return NULL;
5430 Py_DECREF(key);
5431 Py_DECREF(mnemo);
5432 errcode++;
5433 }
5434 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5435 return NULL;
5436 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5437 return NULL;
5438
5439 lib_codes_to_names = PyDict_New();
5440 if (lib_codes_to_names == NULL)
5441 return NULL;
5442 libcode = library_codes;
5443 while (libcode->library != NULL) {
5444 PyObject *mnemo, *key;
5445 key = PyLong_FromLong(libcode->code);
5446 mnemo = PyUnicode_FromString(libcode->library);
5447 if (key == NULL || mnemo == NULL)
5448 return NULL;
5449 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5450 return NULL;
5451 Py_DECREF(key);
5452 Py_DECREF(mnemo);
5453 libcode++;
5454 }
5455 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5456 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005457
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005458 /* OpenSSL version */
5459 /* SSLeay() gives us the version of the library linked against,
5460 which could be different from the headers version.
5461 */
5462 libver = SSLeay();
5463 r = PyLong_FromUnsignedLong(libver);
5464 if (r == NULL)
5465 return NULL;
5466 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5467 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005468 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005469 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5470 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5471 return NULL;
5472 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5473 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5474 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005475
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005476 libver = OPENSSL_VERSION_NUMBER;
5477 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5478 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5479 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5480 return NULL;
5481
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005482 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005483}