blob: 2a2c18fe2f73096d0dd37ec8e0d686c15a72f19e [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 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001214
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001215 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001216 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001217
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001218 lst = PyList_New(0);
1219 if (lst == NULL)
1220 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001221
1222 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1223 DIST_POINT *dp;
1224 STACK_OF(GENERAL_NAME) *gns;
1225
1226 dp = sk_DIST_POINT_value(dps, i);
1227 gns = dp->distpoint->name.fullname;
1228
1229 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1230 GENERAL_NAME *gn;
1231 ASN1_IA5STRING *uri;
1232 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001233 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001234
1235 gn = sk_GENERAL_NAME_value(gns, j);
1236 if (gn->type != GEN_URI) {
1237 continue;
1238 }
1239 uri = gn->d.uniformResourceIdentifier;
1240 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1241 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001242 if (ouri == NULL)
1243 goto done;
1244
1245 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001246 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001247 if (err < 0)
1248 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001249 }
1250 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001251
1252 /* Convert to tuple. */
1253 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1254
1255 done:
1256 Py_XDECREF(lst);
Mariatta8e720132017-04-14 18:34:11 -07001257 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001258 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001259}
1260
1261static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001262_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001263
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001264 PyObject *retval = NULL;
1265 BIO *biobuf = NULL;
1266 PyObject *peer;
1267 PyObject *peer_alt_names = NULL;
1268 PyObject *issuer;
1269 PyObject *version;
1270 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001271 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001272 ASN1_INTEGER *serialNumber;
1273 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001274 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001275 ASN1_TIME *notBefore, *notAfter;
1276 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 retval = PyDict_New();
1279 if (retval == NULL)
1280 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001281
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001282 peer = _create_tuple_for_X509_NAME(
1283 X509_get_subject_name(certificate));
1284 if (peer == NULL)
1285 goto fail0;
1286 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1287 Py_DECREF(peer);
1288 goto fail0;
1289 }
1290 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001291
Antoine Pitroufb046912010-11-09 20:21:19 +00001292 issuer = _create_tuple_for_X509_NAME(
1293 X509_get_issuer_name(certificate));
1294 if (issuer == NULL)
1295 goto fail0;
1296 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001297 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001298 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001299 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001300 Py_DECREF(issuer);
1301
1302 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001303 if (version == NULL)
1304 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001305 if (PyDict_SetItemString(retval, "version", version) < 0) {
1306 Py_DECREF(version);
1307 goto fail0;
1308 }
1309 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001310
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001311 /* get a memory buffer */
1312 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001313
Antoine Pitroufb046912010-11-09 20:21:19 +00001314 (void) BIO_reset(biobuf);
1315 serialNumber = X509_get_serialNumber(certificate);
1316 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1317 i2a_ASN1_INTEGER(biobuf, serialNumber);
1318 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1319 if (len < 0) {
1320 _setSSLError(NULL, 0, __FILE__, __LINE__);
1321 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001322 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001323 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1324 if (sn_obj == NULL)
1325 goto fail1;
1326 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1327 Py_DECREF(sn_obj);
1328 goto fail1;
1329 }
1330 Py_DECREF(sn_obj);
1331
1332 (void) BIO_reset(biobuf);
1333 notBefore = X509_get_notBefore(certificate);
1334 ASN1_TIME_print(biobuf, notBefore);
1335 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1336 if (len < 0) {
1337 _setSSLError(NULL, 0, __FILE__, __LINE__);
1338 goto fail1;
1339 }
1340 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1341 if (pnotBefore == NULL)
1342 goto fail1;
1343 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1344 Py_DECREF(pnotBefore);
1345 goto fail1;
1346 }
1347 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001348
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001349 (void) BIO_reset(biobuf);
1350 notAfter = X509_get_notAfter(certificate);
1351 ASN1_TIME_print(biobuf, notAfter);
1352 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1353 if (len < 0) {
1354 _setSSLError(NULL, 0, __FILE__, __LINE__);
1355 goto fail1;
1356 }
1357 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1358 if (pnotAfter == NULL)
1359 goto fail1;
1360 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1361 Py_DECREF(pnotAfter);
1362 goto fail1;
1363 }
1364 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001365
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001367
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 peer_alt_names = _get_peer_alt_names(certificate);
1369 if (peer_alt_names == NULL)
1370 goto fail1;
1371 else if (peer_alt_names != Py_None) {
1372 if (PyDict_SetItemString(retval, "subjectAltName",
1373 peer_alt_names) < 0) {
1374 Py_DECREF(peer_alt_names);
1375 goto fail1;
1376 }
1377 Py_DECREF(peer_alt_names);
1378 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001379
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001380 /* Authority Information Access: OCSP URIs */
1381 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1382 if (obj == NULL) {
1383 goto fail1;
1384 } else if (obj != Py_None) {
1385 result = PyDict_SetItemString(retval, "OCSP", obj);
1386 Py_DECREF(obj);
1387 if (result < 0) {
1388 goto fail1;
1389 }
1390 }
1391
1392 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1393 if (obj == NULL) {
1394 goto fail1;
1395 } else if (obj != Py_None) {
1396 result = PyDict_SetItemString(retval, "caIssuers", obj);
1397 Py_DECREF(obj);
1398 if (result < 0) {
1399 goto fail1;
1400 }
1401 }
1402
1403 /* CDP (CRL distribution points) */
1404 obj = _get_crl_dp(certificate);
1405 if (obj == NULL) {
1406 goto fail1;
1407 } else if (obj != Py_None) {
1408 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1409 Py_DECREF(obj);
1410 if (result < 0) {
1411 goto fail1;
1412 }
1413 }
1414
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001415 BIO_free(biobuf);
1416 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001417
1418 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001419 if (biobuf != NULL)
1420 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001421 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001422 Py_XDECREF(retval);
1423 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001424}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001425
Christian Heimes9a5395a2013-06-17 15:44:12 +02001426static PyObject *
1427_certificate_to_der(X509 *certificate)
1428{
1429 unsigned char *bytes_buf = NULL;
1430 int len;
1431 PyObject *retval;
1432
1433 bytes_buf = NULL;
1434 len = i2d_X509(certificate, &bytes_buf);
1435 if (len < 0) {
1436 _setSSLError(NULL, 0, __FILE__, __LINE__);
1437 return NULL;
1438 }
1439 /* this is actually an immutable bytes sequence */
1440 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1441 OPENSSL_free(bytes_buf);
1442 return retval;
1443}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001444
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001445/*[clinic input]
1446_ssl._test_decode_cert
1447 path: object(converter="PyUnicode_FSConverter")
1448 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001449
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001450[clinic start generated code]*/
1451
1452static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001453_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1454/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001455{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001456 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001457 X509 *x=NULL;
1458 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001459
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001460 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1461 PyErr_SetString(PySSLErrorObject,
1462 "Can't malloc memory to read file");
1463 goto fail0;
1464 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001465
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001466 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001467 PyErr_SetString(PySSLErrorObject,
1468 "Can't open file");
1469 goto fail0;
1470 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001471
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001472 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1473 if (x == NULL) {
1474 PyErr_SetString(PySSLErrorObject,
1475 "Error decoding PEM-encoded file");
1476 goto fail0;
1477 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001478
Antoine Pitroufb046912010-11-09 20:21:19 +00001479 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001480 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001481
1482 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001483 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001484 if (cert != NULL) BIO_free(cert);
1485 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001486}
1487
1488
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001489/*[clinic input]
1490_ssl._SSLSocket.peer_certificate
1491 der as binary_mode: bool = False
1492 /
1493
1494Returns the certificate for the peer.
1495
1496If no certificate was provided, returns None. If a certificate was
1497provided, but not validated, returns an empty dictionary. Otherwise
1498returns a dict containing information about the peer certificate.
1499
1500If the optional argument is True, returns a DER-encoded copy of the
1501peer certificate, or None if no certificate was provided. This will
1502return the certificate even if it wasn't validated.
1503[clinic start generated code]*/
1504
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001505static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001506_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1507/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001508{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001509 int verification;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001510
Antoine Pitrou20b85552013-09-29 19:50:53 +02001511 if (!self->handshake_done) {
1512 PyErr_SetString(PyExc_ValueError,
1513 "handshake not done yet");
1514 return NULL;
1515 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001516 if (!self->peer_cert)
1517 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001518
Antoine Pitrou721738f2012-08-15 23:20:39 +02001519 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001520 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001521 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001523 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 if ((verification & SSL_VERIFY_PEER) == 0)
1525 return PyDict_New();
1526 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001527 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001529}
1530
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001531static PyObject *
1532cipher_to_tuple(const SSL_CIPHER *cipher)
1533{
1534 const char *cipher_name, *cipher_protocol;
1535 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001536 if (retval == NULL)
1537 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001538
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001539 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001540 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001541 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001542 PyTuple_SET_ITEM(retval, 0, Py_None);
1543 } else {
1544 v = PyUnicode_FromString(cipher_name);
1545 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001546 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001547 PyTuple_SET_ITEM(retval, 0, v);
1548 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001549
1550 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001551 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001552 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001553 PyTuple_SET_ITEM(retval, 1, Py_None);
1554 } else {
1555 v = PyUnicode_FromString(cipher_protocol);
1556 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001557 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558 PyTuple_SET_ITEM(retval, 1, v);
1559 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001560
1561 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001562 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, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001565
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001566 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001567
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001568 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001569 Py_DECREF(retval);
1570 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001571}
1572
Christian Heimes25bfcd52016-09-06 00:04:45 +02001573#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1574static PyObject *
1575cipher_to_dict(const SSL_CIPHER *cipher)
1576{
1577 const char *cipher_name, *cipher_protocol;
1578
1579 unsigned long cipher_id;
1580 int alg_bits, strength_bits, len;
1581 char buf[512] = {0};
1582#if OPENSSL_VERSION_1_1
1583 int aead, nid;
1584 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1585#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001586
1587 /* can be NULL */
1588 cipher_name = SSL_CIPHER_get_name(cipher);
1589 cipher_protocol = SSL_CIPHER_get_version(cipher);
1590 cipher_id = SSL_CIPHER_get_id(cipher);
1591 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1592 len = strlen(buf);
1593 if (len > 1 && buf[len-1] == '\n')
1594 buf[len-1] = '\0';
1595 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1596
1597#if OPENSSL_VERSION_1_1
1598 aead = SSL_CIPHER_is_aead(cipher);
1599 nid = SSL_CIPHER_get_cipher_nid(cipher);
1600 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1601 nid = SSL_CIPHER_get_digest_nid(cipher);
1602 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1603 nid = SSL_CIPHER_get_kx_nid(cipher);
1604 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1605 nid = SSL_CIPHER_get_auth_nid(cipher);
1606 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1607#endif
1608
Victor Stinner410b9882016-09-12 12:00:23 +02001609 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001610 "{sksssssssisi"
1611#if OPENSSL_VERSION_1_1
1612 "sOssssssss"
1613#endif
1614 "}",
1615 "id", cipher_id,
1616 "name", cipher_name,
1617 "protocol", cipher_protocol,
1618 "description", buf,
1619 "strength_bits", strength_bits,
1620 "alg_bits", alg_bits
1621#if OPENSSL_VERSION_1_1
1622 ,"aead", aead ? Py_True : Py_False,
1623 "symmetric", skcipher,
1624 "digest", digest,
1625 "kea", kx,
1626 "auth", auth
1627#endif
1628 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001629}
1630#endif
1631
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001632/*[clinic input]
1633_ssl._SSLSocket.shared_ciphers
1634[clinic start generated code]*/
1635
1636static PyObject *
1637_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1638/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001639{
1640 STACK_OF(SSL_CIPHER) *ciphers;
1641 int i;
1642 PyObject *res;
1643
Christian Heimes598894f2016-09-05 23:19:05 +02001644 ciphers = SSL_get_ciphers(self->ssl);
1645 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001646 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001647 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1648 if (!res)
1649 return NULL;
1650 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1651 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1652 if (!tup) {
1653 Py_DECREF(res);
1654 return NULL;
1655 }
1656 PyList_SET_ITEM(res, i, tup);
1657 }
1658 return res;
1659}
1660
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001661/*[clinic input]
1662_ssl._SSLSocket.cipher
1663[clinic start generated code]*/
1664
1665static PyObject *
1666_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1667/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001668{
1669 const SSL_CIPHER *current;
1670
1671 if (self->ssl == NULL)
1672 Py_RETURN_NONE;
1673 current = SSL_get_current_cipher(self->ssl);
1674 if (current == NULL)
1675 Py_RETURN_NONE;
1676 return cipher_to_tuple(current);
1677}
1678
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001679/*[clinic input]
1680_ssl._SSLSocket.version
1681[clinic start generated code]*/
1682
1683static PyObject *
1684_ssl__SSLSocket_version_impl(PySSLSocket *self)
1685/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001686{
1687 const char *version;
1688
1689 if (self->ssl == NULL)
1690 Py_RETURN_NONE;
1691 version = SSL_get_version(self->ssl);
1692 if (!strcmp(version, "unknown"))
1693 Py_RETURN_NONE;
1694 return PyUnicode_FromString(version);
1695}
1696
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001697#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001698/*[clinic input]
1699_ssl._SSLSocket.selected_npn_protocol
1700[clinic start generated code]*/
1701
1702static PyObject *
1703_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1704/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1705{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001706 const unsigned char *out;
1707 unsigned int outlen;
1708
Victor Stinner4569cd52013-06-23 14:58:43 +02001709 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001710 &out, &outlen);
1711
1712 if (out == NULL)
1713 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001714 return PyUnicode_FromStringAndSize((char *)out, outlen);
1715}
1716#endif
1717
1718#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001719/*[clinic input]
1720_ssl._SSLSocket.selected_alpn_protocol
1721[clinic start generated code]*/
1722
1723static PyObject *
1724_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1725/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1726{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001727 const unsigned char *out;
1728 unsigned int outlen;
1729
1730 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1731
1732 if (out == NULL)
1733 Py_RETURN_NONE;
1734 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001735}
1736#endif
1737
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001738/*[clinic input]
1739_ssl._SSLSocket.compression
1740[clinic start generated code]*/
1741
1742static PyObject *
1743_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1744/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1745{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001746#ifdef OPENSSL_NO_COMP
1747 Py_RETURN_NONE;
1748#else
1749 const COMP_METHOD *comp_method;
1750 const char *short_name;
1751
1752 if (self->ssl == NULL)
1753 Py_RETURN_NONE;
1754 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001755 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001756 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001757 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001758 if (short_name == NULL)
1759 Py_RETURN_NONE;
1760 return PyUnicode_DecodeFSDefault(short_name);
1761#endif
1762}
1763
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001764static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1765 Py_INCREF(self->ctx);
1766 return self->ctx;
1767}
1768
1769static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1770 void *closure) {
1771
1772 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001773#if !HAVE_SNI
1774 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1775 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001776 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001777#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001778 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001779 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001780 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001781#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001782 } else {
1783 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1784 return -1;
1785 }
1786
1787 return 0;
1788}
1789
1790PyDoc_STRVAR(PySSL_set_context_doc,
1791"_setter_context(ctx)\n\
1792\
1793This changes the context associated with the SSLSocket. This is typically\n\
1794used from within a callback function set by the set_servername_callback\n\
1795on the SSLContext to change the certificate information associated with the\n\
1796SSLSocket before the cryptographic exchange handshake messages\n");
1797
1798
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001799static PyObject *
1800PySSL_get_server_side(PySSLSocket *self, void *c)
1801{
1802 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1803}
1804
1805PyDoc_STRVAR(PySSL_get_server_side_doc,
1806"Whether this is a server-side socket.");
1807
1808static PyObject *
1809PySSL_get_server_hostname(PySSLSocket *self, void *c)
1810{
1811 if (self->server_hostname == NULL)
1812 Py_RETURN_NONE;
1813 Py_INCREF(self->server_hostname);
1814 return self->server_hostname;
1815}
1816
1817PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1818"The currently set server hostname (for SNI).");
1819
1820static PyObject *
1821PySSL_get_owner(PySSLSocket *self, void *c)
1822{
1823 PyObject *owner;
1824
1825 if (self->owner == NULL)
1826 Py_RETURN_NONE;
1827
1828 owner = PyWeakref_GetObject(self->owner);
1829 Py_INCREF(owner);
1830 return owner;
1831}
1832
1833static int
1834PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1835{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001836 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001837 if (self->owner == NULL)
1838 return -1;
1839 return 0;
1840}
1841
1842PyDoc_STRVAR(PySSL_get_owner_doc,
1843"The Python-level owner of this object.\
1844Passed as \"self\" in servername callback.");
1845
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001846
Antoine Pitrou152efa22010-05-16 18:19:27 +00001847static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001848{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001849 if (self->peer_cert) /* Possible not to have one? */
1850 X509_free (self->peer_cert);
1851 if (self->ssl)
1852 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001853 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001854 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001855 Py_XDECREF(self->server_hostname);
1856 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001857 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001858}
1859
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001860/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001861 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001862 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001863 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001864
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001865static int
Victor Stinner14690702015-04-06 22:46:13 +02001866PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001867{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001868 int rc;
1869#ifdef HAVE_POLL
1870 struct pollfd pollfd;
1871 _PyTime_t ms;
1872#else
1873 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001874 fd_set fds;
1875 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001876#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001877
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001878 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001879 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001880 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001881 else if (timeout < 0) {
1882 if (s->sock_timeout > 0)
1883 return SOCKET_HAS_TIMED_OUT;
1884 else
1885 return SOCKET_IS_BLOCKING;
1886 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001887
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001888 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001889 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001890 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001891
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001892 /* Prefer poll, if available, since you can poll() any fd
1893 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001894#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001895 pollfd.fd = s->sock_fd;
1896 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001897
Victor Stinner14690702015-04-06 22:46:13 +02001898 /* timeout is in seconds, poll() uses milliseconds */
1899 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001900 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001901
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001902 PySSL_BEGIN_ALLOW_THREADS
1903 rc = poll(&pollfd, 1, (int)ms);
1904 PySSL_END_ALLOW_THREADS
1905#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001906 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001907 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001908 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001909
Victor Stinner14690702015-04-06 22:46:13 +02001910 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001911
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001912 FD_ZERO(&fds);
1913 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001914
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001915 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001916 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001917 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001918 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001919 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001920 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001921 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001922 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001923#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001924
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001925 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1926 (when we are able to write or when there's something to read) */
1927 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001928}
1929
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001930/*[clinic input]
1931_ssl._SSLSocket.write
1932 b: Py_buffer
1933 /
1934
1935Writes the bytes-like object b into the SSL object.
1936
1937Returns the number of bytes written.
1938[clinic start generated code]*/
1939
1940static PyObject *
1941_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1942/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001943{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001944 int len;
1945 int sockstate;
1946 int err;
1947 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001948 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001949 _PyTime_t timeout, deadline = 0;
1950 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001951
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001952 if (sock != NULL) {
1953 if (((PyObject*)sock) == Py_None) {
1954 _setSSLError("Underlying socket connection gone",
1955 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1956 return NULL;
1957 }
1958 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001959 }
1960
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001961 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001962 PyErr_Format(PyExc_OverflowError,
1963 "string longer than %d bytes", INT_MAX);
1964 goto error;
1965 }
1966
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001967 if (sock != NULL) {
1968 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001969 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001970 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1971 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1972 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001973
Victor Stinner14690702015-04-06 22:46:13 +02001974 timeout = GET_SOCKET_TIMEOUT(sock);
1975 has_timeout = (timeout > 0);
1976 if (has_timeout)
1977 deadline = _PyTime_GetMonotonicClock() + timeout;
1978
1979 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001980 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001981 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001982 "The write operation timed out");
1983 goto error;
1984 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1985 PyErr_SetString(PySSLErrorObject,
1986 "Underlying socket has been closed.");
1987 goto error;
1988 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1989 PyErr_SetString(PySSLErrorObject,
1990 "Underlying socket too large for select().");
1991 goto error;
1992 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001993
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001994 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001995 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001996 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001997 err = SSL_get_error(self->ssl, len);
1998 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001999
2000 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002001 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002002
Victor Stinner14690702015-04-06 22:46:13 +02002003 if (has_timeout)
2004 timeout = deadline - _PyTime_GetMonotonicClock();
2005
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002006 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002007 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002008 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002009 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002010 } else {
2011 sockstate = SOCKET_OPERATION_OK;
2012 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002013
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002014 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002015 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002016 "The write operation timed out");
2017 goto error;
2018 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2019 PyErr_SetString(PySSLErrorObject,
2020 "Underlying socket has been closed.");
2021 goto error;
2022 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2023 break;
2024 }
2025 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002026
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002027 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002028 if (len > 0)
2029 return PyLong_FromLong(len);
2030 else
2031 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002032
2033error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002034 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002035 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002036}
2037
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002038/*[clinic input]
2039_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002040
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002041Returns the number of already decrypted bytes available for read, pending on the connection.
2042[clinic start generated code]*/
2043
2044static PyObject *
2045_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2046/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002047{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002048 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002049
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002050 PySSL_BEGIN_ALLOW_THREADS
2051 count = SSL_pending(self->ssl);
2052 PySSL_END_ALLOW_THREADS
2053 if (count < 0)
2054 return PySSL_SetError(self, count, __FILE__, __LINE__);
2055 else
2056 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002057}
2058
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002059/*[clinic input]
2060_ssl._SSLSocket.read
2061 size as len: int
2062 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002063 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002064 ]
2065 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002066
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002067Read up to size bytes from the SSL socket.
2068[clinic start generated code]*/
2069
2070static PyObject *
2071_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2072 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002073/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002074{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002075 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002076 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002077 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002078 int sockstate;
2079 int err;
2080 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002081 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002082 _PyTime_t timeout, deadline = 0;
2083 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002084
Martin Panter5503d472016-03-27 05:35:19 +00002085 if (!group_right_1 && len < 0) {
2086 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2087 return NULL;
2088 }
2089
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002090 if (sock != NULL) {
2091 if (((PyObject*)sock) == Py_None) {
2092 _setSSLError("Underlying socket connection gone",
2093 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2094 return NULL;
2095 }
2096 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002097 }
2098
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002099 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002100 dest = PyBytes_FromStringAndSize(NULL, len);
2101 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002102 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002103 if (len == 0) {
2104 Py_XDECREF(sock);
2105 return dest;
2106 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002107 mem = PyBytes_AS_STRING(dest);
2108 }
2109 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002110 mem = buffer->buf;
2111 if (len <= 0 || len > buffer->len) {
2112 len = (int) buffer->len;
2113 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002114 PyErr_SetString(PyExc_OverflowError,
2115 "maximum length can't fit in a C 'int'");
2116 goto error;
2117 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002118 if (len == 0) {
2119 count = 0;
2120 goto done;
2121 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002122 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002123 }
2124
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002125 if (sock != NULL) {
2126 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002127 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002128 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2129 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2130 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002131
Victor Stinner14690702015-04-06 22:46:13 +02002132 timeout = GET_SOCKET_TIMEOUT(sock);
2133 has_timeout = (timeout > 0);
2134 if (has_timeout)
2135 deadline = _PyTime_GetMonotonicClock() + timeout;
2136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002137 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002138 PySSL_BEGIN_ALLOW_THREADS
2139 count = SSL_read(self->ssl, mem, len);
2140 err = SSL_get_error(self->ssl, count);
2141 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002142
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002143 if (PyErr_CheckSignals())
2144 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002145
Victor Stinner14690702015-04-06 22:46:13 +02002146 if (has_timeout)
2147 timeout = deadline - _PyTime_GetMonotonicClock();
2148
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002149 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002150 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002151 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002152 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002153 } else if (err == SSL_ERROR_ZERO_RETURN &&
2154 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002155 {
2156 count = 0;
2157 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002158 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002159 else
2160 sockstate = SOCKET_OPERATION_OK;
2161
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002162 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002163 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002164 "The read operation timed out");
2165 goto error;
2166 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2167 break;
2168 }
2169 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002170
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002171 if (count <= 0) {
2172 PySSL_SetError(self, count, __FILE__, __LINE__);
2173 goto error;
2174 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002175
2176done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002177 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002178 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002179 _PyBytes_Resize(&dest, count);
2180 return dest;
2181 }
2182 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002183 return PyLong_FromLong(count);
2184 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002185
2186error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002187 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002188 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002189 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002190 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002191}
2192
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002193/*[clinic input]
2194_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002195
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002196Does the SSL shutdown handshake with the remote end.
2197
2198Returns the underlying socket object.
2199[clinic start generated code]*/
2200
2201static PyObject *
2202_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2203/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002204{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002205 int err, ssl_err, sockstate, nonblocking;
2206 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002207 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002208 _PyTime_t timeout, deadline = 0;
2209 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002210
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002211 if (sock != NULL) {
2212 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002213 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002214 _setSSLError("Underlying socket connection gone",
2215 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2216 return NULL;
2217 }
2218 Py_INCREF(sock);
2219
2220 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002221 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002222 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2223 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002224 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002225
Victor Stinner14690702015-04-06 22:46:13 +02002226 timeout = GET_SOCKET_TIMEOUT(sock);
2227 has_timeout = (timeout > 0);
2228 if (has_timeout)
2229 deadline = _PyTime_GetMonotonicClock() + timeout;
2230
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002231 while (1) {
2232 PySSL_BEGIN_ALLOW_THREADS
2233 /* Disable read-ahead so that unwrap can work correctly.
2234 * Otherwise OpenSSL might read in too much data,
2235 * eating clear text data that happens to be
2236 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002237 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002238 * function is used and the shutdown_seen_zero != 0
2239 * condition is met.
2240 */
2241 if (self->shutdown_seen_zero)
2242 SSL_set_read_ahead(self->ssl, 0);
2243 err = SSL_shutdown(self->ssl);
2244 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002245
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002246 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2247 if (err > 0)
2248 break;
2249 if (err == 0) {
2250 /* Don't loop endlessly; instead preserve legacy
2251 behaviour of trying SSL_shutdown() only twice.
2252 This looks necessary for OpenSSL < 0.9.8m */
2253 if (++zeros > 1)
2254 break;
2255 /* Shutdown was sent, now try receiving */
2256 self->shutdown_seen_zero = 1;
2257 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002258 }
2259
Victor Stinner14690702015-04-06 22:46:13 +02002260 if (has_timeout)
2261 timeout = deadline - _PyTime_GetMonotonicClock();
2262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002263 /* Possibly retry shutdown until timeout or failure */
2264 ssl_err = SSL_get_error(self->ssl, err);
2265 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002266 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002267 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002268 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002269 else
2270 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002271
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002272 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2273 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002274 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002275 "The read operation timed out");
2276 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002277 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002278 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002279 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002280 }
2281 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2282 PyErr_SetString(PySSLErrorObject,
2283 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002284 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002285 }
2286 else if (sockstate != SOCKET_OPERATION_OK)
2287 /* Retain the SSL error code */
2288 break;
2289 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002290
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002291 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002292 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002293 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002294 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002295 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002296 /* It's already INCREF'ed */
2297 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002298 else
2299 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002300
2301error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002302 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002303 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002304}
2305
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002306/*[clinic input]
2307_ssl._SSLSocket.tls_unique_cb
2308
2309Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2310
2311If the TLS handshake is not yet complete, None is returned.
2312[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002313
Antoine Pitroud6494802011-07-21 01:11:30 +02002314static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002315_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2316/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002317{
2318 PyObject *retval = NULL;
2319 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002320 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002321
2322 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2323 /* if session is resumed XOR we are the client */
2324 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2325 }
2326 else {
2327 /* if a new session XOR we are the server */
2328 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2329 }
2330
2331 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002332 if (len == 0)
2333 Py_RETURN_NONE;
2334
2335 retval = PyBytes_FromStringAndSize(buf, len);
2336
2337 return retval;
2338}
2339
Christian Heimes99a65702016-09-10 23:44:53 +02002340#ifdef OPENSSL_VERSION_1_1
2341
2342static SSL_SESSION*
2343_ssl_session_dup(SSL_SESSION *session) {
2344 SSL_SESSION *newsession = NULL;
2345 int slen;
2346 unsigned char *senc = NULL, *p;
2347 const unsigned char *const_p;
2348
2349 if (session == NULL) {
2350 PyErr_SetString(PyExc_ValueError, "Invalid session");
2351 goto error;
2352 }
2353
2354 /* get length */
2355 slen = i2d_SSL_SESSION(session, NULL);
2356 if (slen == 0 || slen > 0xFF00) {
2357 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2358 goto error;
2359 }
2360 if ((senc = PyMem_Malloc(slen)) == NULL) {
2361 PyErr_NoMemory();
2362 goto error;
2363 }
2364 p = senc;
2365 if (!i2d_SSL_SESSION(session, &p)) {
2366 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2367 goto error;
2368 }
2369 const_p = senc;
2370 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2371 if (session == NULL) {
2372 goto error;
2373 }
2374 PyMem_Free(senc);
2375 return newsession;
2376 error:
2377 if (senc != NULL) {
2378 PyMem_Free(senc);
2379 }
2380 return NULL;
2381}
2382#endif
2383
2384static PyObject *
2385PySSL_get_session(PySSLSocket *self, void *closure) {
2386 /* get_session can return sessions from a server-side connection,
2387 * it does not check for handshake done or client socket. */
2388 PySSLSession *pysess;
2389 SSL_SESSION *session;
2390
2391#ifdef OPENSSL_VERSION_1_1
2392 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2393 * https://github.com/openssl/openssl/issues/1550 */
2394 session = SSL_get0_session(self->ssl); /* borrowed reference */
2395 if (session == NULL) {
2396 Py_RETURN_NONE;
2397 }
2398 if ((session = _ssl_session_dup(session)) == NULL) {
2399 return NULL;
2400 }
2401#else
2402 session = SSL_get1_session(self->ssl);
2403 if (session == NULL) {
2404 Py_RETURN_NONE;
2405 }
2406#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002407 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002408 if (pysess == NULL) {
2409 SSL_SESSION_free(session);
2410 return NULL;
2411 }
2412
2413 assert(self->ctx);
2414 pysess->ctx = self->ctx;
2415 Py_INCREF(pysess->ctx);
2416 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002417 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002418 return (PyObject *)pysess;
2419}
2420
2421static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2422 void *closure)
2423 {
2424 PySSLSession *pysess;
2425#ifdef OPENSSL_VERSION_1_1
2426 SSL_SESSION *session;
2427#endif
2428 int result;
2429
2430 if (!PySSLSession_Check(value)) {
2431 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2432 return -1;
2433 }
2434 pysess = (PySSLSession *)value;
2435
2436 if (self->ctx->ctx != pysess->ctx->ctx) {
2437 PyErr_SetString(PyExc_ValueError,
2438 "Session refers to a different SSLContext.");
2439 return -1;
2440 }
2441 if (self->socket_type != PY_SSL_CLIENT) {
2442 PyErr_SetString(PyExc_ValueError,
2443 "Cannot set session for server-side SSLSocket.");
2444 return -1;
2445 }
2446 if (self->handshake_done) {
2447 PyErr_SetString(PyExc_ValueError,
2448 "Cannot set session after handshake.");
2449 return -1;
2450 }
2451#ifdef OPENSSL_VERSION_1_1
2452 /* duplicate session */
2453 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2454 return -1;
2455 }
2456 result = SSL_set_session(self->ssl, session);
2457 /* free duplicate, SSL_set_session() bumps ref count */
2458 SSL_SESSION_free(session);
2459#else
2460 result = SSL_set_session(self->ssl, pysess->session);
2461#endif
2462 if (result == 0) {
2463 _setSSLError(NULL, 0, __FILE__, __LINE__);
2464 return -1;
2465 }
2466 return 0;
2467}
2468
2469PyDoc_STRVAR(PySSL_set_session_doc,
2470"_setter_session(session)\n\
2471\
2472Get / set SSLSession.");
2473
2474static PyObject *
2475PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2476 if (SSL_session_reused(self->ssl)) {
2477 Py_RETURN_TRUE;
2478 } else {
2479 Py_RETURN_FALSE;
2480 }
2481}
2482
2483PyDoc_STRVAR(PySSL_get_session_reused_doc,
2484"Was the client session reused during handshake?");
2485
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002486static PyGetSetDef ssl_getsetlist[] = {
2487 {"context", (getter) PySSL_get_context,
2488 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002489 {"server_side", (getter) PySSL_get_server_side, NULL,
2490 PySSL_get_server_side_doc},
2491 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2492 PySSL_get_server_hostname_doc},
2493 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2494 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002495 {"session", (getter) PySSL_get_session,
2496 (setter) PySSL_set_session, PySSL_set_session_doc},
2497 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2498 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002499 {NULL}, /* sentinel */
2500};
2501
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002502static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002503 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2504 _SSL__SSLSOCKET_WRITE_METHODDEF
2505 _SSL__SSLSOCKET_READ_METHODDEF
2506 _SSL__SSLSOCKET_PENDING_METHODDEF
2507 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2508 _SSL__SSLSOCKET_CIPHER_METHODDEF
2509 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2510 _SSL__SSLSOCKET_VERSION_METHODDEF
2511 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2512 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2513 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2514 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2515 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002516 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002517};
2518
Antoine Pitrou152efa22010-05-16 18:19:27 +00002519static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002520 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002521 "_ssl._SSLSocket", /*tp_name*/
2522 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002523 0, /*tp_itemsize*/
2524 /* methods */
2525 (destructor)PySSL_dealloc, /*tp_dealloc*/
2526 0, /*tp_print*/
2527 0, /*tp_getattr*/
2528 0, /*tp_setattr*/
2529 0, /*tp_reserved*/
2530 0, /*tp_repr*/
2531 0, /*tp_as_number*/
2532 0, /*tp_as_sequence*/
2533 0, /*tp_as_mapping*/
2534 0, /*tp_hash*/
2535 0, /*tp_call*/
2536 0, /*tp_str*/
2537 0, /*tp_getattro*/
2538 0, /*tp_setattro*/
2539 0, /*tp_as_buffer*/
2540 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2541 0, /*tp_doc*/
2542 0, /*tp_traverse*/
2543 0, /*tp_clear*/
2544 0, /*tp_richcompare*/
2545 0, /*tp_weaklistoffset*/
2546 0, /*tp_iter*/
2547 0, /*tp_iternext*/
2548 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002549 0, /*tp_members*/
2550 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002551};
2552
Antoine Pitrou152efa22010-05-16 18:19:27 +00002553
2554/*
2555 * _SSLContext objects
2556 */
2557
Christian Heimes5fe668c2016-09-12 00:01:11 +02002558static int
2559_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2560{
2561 int mode;
2562 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2563
2564 switch(n) {
2565 case PY_SSL_CERT_NONE:
2566 mode = SSL_VERIFY_NONE;
2567 break;
2568 case PY_SSL_CERT_OPTIONAL:
2569 mode = SSL_VERIFY_PEER;
2570 break;
2571 case PY_SSL_CERT_REQUIRED:
2572 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2573 break;
2574 default:
2575 PyErr_SetString(PyExc_ValueError,
2576 "invalid value for verify_mode");
2577 return -1;
2578 }
2579 /* keep current verify cb */
2580 verify_cb = SSL_CTX_get_verify_callback(ctx);
2581 SSL_CTX_set_verify(ctx, mode, verify_cb);
2582 return 0;
2583}
2584
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002585/*[clinic input]
2586@classmethod
2587_ssl._SSLContext.__new__
2588 protocol as proto_version: int
2589 /
2590[clinic start generated code]*/
2591
Antoine Pitrou152efa22010-05-16 18:19:27 +00002592static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002593_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2594/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002595{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002596 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002597 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002598 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002599 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002600#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002601 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002602#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002603
Antoine Pitrou152efa22010-05-16 18:19:27 +00002604 PySSL_BEGIN_ALLOW_THREADS
2605 if (proto_version == PY_SSL_VERSION_TLS1)
2606 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002607#if HAVE_TLSv1_2
2608 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2609 ctx = SSL_CTX_new(TLSv1_1_method());
2610 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2611 ctx = SSL_CTX_new(TLSv1_2_method());
2612#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002613#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002614 else if (proto_version == PY_SSL_VERSION_SSL3)
2615 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002616#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002617#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002618 else if (proto_version == PY_SSL_VERSION_SSL2)
2619 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002620#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002621 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002622 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002623 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2624 ctx = SSL_CTX_new(TLS_client_method());
2625 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2626 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002627 else
2628 proto_version = -1;
2629 PySSL_END_ALLOW_THREADS
2630
2631 if (proto_version == -1) {
2632 PyErr_SetString(PyExc_ValueError,
2633 "invalid protocol version");
2634 return NULL;
2635 }
2636 if (ctx == NULL) {
2637 PyErr_SetString(PySSLErrorObject,
2638 "failed to allocate SSL context");
2639 return NULL;
2640 }
2641
2642 assert(type != NULL && type->tp_alloc != NULL);
2643 self = (PySSLContext *) type->tp_alloc(type, 0);
2644 if (self == NULL) {
2645 SSL_CTX_free(ctx);
2646 return NULL;
2647 }
2648 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002649#ifdef OPENSSL_NPN_NEGOTIATED
2650 self->npn_protocols = NULL;
2651#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002652#ifdef HAVE_ALPN
2653 self->alpn_protocols = NULL;
2654#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002655#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002656 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002657#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002658 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002659 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2660 self->check_hostname = 1;
2661 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2662 Py_DECREF(self);
2663 return NULL;
2664 }
2665 } else {
2666 self->check_hostname = 0;
2667 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2668 Py_DECREF(self);
2669 return NULL;
2670 }
2671 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002672 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002673 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2674 if (proto_version != PY_SSL_VERSION_SSL2)
2675 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002676 if (proto_version != PY_SSL_VERSION_SSL3)
2677 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002678 /* Minimal security flags for server and client side context.
2679 * Client sockets ignore server-side parameters. */
2680#ifdef SSL_OP_NO_COMPRESSION
2681 options |= SSL_OP_NO_COMPRESSION;
2682#endif
2683#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2684 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2685#endif
2686#ifdef SSL_OP_SINGLE_DH_USE
2687 options |= SSL_OP_SINGLE_DH_USE;
2688#endif
2689#ifdef SSL_OP_SINGLE_ECDH_USE
2690 options |= SSL_OP_SINGLE_ECDH_USE;
2691#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002692 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002693
Christian Heimes358cfd42016-09-10 22:43:48 +02002694 /* A bare minimum cipher list without completly broken cipher suites.
2695 * It's far from perfect but gives users a better head start. */
2696 if (proto_version != PY_SSL_VERSION_SSL2) {
2697 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2698 } else {
2699 /* SSLv2 needs MD5 */
2700 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2701 }
2702 if (result == 0) {
2703 Py_DECREF(self);
2704 ERR_clear_error();
2705 PyErr_SetString(PySSLErrorObject,
2706 "No cipher can be selected.");
2707 return NULL;
2708 }
2709
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002710#if defined(SSL_MODE_RELEASE_BUFFERS)
2711 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2712 usage for no cost at all. However, don't do this for OpenSSL versions
2713 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2714 2014-0198. I can't find exactly which beta fixed this CVE, so be
2715 conservative and assume it wasn't fixed until release. We do this check
2716 at runtime to avoid problems from the dynamic linker.
2717 See #25672 for more on this. */
2718 libver = SSLeay();
2719 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2720 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2721 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2722 }
2723#endif
2724
2725
Donald Stufft784ba7c2017-03-02 12:32:13 -05002726#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002727 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2728 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002729 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2730 */
Donald Stufft784ba7c2017-03-02 12:32:13 -05002731#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002732 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2733#else
2734 {
2735 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2736 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2737 EC_KEY_free(key);
2738 }
2739#endif
2740#endif
2741
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002742#define SID_CTX "Python"
2743 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2744 sizeof(SID_CTX));
2745#undef SID_CTX
2746
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002747#ifdef X509_V_FLAG_TRUSTED_FIRST
2748 {
2749 /* Improve trust chain building when cross-signed intermediate
2750 certificates are present. See https://bugs.python.org/issue23476. */
2751 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2752 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2753 }
2754#endif
2755
Antoine Pitrou152efa22010-05-16 18:19:27 +00002756 return (PyObject *)self;
2757}
2758
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002759static int
2760context_traverse(PySSLContext *self, visitproc visit, void *arg)
2761{
2762#ifndef OPENSSL_NO_TLSEXT
2763 Py_VISIT(self->set_hostname);
2764#endif
2765 return 0;
2766}
2767
2768static int
2769context_clear(PySSLContext *self)
2770{
2771#ifndef OPENSSL_NO_TLSEXT
2772 Py_CLEAR(self->set_hostname);
2773#endif
2774 return 0;
2775}
2776
Antoine Pitrou152efa22010-05-16 18:19:27 +00002777static void
2778context_dealloc(PySSLContext *self)
2779{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002780 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002781 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002782#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002783 PyMem_FREE(self->npn_protocols);
2784#endif
2785#ifdef HAVE_ALPN
2786 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002787#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002788 Py_TYPE(self)->tp_free(self);
2789}
2790
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002791/*[clinic input]
2792_ssl._SSLContext.set_ciphers
2793 cipherlist: str
2794 /
2795[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002796
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002797static PyObject *
2798_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2799/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2800{
2801 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002802 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002803 /* Clearing the error queue is necessary on some OpenSSL versions,
2804 otherwise the error will be reported again when another SSL call
2805 is done. */
2806 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002807 PyErr_SetString(PySSLErrorObject,
2808 "No cipher can be selected.");
2809 return NULL;
2810 }
2811 Py_RETURN_NONE;
2812}
2813
Christian Heimes25bfcd52016-09-06 00:04:45 +02002814#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2815/*[clinic input]
2816_ssl._SSLContext.get_ciphers
2817[clinic start generated code]*/
2818
2819static PyObject *
2820_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2821/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2822{
2823 SSL *ssl = NULL;
2824 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002825 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002826 int i=0;
2827 PyObject *result = NULL, *dct;
2828
2829 ssl = SSL_new(self->ctx);
2830 if (ssl == NULL) {
2831 _setSSLError(NULL, 0, __FILE__, __LINE__);
2832 goto exit;
2833 }
2834 sk = SSL_get_ciphers(ssl);
2835
2836 result = PyList_New(sk_SSL_CIPHER_num(sk));
2837 if (result == NULL) {
2838 goto exit;
2839 }
2840
2841 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2842 cipher = sk_SSL_CIPHER_value(sk, i);
2843 dct = cipher_to_dict(cipher);
2844 if (dct == NULL) {
2845 Py_CLEAR(result);
2846 goto exit;
2847 }
2848 PyList_SET_ITEM(result, i, dct);
2849 }
2850
2851 exit:
2852 if (ssl != NULL)
2853 SSL_free(ssl);
2854 return result;
2855
2856}
2857#endif
2858
2859
Benjamin Petersonc54de472015-01-28 12:06:39 -05002860#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002861static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002862do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2863 const unsigned char *server_protocols, unsigned int server_protocols_len,
2864 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002865{
Benjamin Peterson88615022015-01-23 17:30:26 -05002866 int ret;
2867 if (client_protocols == NULL) {
2868 client_protocols = (unsigned char *)"";
2869 client_protocols_len = 0;
2870 }
2871 if (server_protocols == NULL) {
2872 server_protocols = (unsigned char *)"";
2873 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002874 }
2875
Benjamin Peterson88615022015-01-23 17:30:26 -05002876 ret = SSL_select_next_proto(out, outlen,
2877 server_protocols, server_protocols_len,
2878 client_protocols, client_protocols_len);
2879 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2880 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002881
2882 return SSL_TLSEXT_ERR_OK;
2883}
2884
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002885/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2886static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002887_advertiseNPN_cb(SSL *s,
2888 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002889 void *args)
2890{
2891 PySSLContext *ssl_ctx = (PySSLContext *) args;
2892
2893 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002894 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002895 *len = 0;
2896 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002897 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002898 *len = ssl_ctx->npn_protocols_len;
2899 }
2900
2901 return SSL_TLSEXT_ERR_OK;
2902}
2903/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2904static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002905_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002906 unsigned char **out, unsigned char *outlen,
2907 const unsigned char *server, unsigned int server_len,
2908 void *args)
2909{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002910 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002911 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002912 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002913}
2914#endif
2915
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002916/*[clinic input]
2917_ssl._SSLContext._set_npn_protocols
2918 protos: Py_buffer
2919 /
2920[clinic start generated code]*/
2921
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002922static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002923_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2924 Py_buffer *protos)
2925/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002926{
2927#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002928 PyMem_Free(self->npn_protocols);
2929 self->npn_protocols = PyMem_Malloc(protos->len);
2930 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002931 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002932 memcpy(self->npn_protocols, protos->buf, protos->len);
2933 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002934
2935 /* set both server and client callbacks, because the context can
2936 * be used to create both types of sockets */
2937 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2938 _advertiseNPN_cb,
2939 self);
2940 SSL_CTX_set_next_proto_select_cb(self->ctx,
2941 _selectNPN_cb,
2942 self);
2943
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002944 Py_RETURN_NONE;
2945#else
2946 PyErr_SetString(PyExc_NotImplementedError,
2947 "The NPN extension requires OpenSSL 1.0.1 or later.");
2948 return NULL;
2949#endif
2950}
2951
Benjamin Petersoncca27322015-01-23 16:35:37 -05002952#ifdef HAVE_ALPN
2953static int
2954_selectALPN_cb(SSL *s,
2955 const unsigned char **out, unsigned char *outlen,
2956 const unsigned char *client_protocols, unsigned int client_protocols_len,
2957 void *args)
2958{
2959 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002960 return do_protocol_selection(1, (unsigned char **)out, outlen,
2961 ctx->alpn_protocols, ctx->alpn_protocols_len,
2962 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002963}
2964#endif
2965
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002966/*[clinic input]
2967_ssl._SSLContext._set_alpn_protocols
2968 protos: Py_buffer
2969 /
2970[clinic start generated code]*/
2971
Benjamin Petersoncca27322015-01-23 16:35:37 -05002972static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002973_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2974 Py_buffer *protos)
2975/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002976{
2977#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002978 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002979 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002980 if (!self->alpn_protocols)
2981 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002982 memcpy(self->alpn_protocols, protos->buf, protos->len);
2983 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002984
2985 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2986 return PyErr_NoMemory();
2987 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2988
Benjamin Petersoncca27322015-01-23 16:35:37 -05002989 Py_RETURN_NONE;
2990#else
2991 PyErr_SetString(PyExc_NotImplementedError,
2992 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2993 return NULL;
2994#endif
2995}
2996
Antoine Pitrou152efa22010-05-16 18:19:27 +00002997static PyObject *
2998get_verify_mode(PySSLContext *self, void *c)
2999{
3000 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3001 case SSL_VERIFY_NONE:
3002 return PyLong_FromLong(PY_SSL_CERT_NONE);
3003 case SSL_VERIFY_PEER:
3004 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3005 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3006 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3007 }
3008 PyErr_SetString(PySSLErrorObject,
3009 "invalid return value from SSL_CTX_get_verify_mode");
3010 return NULL;
3011}
3012
3013static int
3014set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3015{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003016 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003017 if (!PyArg_Parse(arg, "i", &n))
3018 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003019 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003020 PyErr_SetString(PyExc_ValueError,
3021 "Cannot set verify_mode to CERT_NONE when "
3022 "check_hostname is enabled.");
3023 return -1;
3024 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003025 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003026}
3027
3028static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003029get_verify_flags(PySSLContext *self, void *c)
3030{
3031 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003032 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003033 unsigned long flags;
3034
3035 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003036 param = X509_STORE_get0_param(store);
3037 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003038 return PyLong_FromUnsignedLong(flags);
3039}
3040
3041static int
3042set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3043{
3044 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003045 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003046 unsigned long new_flags, flags, set, clear;
3047
3048 if (!PyArg_Parse(arg, "k", &new_flags))
3049 return -1;
3050 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003051 param = X509_STORE_get0_param(store);
3052 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003053 clear = flags & ~new_flags;
3054 set = ~flags & new_flags;
3055 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003056 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003057 _setSSLError(NULL, 0, __FILE__, __LINE__);
3058 return -1;
3059 }
3060 }
3061 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003062 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003063 _setSSLError(NULL, 0, __FILE__, __LINE__);
3064 return -1;
3065 }
3066 }
3067 return 0;
3068}
3069
3070static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003071get_options(PySSLContext *self, void *c)
3072{
3073 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3074}
3075
3076static int
3077set_options(PySSLContext *self, PyObject *arg, void *c)
3078{
3079 long new_opts, opts, set, clear;
3080 if (!PyArg_Parse(arg, "l", &new_opts))
3081 return -1;
3082 opts = SSL_CTX_get_options(self->ctx);
3083 clear = opts & ~new_opts;
3084 set = ~opts & new_opts;
3085 if (clear) {
3086#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3087 SSL_CTX_clear_options(self->ctx, clear);
3088#else
3089 PyErr_SetString(PyExc_ValueError,
3090 "can't clear options before OpenSSL 0.9.8m");
3091 return -1;
3092#endif
3093 }
3094 if (set)
3095 SSL_CTX_set_options(self->ctx, set);
3096 return 0;
3097}
3098
Christian Heimes1aa9a752013-12-02 02:41:19 +01003099static PyObject *
3100get_check_hostname(PySSLContext *self, void *c)
3101{
3102 return PyBool_FromLong(self->check_hostname);
3103}
3104
3105static int
3106set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3107{
3108 int check_hostname;
3109 if (!PyArg_Parse(arg, "p", &check_hostname))
3110 return -1;
3111 if (check_hostname &&
3112 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3113 PyErr_SetString(PyExc_ValueError,
3114 "check_hostname needs a SSL context with either "
3115 "CERT_OPTIONAL or CERT_REQUIRED");
3116 return -1;
3117 }
3118 self->check_hostname = check_hostname;
3119 return 0;
3120}
3121
3122
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003123typedef struct {
3124 PyThreadState *thread_state;
3125 PyObject *callable;
3126 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003127 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003128 int error;
3129} _PySSLPasswordInfo;
3130
3131static int
3132_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3133 const char *bad_type_error)
3134{
3135 /* Set the password and size fields of a _PySSLPasswordInfo struct
3136 from a unicode, bytes, or byte array object.
3137 The password field will be dynamically allocated and must be freed
3138 by the caller */
3139 PyObject *password_bytes = NULL;
3140 const char *data = NULL;
3141 Py_ssize_t size;
3142
3143 if (PyUnicode_Check(password)) {
3144 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3145 if (!password_bytes) {
3146 goto error;
3147 }
3148 data = PyBytes_AS_STRING(password_bytes);
3149 size = PyBytes_GET_SIZE(password_bytes);
3150 } else if (PyBytes_Check(password)) {
3151 data = PyBytes_AS_STRING(password);
3152 size = PyBytes_GET_SIZE(password);
3153 } else if (PyByteArray_Check(password)) {
3154 data = PyByteArray_AS_STRING(password);
3155 size = PyByteArray_GET_SIZE(password);
3156 } else {
3157 PyErr_SetString(PyExc_TypeError, bad_type_error);
3158 goto error;
3159 }
3160
Victor Stinner9ee02032013-06-23 15:08:23 +02003161 if (size > (Py_ssize_t)INT_MAX) {
3162 PyErr_Format(PyExc_ValueError,
3163 "password cannot be longer than %d bytes", INT_MAX);
3164 goto error;
3165 }
3166
Victor Stinner11ebff22013-07-07 17:07:52 +02003167 PyMem_Free(pw_info->password);
3168 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003169 if (!pw_info->password) {
3170 PyErr_SetString(PyExc_MemoryError,
3171 "unable to allocate password buffer");
3172 goto error;
3173 }
3174 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003175 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003176
3177 Py_XDECREF(password_bytes);
3178 return 1;
3179
3180error:
3181 Py_XDECREF(password_bytes);
3182 return 0;
3183}
3184
3185static int
3186_password_callback(char *buf, int size, int rwflag, void *userdata)
3187{
3188 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3189 PyObject *fn_ret = NULL;
3190
3191 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3192
3193 if (pw_info->callable) {
3194 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
3195 if (!fn_ret) {
3196 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3197 core python API, so we could use it to add a frame here */
3198 goto error;
3199 }
3200
3201 if (!_pwinfo_set(pw_info, fn_ret,
3202 "password callback must return a string")) {
3203 goto error;
3204 }
3205 Py_CLEAR(fn_ret);
3206 }
3207
3208 if (pw_info->size > size) {
3209 PyErr_Format(PyExc_ValueError,
3210 "password cannot be longer than %d bytes", size);
3211 goto error;
3212 }
3213
3214 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3215 memcpy(buf, pw_info->password, pw_info->size);
3216 return pw_info->size;
3217
3218error:
3219 Py_XDECREF(fn_ret);
3220 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3221 pw_info->error = 1;
3222 return -1;
3223}
3224
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003225/*[clinic input]
3226_ssl._SSLContext.load_cert_chain
3227 certfile: object
3228 keyfile: object = NULL
3229 password: object = NULL
3230
3231[clinic start generated code]*/
3232
Antoine Pitroub5218772010-05-21 09:56:06 +00003233static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003234_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3235 PyObject *keyfile, PyObject *password)
3236/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003237{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003238 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003239 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3240 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003241 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003242 int r;
3243
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003244 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003245 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003246 if (keyfile == Py_None)
3247 keyfile = NULL;
3248 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3249 PyErr_SetString(PyExc_TypeError,
3250 "certfile should be a valid filesystem path");
3251 return NULL;
3252 }
3253 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3254 PyErr_SetString(PyExc_TypeError,
3255 "keyfile should be a valid filesystem path");
3256 goto error;
3257 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003258 if (password && password != Py_None) {
3259 if (PyCallable_Check(password)) {
3260 pw_info.callable = password;
3261 } else if (!_pwinfo_set(&pw_info, password,
3262 "password should be a string or callable")) {
3263 goto error;
3264 }
3265 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3266 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3267 }
3268 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003269 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3270 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003271 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003272 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003273 if (pw_info.error) {
3274 ERR_clear_error();
3275 /* the password callback has already set the error information */
3276 }
3277 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003278 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003279 PyErr_SetFromErrno(PyExc_IOError);
3280 }
3281 else {
3282 _setSSLError(NULL, 0, __FILE__, __LINE__);
3283 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003284 goto error;
3285 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003286 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003287 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003288 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3289 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003290 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3291 Py_CLEAR(keyfile_bytes);
3292 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003293 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003294 if (pw_info.error) {
3295 ERR_clear_error();
3296 /* the password callback has already set the error information */
3297 }
3298 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003299 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003300 PyErr_SetFromErrno(PyExc_IOError);
3301 }
3302 else {
3303 _setSSLError(NULL, 0, __FILE__, __LINE__);
3304 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003305 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003306 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003307 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003308 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003309 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003310 if (r != 1) {
3311 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003312 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003313 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003314 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3315 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003316 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003317 Py_RETURN_NONE;
3318
3319error:
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_XDECREF(keyfile_bytes);
3324 Py_XDECREF(certfile_bytes);
3325 return NULL;
3326}
3327
Christian Heimesefff7062013-11-21 03:35:02 +01003328/* internal helper function, returns -1 on error
3329 */
3330static int
3331_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3332 int filetype)
3333{
3334 BIO *biobuf = NULL;
3335 X509_STORE *store;
3336 int retval = 0, err, loaded = 0;
3337
3338 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3339
3340 if (len <= 0) {
3341 PyErr_SetString(PyExc_ValueError,
3342 "Empty certificate data");
3343 return -1;
3344 } else if (len > INT_MAX) {
3345 PyErr_SetString(PyExc_OverflowError,
3346 "Certificate data is too long.");
3347 return -1;
3348 }
3349
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003350 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003351 if (biobuf == NULL) {
3352 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3353 return -1;
3354 }
3355
3356 store = SSL_CTX_get_cert_store(self->ctx);
3357 assert(store != NULL);
3358
3359 while (1) {
3360 X509 *cert = NULL;
3361 int r;
3362
3363 if (filetype == SSL_FILETYPE_ASN1) {
3364 cert = d2i_X509_bio(biobuf, NULL);
3365 } else {
3366 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003367 SSL_CTX_get_default_passwd_cb(self->ctx),
3368 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3369 );
Christian Heimesefff7062013-11-21 03:35:02 +01003370 }
3371 if (cert == NULL) {
3372 break;
3373 }
3374 r = X509_STORE_add_cert(store, cert);
3375 X509_free(cert);
3376 if (!r) {
3377 err = ERR_peek_last_error();
3378 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3379 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3380 /* cert already in hash table, not an error */
3381 ERR_clear_error();
3382 } else {
3383 break;
3384 }
3385 }
3386 loaded++;
3387 }
3388
3389 err = ERR_peek_last_error();
3390 if ((filetype == SSL_FILETYPE_ASN1) &&
3391 (loaded > 0) &&
3392 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3393 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3394 /* EOF ASN1 file, not an error */
3395 ERR_clear_error();
3396 retval = 0;
3397 } else if ((filetype == SSL_FILETYPE_PEM) &&
3398 (loaded > 0) &&
3399 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3400 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3401 /* EOF PEM file, not an error */
3402 ERR_clear_error();
3403 retval = 0;
3404 } else {
3405 _setSSLError(NULL, 0, __FILE__, __LINE__);
3406 retval = -1;
3407 }
3408
3409 BIO_free(biobuf);
3410 return retval;
3411}
3412
3413
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003414/*[clinic input]
3415_ssl._SSLContext.load_verify_locations
3416 cafile: object = NULL
3417 capath: object = NULL
3418 cadata: object = NULL
3419
3420[clinic start generated code]*/
3421
Antoine Pitrou152efa22010-05-16 18:19:27 +00003422static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003423_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3424 PyObject *cafile,
3425 PyObject *capath,
3426 PyObject *cadata)
3427/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003428{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003429 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3430 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003431 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003432
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003433 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003434 if (cafile == Py_None)
3435 cafile = NULL;
3436 if (capath == Py_None)
3437 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003438 if (cadata == Py_None)
3439 cadata = NULL;
3440
3441 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003442 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003443 "cafile, capath and cadata cannot be all omitted");
3444 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003445 }
3446 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3447 PyErr_SetString(PyExc_TypeError,
3448 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003449 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003450 }
3451 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003452 PyErr_SetString(PyExc_TypeError,
3453 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003454 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003455 }
Christian Heimesefff7062013-11-21 03:35:02 +01003456
3457 /* validata cadata type and load cadata */
3458 if (cadata) {
3459 Py_buffer buf;
3460 PyObject *cadata_ascii = NULL;
3461
3462 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3463 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3464 PyBuffer_Release(&buf);
3465 PyErr_SetString(PyExc_TypeError,
3466 "cadata should be a contiguous buffer with "
3467 "a single dimension");
3468 goto error;
3469 }
3470 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3471 PyBuffer_Release(&buf);
3472 if (r == -1) {
3473 goto error;
3474 }
3475 } else {
3476 PyErr_Clear();
3477 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3478 if (cadata_ascii == NULL) {
3479 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003480 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003481 "bytes-like object");
3482 goto error;
3483 }
3484 r = _add_ca_certs(self,
3485 PyBytes_AS_STRING(cadata_ascii),
3486 PyBytes_GET_SIZE(cadata_ascii),
3487 SSL_FILETYPE_PEM);
3488 Py_DECREF(cadata_ascii);
3489 if (r == -1) {
3490 goto error;
3491 }
3492 }
3493 }
3494
3495 /* load cafile or capath */
3496 if (cafile || capath) {
3497 if (cafile)
3498 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3499 if (capath)
3500 capath_buf = PyBytes_AS_STRING(capath_bytes);
3501 PySSL_BEGIN_ALLOW_THREADS
3502 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3503 PySSL_END_ALLOW_THREADS
3504 if (r != 1) {
3505 ok = 0;
3506 if (errno != 0) {
3507 ERR_clear_error();
3508 PyErr_SetFromErrno(PyExc_IOError);
3509 }
3510 else {
3511 _setSSLError(NULL, 0, __FILE__, __LINE__);
3512 }
3513 goto error;
3514 }
3515 }
3516 goto end;
3517
3518 error:
3519 ok = 0;
3520 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003521 Py_XDECREF(cafile_bytes);
3522 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003523 if (ok) {
3524 Py_RETURN_NONE;
3525 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003526 return NULL;
3527 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003528}
3529
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003530/*[clinic input]
3531_ssl._SSLContext.load_dh_params
3532 path as filepath: object
3533 /
3534
3535[clinic start generated code]*/
3536
Antoine Pitrou152efa22010-05-16 18:19:27 +00003537static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003538_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3539/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003540{
3541 FILE *f;
3542 DH *dh;
3543
Victor Stinnerdaf45552013-08-28 00:53:59 +02003544 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003545 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003546 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003547
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003548 errno = 0;
3549 PySSL_BEGIN_ALLOW_THREADS
3550 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003551 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003552 PySSL_END_ALLOW_THREADS
3553 if (dh == NULL) {
3554 if (errno != 0) {
3555 ERR_clear_error();
3556 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3557 }
3558 else {
3559 _setSSLError(NULL, 0, __FILE__, __LINE__);
3560 }
3561 return NULL;
3562 }
3563 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3564 _setSSLError(NULL, 0, __FILE__, __LINE__);
3565 DH_free(dh);
3566 Py_RETURN_NONE;
3567}
3568
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003569/*[clinic input]
3570_ssl._SSLContext._wrap_socket
3571 sock: object(subclass_of="PySocketModule.Sock_Type")
3572 server_side: int
3573 server_hostname as hostname_obj: object = None
3574
3575[clinic start generated code]*/
3576
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003577static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003578_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3579 int server_side, PyObject *hostname_obj)
3580/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003581{
Antoine Pitroud5323212010-10-22 18:19:07 +00003582 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003583 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003584
Antoine Pitroud5323212010-10-22 18:19:07 +00003585 /* server_hostname is either None (or absent), or to be encoded
3586 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003587 if (hostname_obj != Py_None) {
3588 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003589 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003590 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003591
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003592 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3593 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003594 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003595 if (hostname != NULL)
3596 PyMem_Free(hostname);
3597 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003598}
3599
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003600/*[clinic input]
3601_ssl._SSLContext._wrap_bio
3602 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3603 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3604 server_side: int
3605 server_hostname as hostname_obj: object = None
3606
3607[clinic start generated code]*/
3608
Antoine Pitroub0182c82010-10-12 20:09:02 +00003609static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003610_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3611 PySSLMemoryBIO *outgoing, int server_side,
3612 PyObject *hostname_obj)
3613/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003614{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003615 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003616 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003617
3618 /* server_hostname is either None (or absent), or to be encoded
3619 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003620 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003621 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3622 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003623 }
3624
3625 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3626 incoming, outgoing);
3627
3628 PyMem_Free(hostname);
3629 return res;
3630}
3631
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003632/*[clinic input]
3633_ssl._SSLContext.session_stats
3634[clinic start generated code]*/
3635
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003636static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003637_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3638/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003639{
3640 int r;
3641 PyObject *value, *stats = PyDict_New();
3642 if (!stats)
3643 return NULL;
3644
3645#define ADD_STATS(SSL_NAME, KEY_NAME) \
3646 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3647 if (value == NULL) \
3648 goto error; \
3649 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3650 Py_DECREF(value); \
3651 if (r < 0) \
3652 goto error;
3653
3654 ADD_STATS(number, "number");
3655 ADD_STATS(connect, "connect");
3656 ADD_STATS(connect_good, "connect_good");
3657 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3658 ADD_STATS(accept, "accept");
3659 ADD_STATS(accept_good, "accept_good");
3660 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3661 ADD_STATS(accept, "accept");
3662 ADD_STATS(hits, "hits");
3663 ADD_STATS(misses, "misses");
3664 ADD_STATS(timeouts, "timeouts");
3665 ADD_STATS(cache_full, "cache_full");
3666
3667#undef ADD_STATS
3668
3669 return stats;
3670
3671error:
3672 Py_DECREF(stats);
3673 return NULL;
3674}
3675
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003676/*[clinic input]
3677_ssl._SSLContext.set_default_verify_paths
3678[clinic start generated code]*/
3679
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003680static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003681_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3682/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003683{
3684 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3685 _setSSLError(NULL, 0, __FILE__, __LINE__);
3686 return NULL;
3687 }
3688 Py_RETURN_NONE;
3689}
3690
Antoine Pitrou501da612011-12-21 09:27:41 +01003691#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003692/*[clinic input]
3693_ssl._SSLContext.set_ecdh_curve
3694 name: object
3695 /
3696
3697[clinic start generated code]*/
3698
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003699static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003700_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3701/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003702{
3703 PyObject *name_bytes;
3704 int nid;
3705 EC_KEY *key;
3706
3707 if (!PyUnicode_FSConverter(name, &name_bytes))
3708 return NULL;
3709 assert(PyBytes_Check(name_bytes));
3710 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3711 Py_DECREF(name_bytes);
3712 if (nid == 0) {
3713 PyErr_Format(PyExc_ValueError,
3714 "unknown elliptic curve name %R", name);
3715 return NULL;
3716 }
3717 key = EC_KEY_new_by_curve_name(nid);
3718 if (key == NULL) {
3719 _setSSLError(NULL, 0, __FILE__, __LINE__);
3720 return NULL;
3721 }
3722 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3723 EC_KEY_free(key);
3724 Py_RETURN_NONE;
3725}
Antoine Pitrou501da612011-12-21 09:27:41 +01003726#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003727
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003728#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003729static int
3730_servername_callback(SSL *s, int *al, void *args)
3731{
3732 int ret;
3733 PySSLContext *ssl_ctx = (PySSLContext *) args;
3734 PySSLSocket *ssl;
3735 PyObject *servername_o;
3736 PyObject *servername_idna;
3737 PyObject *result;
3738 /* The high-level ssl.SSLSocket object */
3739 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003740 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003741#ifdef WITH_THREAD
3742 PyGILState_STATE gstate = PyGILState_Ensure();
3743#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003744
3745 if (ssl_ctx->set_hostname == NULL) {
3746 /* remove race condition in this the call back while if removing the
3747 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003748#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003749 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003750#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003751 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003752 }
3753
3754 ssl = SSL_get_app_data(s);
3755 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003756
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003757 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003758 * SSL connection and that has a .context attribute that can be changed to
3759 * identify the requested hostname. Since the official API is the Python
3760 * level API we want to pass the callback a Python level object rather than
3761 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3762 * SSLObject) that will be passed. Otherwise if there's a socket then that
3763 * will be passed. If both do not exist only then the C-level object is
3764 * passed. */
3765 if (ssl->owner)
3766 ssl_socket = PyWeakref_GetObject(ssl->owner);
3767 else if (ssl->Socket)
3768 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3769 else
3770 ssl_socket = (PyObject *) ssl;
3771
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003772 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003773 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003774 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003775
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003776 if (servername == NULL) {
3777 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3778 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003779 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003780 else {
3781 servername_o = PyBytes_FromString(servername);
3782 if (servername_o == NULL) {
3783 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3784 goto error;
3785 }
3786 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3787 if (servername_idna == NULL) {
3788 PyErr_WriteUnraisable(servername_o);
3789 Py_DECREF(servername_o);
3790 goto error;
3791 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003792 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003793 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3794 servername_idna, ssl_ctx, NULL);
3795 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003796 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003797 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003798
3799 if (result == NULL) {
3800 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3801 *al = SSL_AD_HANDSHAKE_FAILURE;
3802 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3803 }
3804 else {
3805 if (result != Py_None) {
3806 *al = (int) PyLong_AsLong(result);
3807 if (PyErr_Occurred()) {
3808 PyErr_WriteUnraisable(result);
3809 *al = SSL_AD_INTERNAL_ERROR;
3810 }
3811 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3812 }
3813 else {
3814 ret = SSL_TLSEXT_ERR_OK;
3815 }
3816 Py_DECREF(result);
3817 }
3818
Stefan Krah20d60802013-01-17 17:07:17 +01003819#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003820 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003821#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003822 return ret;
3823
3824error:
3825 Py_DECREF(ssl_socket);
3826 *al = SSL_AD_INTERNAL_ERROR;
3827 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003828#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003829 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003830#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003831 return ret;
3832}
Antoine Pitroua5963382013-03-30 16:39:00 +01003833#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003834
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003835/*[clinic input]
3836_ssl._SSLContext.set_servername_callback
3837 method as cb: object
3838 /
3839
3840Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3841
3842If the argument is None then the callback is disabled. The method is called
3843with the SSLSocket, the server name as a string, and the SSLContext object.
3844See RFC 6066 for details of the SNI extension.
3845[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003846
3847static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003848_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3849/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003850{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003851#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003852 Py_CLEAR(self->set_hostname);
3853 if (cb == Py_None) {
3854 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3855 }
3856 else {
3857 if (!PyCallable_Check(cb)) {
3858 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3859 PyErr_SetString(PyExc_TypeError,
3860 "not a callable object");
3861 return NULL;
3862 }
3863 Py_INCREF(cb);
3864 self->set_hostname = cb;
3865 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3866 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3867 }
3868 Py_RETURN_NONE;
3869#else
3870 PyErr_SetString(PyExc_NotImplementedError,
3871 "The TLS extension servername callback, "
3872 "SSL_CTX_set_tlsext_servername_callback, "
3873 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003874 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003875#endif
3876}
3877
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003878/*[clinic input]
3879_ssl._SSLContext.cert_store_stats
3880
3881Returns quantities of loaded X.509 certificates.
3882
3883X.509 certificates with a CA extension and certificate revocation lists
3884inside the context's cert store.
3885
3886NOTE: Certificates in a capath directory aren't loaded unless they have
3887been used at least once.
3888[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003889
3890static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003891_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3892/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003893{
3894 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003895 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003896 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003897 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003898
3899 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003900 objs = X509_STORE_get0_objects(store);
3901 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3902 obj = sk_X509_OBJECT_value(objs, i);
3903 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003904 case X509_LU_X509:
3905 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003906 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003907 ca++;
3908 }
3909 break;
3910 case X509_LU_CRL:
3911 crl++;
3912 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003913 default:
3914 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3915 * As far as I can tell they are internal states and never
3916 * stored in a cert store */
3917 break;
3918 }
3919 }
3920 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3921 "x509_ca", ca);
3922}
3923
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003924/*[clinic input]
3925_ssl._SSLContext.get_ca_certs
3926 binary_form: bool = False
3927
3928Returns a list of dicts with information of loaded CA certs.
3929
3930If the optional argument is True, returns a DER-encoded copy of the CA
3931certificate.
3932
3933NOTE: Certificates in a capath directory aren't loaded unless they have
3934been used at least once.
3935[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003936
3937static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003938_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3939/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003940{
3941 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003942 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003943 PyObject *ci = NULL, *rlist = NULL;
3944 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003945
3946 if ((rlist = PyList_New(0)) == NULL) {
3947 return NULL;
3948 }
3949
3950 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003951 objs = X509_STORE_get0_objects(store);
3952 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003953 X509_OBJECT *obj;
3954 X509 *cert;
3955
Christian Heimes598894f2016-09-05 23:19:05 +02003956 obj = sk_X509_OBJECT_value(objs, i);
3957 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003958 /* not a x509 cert */
3959 continue;
3960 }
3961 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003962 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003963 if (!X509_check_ca(cert)) {
3964 continue;
3965 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003966 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003967 ci = _certificate_to_der(cert);
3968 } else {
3969 ci = _decode_certificate(cert);
3970 }
3971 if (ci == NULL) {
3972 goto error;
3973 }
3974 if (PyList_Append(rlist, ci) == -1) {
3975 goto error;
3976 }
3977 Py_CLEAR(ci);
3978 }
3979 return rlist;
3980
3981 error:
3982 Py_XDECREF(ci);
3983 Py_XDECREF(rlist);
3984 return NULL;
3985}
3986
3987
Antoine Pitrou152efa22010-05-16 18:19:27 +00003988static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003989 {"check_hostname", (getter) get_check_hostname,
3990 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003991 {"options", (getter) get_options,
3992 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003993 {"verify_flags", (getter) get_verify_flags,
3994 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003995 {"verify_mode", (getter) get_verify_mode,
3996 (setter) set_verify_mode, NULL},
3997 {NULL}, /* sentinel */
3998};
3999
4000static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004001 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4002 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4003 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4004 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4005 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4006 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4007 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4008 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4009 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4010 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4011 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4012 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4013 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4014 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004015 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004016 {NULL, NULL} /* sentinel */
4017};
4018
4019static PyTypeObject PySSLContext_Type = {
4020 PyVarObject_HEAD_INIT(NULL, 0)
4021 "_ssl._SSLContext", /*tp_name*/
4022 sizeof(PySSLContext), /*tp_basicsize*/
4023 0, /*tp_itemsize*/
4024 (destructor)context_dealloc, /*tp_dealloc*/
4025 0, /*tp_print*/
4026 0, /*tp_getattr*/
4027 0, /*tp_setattr*/
4028 0, /*tp_reserved*/
4029 0, /*tp_repr*/
4030 0, /*tp_as_number*/
4031 0, /*tp_as_sequence*/
4032 0, /*tp_as_mapping*/
4033 0, /*tp_hash*/
4034 0, /*tp_call*/
4035 0, /*tp_str*/
4036 0, /*tp_getattro*/
4037 0, /*tp_setattro*/
4038 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004039 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004040 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004041 (traverseproc) context_traverse, /*tp_traverse*/
4042 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004043 0, /*tp_richcompare*/
4044 0, /*tp_weaklistoffset*/
4045 0, /*tp_iter*/
4046 0, /*tp_iternext*/
4047 context_methods, /*tp_methods*/
4048 0, /*tp_members*/
4049 context_getsetlist, /*tp_getset*/
4050 0, /*tp_base*/
4051 0, /*tp_dict*/
4052 0, /*tp_descr_get*/
4053 0, /*tp_descr_set*/
4054 0, /*tp_dictoffset*/
4055 0, /*tp_init*/
4056 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004057 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004058};
4059
4060
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004061/*
4062 * MemoryBIO objects
4063 */
4064
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004065/*[clinic input]
4066@classmethod
4067_ssl.MemoryBIO.__new__
4068
4069[clinic start generated code]*/
4070
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004071static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004072_ssl_MemoryBIO_impl(PyTypeObject *type)
4073/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004074{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004075 BIO *bio;
4076 PySSLMemoryBIO *self;
4077
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004078 bio = BIO_new(BIO_s_mem());
4079 if (bio == NULL) {
4080 PyErr_SetString(PySSLErrorObject,
4081 "failed to allocate BIO");
4082 return NULL;
4083 }
4084 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4085 * just that no data is currently available. The SSL routines should retry
4086 * the read, which we can achieve by calling BIO_set_retry_read(). */
4087 BIO_set_retry_read(bio);
4088 BIO_set_mem_eof_return(bio, -1);
4089
4090 assert(type != NULL && type->tp_alloc != NULL);
4091 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4092 if (self == NULL) {
4093 BIO_free(bio);
4094 return NULL;
4095 }
4096 self->bio = bio;
4097 self->eof_written = 0;
4098
4099 return (PyObject *) self;
4100}
4101
4102static void
4103memory_bio_dealloc(PySSLMemoryBIO *self)
4104{
4105 BIO_free(self->bio);
4106 Py_TYPE(self)->tp_free(self);
4107}
4108
4109static PyObject *
4110memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4111{
4112 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
4113}
4114
4115PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4116"The number of bytes pending in the memory BIO.");
4117
4118static PyObject *
4119memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4120{
4121 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4122 && self->eof_written);
4123}
4124
4125PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4126"Whether the memory BIO is at EOF.");
4127
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004128/*[clinic input]
4129_ssl.MemoryBIO.read
4130 size as len: int = -1
4131 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004132
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004133Read up to size bytes from the memory BIO.
4134
4135If size is not specified, read the entire buffer.
4136If the return value is an empty bytes instance, this means either
4137EOF or that no data is available. Use the "eof" property to
4138distinguish between the two.
4139[clinic start generated code]*/
4140
4141static PyObject *
4142_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4143/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4144{
4145 int avail, nbytes;
4146 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004147
4148 avail = BIO_ctrl_pending(self->bio);
4149 if ((len < 0) || (len > avail))
4150 len = avail;
4151
4152 result = PyBytes_FromStringAndSize(NULL, len);
4153 if ((result == NULL) || (len == 0))
4154 return result;
4155
4156 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4157 /* There should never be any short reads but check anyway. */
4158 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4159 Py_DECREF(result);
4160 return NULL;
4161 }
4162
4163 return result;
4164}
4165
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004166/*[clinic input]
4167_ssl.MemoryBIO.write
4168 b: Py_buffer
4169 /
4170
4171Writes the bytes b into the memory BIO.
4172
4173Returns the number of bytes written.
4174[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004175
4176static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004177_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4178/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004179{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004180 int nbytes;
4181
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004182 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004183 PyErr_Format(PyExc_OverflowError,
4184 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004185 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004186 }
4187
4188 if (self->eof_written) {
4189 PyErr_SetString(PySSLErrorObject,
4190 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004191 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004192 }
4193
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004194 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004195 if (nbytes < 0) {
4196 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004197 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004198 }
4199
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004200 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004201}
4202
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004203/*[clinic input]
4204_ssl.MemoryBIO.write_eof
4205
4206Write an EOF marker to the memory BIO.
4207
4208When all data has been read, the "eof" property will be True.
4209[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004210
4211static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004212_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4213/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004214{
4215 self->eof_written = 1;
4216 /* After an EOF is written, a zero return from read() should be a real EOF
4217 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4218 BIO_clear_retry_flags(self->bio);
4219 BIO_set_mem_eof_return(self->bio, 0);
4220
4221 Py_RETURN_NONE;
4222}
4223
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004224static PyGetSetDef memory_bio_getsetlist[] = {
4225 {"pending", (getter) memory_bio_get_pending, NULL,
4226 PySSL_memory_bio_pending_doc},
4227 {"eof", (getter) memory_bio_get_eof, NULL,
4228 PySSL_memory_bio_eof_doc},
4229 {NULL}, /* sentinel */
4230};
4231
4232static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004233 _SSL_MEMORYBIO_READ_METHODDEF
4234 _SSL_MEMORYBIO_WRITE_METHODDEF
4235 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004236 {NULL, NULL} /* sentinel */
4237};
4238
4239static PyTypeObject PySSLMemoryBIO_Type = {
4240 PyVarObject_HEAD_INIT(NULL, 0)
4241 "_ssl.MemoryBIO", /*tp_name*/
4242 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4243 0, /*tp_itemsize*/
4244 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4245 0, /*tp_print*/
4246 0, /*tp_getattr*/
4247 0, /*tp_setattr*/
4248 0, /*tp_reserved*/
4249 0, /*tp_repr*/
4250 0, /*tp_as_number*/
4251 0, /*tp_as_sequence*/
4252 0, /*tp_as_mapping*/
4253 0, /*tp_hash*/
4254 0, /*tp_call*/
4255 0, /*tp_str*/
4256 0, /*tp_getattro*/
4257 0, /*tp_setattro*/
4258 0, /*tp_as_buffer*/
4259 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4260 0, /*tp_doc*/
4261 0, /*tp_traverse*/
4262 0, /*tp_clear*/
4263 0, /*tp_richcompare*/
4264 0, /*tp_weaklistoffset*/
4265 0, /*tp_iter*/
4266 0, /*tp_iternext*/
4267 memory_bio_methods, /*tp_methods*/
4268 0, /*tp_members*/
4269 memory_bio_getsetlist, /*tp_getset*/
4270 0, /*tp_base*/
4271 0, /*tp_dict*/
4272 0, /*tp_descr_get*/
4273 0, /*tp_descr_set*/
4274 0, /*tp_dictoffset*/
4275 0, /*tp_init*/
4276 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004277 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004278};
4279
Antoine Pitrou152efa22010-05-16 18:19:27 +00004280
Christian Heimes99a65702016-09-10 23:44:53 +02004281/*
4282 * SSL Session object
4283 */
4284
4285static void
4286PySSLSession_dealloc(PySSLSession *self)
4287{
Christian Heimesa5d07652016-09-24 10:48:05 +02004288 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004289 Py_XDECREF(self->ctx);
4290 if (self->session != NULL) {
4291 SSL_SESSION_free(self->session);
4292 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004293 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004294}
4295
4296static PyObject *
4297PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4298{
4299 int result;
4300
4301 if (left == NULL || right == NULL) {
4302 PyErr_BadInternalCall();
4303 return NULL;
4304 }
4305
4306 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4307 Py_RETURN_NOTIMPLEMENTED;
4308 }
4309
4310 if (left == right) {
4311 result = 0;
4312 } else {
4313 const unsigned char *left_id, *right_id;
4314 unsigned int left_len, right_len;
4315 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4316 &left_len);
4317 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4318 &right_len);
4319 if (left_len == right_len) {
4320 result = memcmp(left_id, right_id, left_len);
4321 } else {
4322 result = 1;
4323 }
4324 }
4325
4326 switch (op) {
4327 case Py_EQ:
4328 if (result == 0) {
4329 Py_RETURN_TRUE;
4330 } else {
4331 Py_RETURN_FALSE;
4332 }
4333 break;
4334 case Py_NE:
4335 if (result != 0) {
4336 Py_RETURN_TRUE;
4337 } else {
4338 Py_RETURN_FALSE;
4339 }
4340 break;
4341 case Py_LT:
4342 case Py_LE:
4343 case Py_GT:
4344 case Py_GE:
4345 Py_RETURN_NOTIMPLEMENTED;
4346 break;
4347 default:
4348 PyErr_BadArgument();
4349 return NULL;
4350 }
4351}
4352
4353static int
4354PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4355{
4356 Py_VISIT(self->ctx);
4357 return 0;
4358}
4359
4360static int
4361PySSLSession_clear(PySSLSession *self)
4362{
4363 Py_CLEAR(self->ctx);
4364 return 0;
4365}
4366
4367
4368static PyObject *
4369PySSLSession_get_time(PySSLSession *self, void *closure) {
4370 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4371}
4372
4373PyDoc_STRVAR(PySSLSession_get_time_doc,
4374"Session creation time (seconds since epoch).");
4375
4376
4377static PyObject *
4378PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4379 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4380}
4381
4382PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4383"Session timeout (delta in seconds).");
4384
4385
4386static PyObject *
4387PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4388 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4389 return PyLong_FromUnsignedLong(hint);
4390}
4391
4392PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4393"Ticket life time hint.");
4394
4395
4396static PyObject *
4397PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4398 const unsigned char *id;
4399 unsigned int len;
4400 id = SSL_SESSION_get_id(self->session, &len);
4401 return PyBytes_FromStringAndSize((const char *)id, len);
4402}
4403
4404PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4405"Session id");
4406
4407
4408static PyObject *
4409PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4410 if (SSL_SESSION_has_ticket(self->session)) {
4411 Py_RETURN_TRUE;
4412 } else {
4413 Py_RETURN_FALSE;
4414 }
4415}
4416
4417PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4418"Does the session contain a ticket?");
4419
4420
4421static PyGetSetDef PySSLSession_getsetlist[] = {
4422 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4423 PySSLSession_get_has_ticket_doc},
4424 {"id", (getter) PySSLSession_get_session_id, NULL,
4425 PySSLSession_get_session_id_doc},
4426 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4427 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4428 {"time", (getter) PySSLSession_get_time, NULL,
4429 PySSLSession_get_time_doc},
4430 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4431 PySSLSession_get_timeout_doc},
4432 {NULL}, /* sentinel */
4433};
4434
4435static PyTypeObject PySSLSession_Type = {
4436 PyVarObject_HEAD_INIT(NULL, 0)
4437 "_ssl.Session", /*tp_name*/
4438 sizeof(PySSLSession), /*tp_basicsize*/
4439 0, /*tp_itemsize*/
4440 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4441 0, /*tp_print*/
4442 0, /*tp_getattr*/
4443 0, /*tp_setattr*/
4444 0, /*tp_reserved*/
4445 0, /*tp_repr*/
4446 0, /*tp_as_number*/
4447 0, /*tp_as_sequence*/
4448 0, /*tp_as_mapping*/
4449 0, /*tp_hash*/
4450 0, /*tp_call*/
4451 0, /*tp_str*/
4452 0, /*tp_getattro*/
4453 0, /*tp_setattro*/
4454 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004455 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004456 0, /*tp_doc*/
4457 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4458 (inquiry)PySSLSession_clear, /*tp_clear*/
4459 PySSLSession_richcompare, /*tp_richcompare*/
4460 0, /*tp_weaklistoffset*/
4461 0, /*tp_iter*/
4462 0, /*tp_iternext*/
4463 0, /*tp_methods*/
4464 0, /*tp_members*/
4465 PySSLSession_getsetlist, /*tp_getset*/
4466};
4467
4468
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004469/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004470/*[clinic input]
4471_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004472 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004473 entropy: double
4474 /
4475
4476Mix string into the OpenSSL PRNG state.
4477
4478entropy (a float) is a lower bound on the entropy contained in
4479string. See RFC 1750.
4480[clinic start generated code]*/
4481
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004482static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004483_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
4484/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004485{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004486 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004487 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004488
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004489 buf = (const char *)view->buf;
4490 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004491 do {
4492 written = Py_MIN(len, INT_MAX);
4493 RAND_add(buf, (int)written, entropy);
4494 buf += written;
4495 len -= written;
4496 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004497 Py_INCREF(Py_None);
4498 return Py_None;
4499}
4500
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004501static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004502PySSL_RAND(int len, int pseudo)
4503{
4504 int ok;
4505 PyObject *bytes;
4506 unsigned long err;
4507 const char *errstr;
4508 PyObject *v;
4509
Victor Stinner1e81a392013-12-19 16:47:04 +01004510 if (len < 0) {
4511 PyErr_SetString(PyExc_ValueError, "num must be positive");
4512 return NULL;
4513 }
4514
Victor Stinner99c8b162011-05-24 12:05:19 +02004515 bytes = PyBytes_FromStringAndSize(NULL, len);
4516 if (bytes == NULL)
4517 return NULL;
4518 if (pseudo) {
4519 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4520 if (ok == 0 || ok == 1)
4521 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4522 }
4523 else {
4524 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4525 if (ok == 1)
4526 return bytes;
4527 }
4528 Py_DECREF(bytes);
4529
4530 err = ERR_get_error();
4531 errstr = ERR_reason_error_string(err);
4532 v = Py_BuildValue("(ks)", err, errstr);
4533 if (v != NULL) {
4534 PyErr_SetObject(PySSLErrorObject, v);
4535 Py_DECREF(v);
4536 }
4537 return NULL;
4538}
4539
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004540/*[clinic input]
4541_ssl.RAND_bytes
4542 n: int
4543 /
4544
4545Generate n cryptographically strong pseudo-random bytes.
4546[clinic start generated code]*/
4547
Victor Stinner99c8b162011-05-24 12:05:19 +02004548static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004549_ssl_RAND_bytes_impl(PyObject *module, int n)
4550/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004551{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004552 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004553}
4554
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004555/*[clinic input]
4556_ssl.RAND_pseudo_bytes
4557 n: int
4558 /
4559
4560Generate n pseudo-random bytes.
4561
4562Return a pair (bytes, is_cryptographic). is_cryptographic is True
4563if the bytes generated are cryptographically strong.
4564[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004565
4566static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004567_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4568/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004569{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004570 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004571}
4572
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004573/*[clinic input]
4574_ssl.RAND_status
4575
4576Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4577
4578It is necessary to seed the PRNG with RAND_add() on some platforms before
4579using the ssl() function.
4580[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004581
4582static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004583_ssl_RAND_status_impl(PyObject *module)
4584/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004585{
Christian Heimes217cfd12007-12-02 14:31:20 +00004586 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004587}
4588
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004589#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004590/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004591/*[clinic input]
4592_ssl.RAND_egd
4593 path: object(converter="PyUnicode_FSConverter")
4594 /
4595
4596Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4597
4598Returns number of bytes read. Raises SSLError if connection to EGD
4599fails or if it does not provide enough data to seed PRNG.
4600[clinic start generated code]*/
4601
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004602static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004603_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4604/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004605{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004606 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004607 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004608 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004609 PyErr_SetString(PySSLErrorObject,
4610 "EGD connection failed or EGD did not return "
4611 "enough data to seed the PRNG");
4612 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004613 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004614 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004615}
Christian Heimesa5d07652016-09-24 10:48:05 +02004616/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004617#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004618
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004619
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004620
4621/*[clinic input]
4622_ssl.get_default_verify_paths
4623
4624Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4625
4626The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4627[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004628
4629static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004630_ssl_get_default_verify_paths_impl(PyObject *module)
4631/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004632{
4633 PyObject *ofile_env = NULL;
4634 PyObject *ofile = NULL;
4635 PyObject *odir_env = NULL;
4636 PyObject *odir = NULL;
4637
Benjamin Petersond113c962015-07-18 10:59:13 -07004638#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004639 const char *tmp = (info); \
4640 target = NULL; \
4641 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4642 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4643 target = PyBytes_FromString(tmp); } \
4644 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004645 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004646
Benjamin Petersond113c962015-07-18 10:59:13 -07004647 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4648 CONVERT(X509_get_default_cert_file(), ofile);
4649 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4650 CONVERT(X509_get_default_cert_dir(), odir);
4651#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004652
Christian Heimes200bb1b2013-06-14 15:14:29 +02004653 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004654
4655 error:
4656 Py_XDECREF(ofile_env);
4657 Py_XDECREF(ofile);
4658 Py_XDECREF(odir_env);
4659 Py_XDECREF(odir);
4660 return NULL;
4661}
4662
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004663static PyObject*
4664asn1obj2py(ASN1_OBJECT *obj)
4665{
4666 int nid;
4667 const char *ln, *sn;
4668 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004669 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004670
4671 nid = OBJ_obj2nid(obj);
4672 if (nid == NID_undef) {
4673 PyErr_Format(PyExc_ValueError, "Unknown object");
4674 return NULL;
4675 }
4676 sn = OBJ_nid2sn(nid);
4677 ln = OBJ_nid2ln(nid);
4678 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4679 if (buflen < 0) {
4680 _setSSLError(NULL, 0, __FILE__, __LINE__);
4681 return NULL;
4682 }
4683 if (buflen) {
4684 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4685 } else {
4686 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4687 }
4688}
4689
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004690/*[clinic input]
4691_ssl.txt2obj
4692 txt: str
4693 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004694
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004695Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4696
4697By default objects are looked up by OID. With name=True short and
4698long name are also matched.
4699[clinic start generated code]*/
4700
4701static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004702_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4703/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004704{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004705 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004706 ASN1_OBJECT *obj;
4707
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004708 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4709 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004710 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004711 return NULL;
4712 }
4713 result = asn1obj2py(obj);
4714 ASN1_OBJECT_free(obj);
4715 return result;
4716}
4717
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004718/*[clinic input]
4719_ssl.nid2obj
4720 nid: int
4721 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004722
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004723Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4724[clinic start generated code]*/
4725
4726static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004727_ssl_nid2obj_impl(PyObject *module, int nid)
4728/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004729{
4730 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004731 ASN1_OBJECT *obj;
4732
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004733 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004734 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004735 return NULL;
4736 }
4737 obj = OBJ_nid2obj(nid);
4738 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004739 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004740 return NULL;
4741 }
4742 result = asn1obj2py(obj);
4743 ASN1_OBJECT_free(obj);
4744 return result;
4745}
4746
Christian Heimes46bebee2013-06-09 19:03:31 +02004747#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004748
4749static PyObject*
4750certEncodingType(DWORD encodingType)
4751{
4752 static PyObject *x509_asn = NULL;
4753 static PyObject *pkcs_7_asn = NULL;
4754
4755 if (x509_asn == NULL) {
4756 x509_asn = PyUnicode_InternFromString("x509_asn");
4757 if (x509_asn == NULL)
4758 return NULL;
4759 }
4760 if (pkcs_7_asn == NULL) {
4761 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4762 if (pkcs_7_asn == NULL)
4763 return NULL;
4764 }
4765 switch(encodingType) {
4766 case X509_ASN_ENCODING:
4767 Py_INCREF(x509_asn);
4768 return x509_asn;
4769 case PKCS_7_ASN_ENCODING:
4770 Py_INCREF(pkcs_7_asn);
4771 return pkcs_7_asn;
4772 default:
4773 return PyLong_FromLong(encodingType);
4774 }
4775}
4776
4777static PyObject*
4778parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4779{
4780 CERT_ENHKEY_USAGE *usage;
4781 DWORD size, error, i;
4782 PyObject *retval;
4783
4784 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4785 error = GetLastError();
4786 if (error == CRYPT_E_NOT_FOUND) {
4787 Py_RETURN_TRUE;
4788 }
4789 return PyErr_SetFromWindowsErr(error);
4790 }
4791
4792 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4793 if (usage == NULL) {
4794 return PyErr_NoMemory();
4795 }
4796
4797 /* Now get the actual enhanced usage property */
4798 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4799 PyMem_Free(usage);
4800 error = GetLastError();
4801 if (error == CRYPT_E_NOT_FOUND) {
4802 Py_RETURN_TRUE;
4803 }
4804 return PyErr_SetFromWindowsErr(error);
4805 }
4806 retval = PySet_New(NULL);
4807 if (retval == NULL) {
4808 goto error;
4809 }
4810 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4811 if (usage->rgpszUsageIdentifier[i]) {
4812 PyObject *oid;
4813 int err;
4814 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4815 if (oid == NULL) {
4816 Py_CLEAR(retval);
4817 goto error;
4818 }
4819 err = PySet_Add(retval, oid);
4820 Py_DECREF(oid);
4821 if (err == -1) {
4822 Py_CLEAR(retval);
4823 goto error;
4824 }
4825 }
4826 }
4827 error:
4828 PyMem_Free(usage);
4829 return retval;
4830}
4831
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004832/*[clinic input]
4833_ssl.enum_certificates
4834 store_name: str
4835
4836Retrieve certificates from Windows' cert store.
4837
4838store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4839more cert storages, too. The function returns a list of (bytes,
4840encoding_type, trust) tuples. The encoding_type flag can be interpreted
4841with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4842a set of OIDs or the boolean True.
4843[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004844
Christian Heimes46bebee2013-06-09 19:03:31 +02004845static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004846_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4847/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004848{
Christian Heimes46bebee2013-06-09 19:03:31 +02004849 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004850 PCCERT_CONTEXT pCertCtx = NULL;
4851 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004852 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004853
Christian Heimes44109d72013-11-22 01:51:30 +01004854 result = PyList_New(0);
4855 if (result == NULL) {
4856 return NULL;
4857 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004858 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4859 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4860 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004861 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004862 Py_DECREF(result);
4863 return PyErr_SetFromWindowsErr(GetLastError());
4864 }
4865
Christian Heimes44109d72013-11-22 01:51:30 +01004866 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4867 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4868 pCertCtx->cbCertEncoded);
4869 if (!cert) {
4870 Py_CLEAR(result);
4871 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004872 }
Christian Heimes44109d72013-11-22 01:51:30 +01004873 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4874 Py_CLEAR(result);
4875 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004876 }
Christian Heimes44109d72013-11-22 01:51:30 +01004877 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4878 if (keyusage == Py_True) {
4879 Py_DECREF(keyusage);
4880 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004881 }
Christian Heimes44109d72013-11-22 01:51:30 +01004882 if (keyusage == NULL) {
4883 Py_CLEAR(result);
4884 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004885 }
Christian Heimes44109d72013-11-22 01:51:30 +01004886 if ((tup = PyTuple_New(3)) == NULL) {
4887 Py_CLEAR(result);
4888 break;
4889 }
4890 PyTuple_SET_ITEM(tup, 0, cert);
4891 cert = NULL;
4892 PyTuple_SET_ITEM(tup, 1, enc);
4893 enc = NULL;
4894 PyTuple_SET_ITEM(tup, 2, keyusage);
4895 keyusage = NULL;
4896 if (PyList_Append(result, tup) < 0) {
4897 Py_CLEAR(result);
4898 break;
4899 }
4900 Py_CLEAR(tup);
4901 }
4902 if (pCertCtx) {
4903 /* loop ended with an error, need to clean up context manually */
4904 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004905 }
4906
4907 /* In error cases cert, enc and tup may not be NULL */
4908 Py_XDECREF(cert);
4909 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004910 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004911 Py_XDECREF(tup);
4912
4913 if (!CertCloseStore(hStore, 0)) {
4914 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004915 Py_XDECREF(result);
4916 return PyErr_SetFromWindowsErr(GetLastError());
4917 }
4918 return result;
4919}
4920
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004921/*[clinic input]
4922_ssl.enum_crls
4923 store_name: str
4924
4925Retrieve CRLs from Windows' cert store.
4926
4927store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4928more cert storages, too. The function returns a list of (bytes,
4929encoding_type) tuples. The encoding_type flag can be interpreted with
4930X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4931[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004932
4933static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004934_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4935/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004936{
Christian Heimes44109d72013-11-22 01:51:30 +01004937 HCERTSTORE hStore = NULL;
4938 PCCRL_CONTEXT pCrlCtx = NULL;
4939 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4940 PyObject *result = NULL;
4941
Christian Heimes44109d72013-11-22 01:51:30 +01004942 result = PyList_New(0);
4943 if (result == NULL) {
4944 return NULL;
4945 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004946 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4947 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4948 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004949 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004950 Py_DECREF(result);
4951 return PyErr_SetFromWindowsErr(GetLastError());
4952 }
Christian Heimes44109d72013-11-22 01:51:30 +01004953
4954 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4955 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4956 pCrlCtx->cbCrlEncoded);
4957 if (!crl) {
4958 Py_CLEAR(result);
4959 break;
4960 }
4961 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4962 Py_CLEAR(result);
4963 break;
4964 }
4965 if ((tup = PyTuple_New(2)) == NULL) {
4966 Py_CLEAR(result);
4967 break;
4968 }
4969 PyTuple_SET_ITEM(tup, 0, crl);
4970 crl = NULL;
4971 PyTuple_SET_ITEM(tup, 1, enc);
4972 enc = NULL;
4973
4974 if (PyList_Append(result, tup) < 0) {
4975 Py_CLEAR(result);
4976 break;
4977 }
4978 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004979 }
Christian Heimes44109d72013-11-22 01:51:30 +01004980 if (pCrlCtx) {
4981 /* loop ended with an error, need to clean up context manually */
4982 CertFreeCRLContext(pCrlCtx);
4983 }
4984
4985 /* In error cases cert, enc and tup may not be NULL */
4986 Py_XDECREF(crl);
4987 Py_XDECREF(enc);
4988 Py_XDECREF(tup);
4989
4990 if (!CertCloseStore(hStore, 0)) {
4991 /* This error case might shadow another exception.*/
4992 Py_XDECREF(result);
4993 return PyErr_SetFromWindowsErr(GetLastError());
4994 }
4995 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004996}
Christian Heimes44109d72013-11-22 01:51:30 +01004997
4998#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004999
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005000/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005001static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005002 _SSL__TEST_DECODE_CERT_METHODDEF
5003 _SSL_RAND_ADD_METHODDEF
5004 _SSL_RAND_BYTES_METHODDEF
5005 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5006 _SSL_RAND_EGD_METHODDEF
5007 _SSL_RAND_STATUS_METHODDEF
5008 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5009 _SSL_ENUM_CERTIFICATES_METHODDEF
5010 _SSL_ENUM_CRLS_METHODDEF
5011 _SSL_TXT2OBJ_METHODDEF
5012 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005013 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005014};
5015
5016
Christian Heimes598894f2016-09-05 23:19:05 +02005017#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005018
5019/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005020 * of the Python C thread library
5021 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5022 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005023
5024static PyThread_type_lock *_ssl_locks = NULL;
5025
Christian Heimes4d98ca92013-08-19 17:36:29 +02005026#if OPENSSL_VERSION_NUMBER >= 0x10000000
5027/* use new CRYPTO_THREADID API. */
5028static void
5029_ssl_threadid_callback(CRYPTO_THREADID *id)
5030{
5031 CRYPTO_THREADID_set_numeric(id,
5032 (unsigned long)PyThread_get_thread_ident());
5033}
5034#else
5035/* deprecated CRYPTO_set_id_callback() API. */
5036static unsigned long
5037_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005038 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005039}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005040#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005041
Bill Janssen6e027db2007-11-15 22:23:56 +00005042static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005043 (int mode, int n, const char *file, int line) {
5044 /* this function is needed to perform locking on shared data
5045 structures. (Note that OpenSSL uses a number of global data
5046 structures that will be implicitly shared whenever multiple
5047 threads use OpenSSL.) Multi-threaded applications will
5048 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005049
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005050 locking_function() must be able to handle up to
5051 CRYPTO_num_locks() different mutex locks. It sets the n-th
5052 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005053
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005054 file and line are the file number of the function setting the
5055 lock. They can be useful for debugging.
5056 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005057
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005058 if ((_ssl_locks == NULL) ||
5059 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5060 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005061
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005062 if (mode & CRYPTO_LOCK) {
5063 PyThread_acquire_lock(_ssl_locks[n], 1);
5064 } else {
5065 PyThread_release_lock(_ssl_locks[n]);
5066 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005067}
5068
5069static int _setup_ssl_threads(void) {
5070
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005071 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005072
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005073 if (_ssl_locks == NULL) {
5074 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005075 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5076 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005077 if (_ssl_locks == NULL) {
5078 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005079 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005080 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005081 for (i = 0; i < _ssl_locks_count; i++) {
5082 _ssl_locks[i] = PyThread_allocate_lock();
5083 if (_ssl_locks[i] == NULL) {
5084 unsigned int j;
5085 for (j = 0; j < i; j++) {
5086 PyThread_free_lock(_ssl_locks[j]);
5087 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005088 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005089 return 0;
5090 }
5091 }
5092 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005093#if OPENSSL_VERSION_NUMBER >= 0x10000000
5094 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5095#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005096 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005097#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005098 }
5099 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005100}
5101
Christian Heimes598894f2016-09-05 23:19:05 +02005102#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005103
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005104PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005105"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005106for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005107
Martin v. Löwis1a214512008-06-11 05:26:20 +00005108
5109static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005110 PyModuleDef_HEAD_INIT,
5111 "_ssl",
5112 module_doc,
5113 -1,
5114 PySSL_methods,
5115 NULL,
5116 NULL,
5117 NULL,
5118 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005119};
5120
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005121
5122static void
5123parse_openssl_version(unsigned long libver,
5124 unsigned int *major, unsigned int *minor,
5125 unsigned int *fix, unsigned int *patch,
5126 unsigned int *status)
5127{
5128 *status = libver & 0xF;
5129 libver >>= 4;
5130 *patch = libver & 0xFF;
5131 libver >>= 8;
5132 *fix = libver & 0xFF;
5133 libver >>= 8;
5134 *minor = libver & 0xFF;
5135 libver >>= 8;
5136 *major = libver & 0xFF;
5137}
5138
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005139PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005140PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005141{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005142 PyObject *m, *d, *r;
5143 unsigned long libver;
5144 unsigned int major, minor, fix, patch, status;
5145 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005146 struct py_ssl_error_code *errcode;
5147 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005148
Antoine Pitrou152efa22010-05-16 18:19:27 +00005149 if (PyType_Ready(&PySSLContext_Type) < 0)
5150 return NULL;
5151 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005152 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005153 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5154 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005155 if (PyType_Ready(&PySSLSession_Type) < 0)
5156 return NULL;
5157
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005158
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005159 m = PyModule_Create(&_sslmodule);
5160 if (m == NULL)
5161 return NULL;
5162 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005163
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005164 /* Load _socket module and its C API */
5165 socket_api = PySocketModule_ImportModuleAndAPI();
5166 if (!socket_api)
5167 return NULL;
5168 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005169
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005170 /* Init OpenSSL */
5171 SSL_load_error_strings();
5172 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005173#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02005174#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005175 /* note that this will start threading if not already started */
5176 if (!_setup_ssl_threads()) {
5177 return NULL;
5178 }
Christian Heimes598894f2016-09-05 23:19:05 +02005179#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5180 /* OpenSSL 1.1.0 builtin thread support is enabled */
5181 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005182#endif
Christian Heimes598894f2016-09-05 23:19:05 +02005183#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005184 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005185
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005186 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005187 sslerror_type_slots[0].pfunc = PyExc_OSError;
5188 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005189 if (PySSLErrorObject == NULL)
5190 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005191
Antoine Pitrou41032a62011-10-27 23:56:55 +02005192 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5193 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5194 PySSLErrorObject, NULL);
5195 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5196 "ssl.SSLWantReadError", SSLWantReadError_doc,
5197 PySSLErrorObject, NULL);
5198 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5199 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5200 PySSLErrorObject, NULL);
5201 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5202 "ssl.SSLSyscallError", SSLSyscallError_doc,
5203 PySSLErrorObject, NULL);
5204 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5205 "ssl.SSLEOFError", SSLEOFError_doc,
5206 PySSLErrorObject, NULL);
5207 if (PySSLZeroReturnErrorObject == NULL
5208 || PySSLWantReadErrorObject == NULL
5209 || PySSLWantWriteErrorObject == NULL
5210 || PySSLSyscallErrorObject == NULL
5211 || PySSLEOFErrorObject == NULL)
5212 return NULL;
5213 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5214 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5215 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5216 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5217 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5218 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005219 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005220 if (PyDict_SetItemString(d, "_SSLContext",
5221 (PyObject *)&PySSLContext_Type) != 0)
5222 return NULL;
5223 if (PyDict_SetItemString(d, "_SSLSocket",
5224 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005225 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005226 if (PyDict_SetItemString(d, "MemoryBIO",
5227 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5228 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005229 if (PyDict_SetItemString(d, "SSLSession",
5230 (PyObject *)&PySSLSession_Type) != 0)
5231 return NULL;
5232
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005233 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5234 PY_SSL_ERROR_ZERO_RETURN);
5235 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5236 PY_SSL_ERROR_WANT_READ);
5237 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5238 PY_SSL_ERROR_WANT_WRITE);
5239 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5240 PY_SSL_ERROR_WANT_X509_LOOKUP);
5241 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5242 PY_SSL_ERROR_SYSCALL);
5243 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5244 PY_SSL_ERROR_SSL);
5245 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5246 PY_SSL_ERROR_WANT_CONNECT);
5247 /* non ssl.h errorcodes */
5248 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5249 PY_SSL_ERROR_EOF);
5250 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5251 PY_SSL_ERROR_INVALID_ERROR_CODE);
5252 /* cert requirements */
5253 PyModule_AddIntConstant(m, "CERT_NONE",
5254 PY_SSL_CERT_NONE);
5255 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5256 PY_SSL_CERT_OPTIONAL);
5257 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5258 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005259 /* CRL verification for verification_flags */
5260 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5261 0);
5262 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5263 X509_V_FLAG_CRL_CHECK);
5264 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5265 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5266 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5267 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005268#ifdef X509_V_FLAG_TRUSTED_FIRST
5269 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5270 X509_V_FLAG_TRUSTED_FIRST);
5271#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005272
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005273 /* Alert Descriptions from ssl.h */
5274 /* note RESERVED constants no longer intended for use have been removed */
5275 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5276
5277#define ADD_AD_CONSTANT(s) \
5278 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5279 SSL_AD_##s)
5280
5281 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5282 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5283 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5284 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5285 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5286 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5287 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5288 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5289 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5290 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5291 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5292 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5293 ADD_AD_CONSTANT(UNKNOWN_CA);
5294 ADD_AD_CONSTANT(ACCESS_DENIED);
5295 ADD_AD_CONSTANT(DECODE_ERROR);
5296 ADD_AD_CONSTANT(DECRYPT_ERROR);
5297 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5298 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5299 ADD_AD_CONSTANT(INTERNAL_ERROR);
5300 ADD_AD_CONSTANT(USER_CANCELLED);
5301 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005302 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005303#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5304 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5305#endif
5306#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5307 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5308#endif
5309#ifdef SSL_AD_UNRECOGNIZED_NAME
5310 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5311#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005312#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5313 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5314#endif
5315#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5316 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5317#endif
5318#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5319 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5320#endif
5321
5322#undef ADD_AD_CONSTANT
5323
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005324 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005325#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005326 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5327 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005328#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005329#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005330 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5331 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005332#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005333 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005334 PY_SSL_VERSION_TLS);
5335 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5336 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005337 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5338 PY_SSL_VERSION_TLS_CLIENT);
5339 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5340 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005341 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5342 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005343#if HAVE_TLSv1_2
5344 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5345 PY_SSL_VERSION_TLS1_1);
5346 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5347 PY_SSL_VERSION_TLS1_2);
5348#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005349
Antoine Pitroub5218772010-05-21 09:56:06 +00005350 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005351 PyModule_AddIntConstant(m, "OP_ALL",
5352 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005353 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5354 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5355 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005356#if HAVE_TLSv1_2
5357 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5358 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5359#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005360 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5361 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005362 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005363 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005364#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005365 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005366#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005367#ifdef SSL_OP_NO_COMPRESSION
5368 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5369 SSL_OP_NO_COMPRESSION);
5370#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005371
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005372#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005373 r = Py_True;
5374#else
5375 r = Py_False;
5376#endif
5377 Py_INCREF(r);
5378 PyModule_AddObject(m, "HAS_SNI", r);
5379
Antoine Pitroud6494802011-07-21 01:11:30 +02005380 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005381 Py_INCREF(r);
5382 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5383
Antoine Pitrou501da612011-12-21 09:27:41 +01005384#ifdef OPENSSL_NO_ECDH
5385 r = Py_False;
5386#else
5387 r = Py_True;
5388#endif
5389 Py_INCREF(r);
5390 PyModule_AddObject(m, "HAS_ECDH", r);
5391
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005392#ifdef OPENSSL_NPN_NEGOTIATED
5393 r = Py_True;
5394#else
5395 r = Py_False;
5396#endif
5397 Py_INCREF(r);
5398 PyModule_AddObject(m, "HAS_NPN", r);
5399
Benjamin Petersoncca27322015-01-23 16:35:37 -05005400#ifdef HAVE_ALPN
5401 r = Py_True;
5402#else
5403 r = Py_False;
5404#endif
5405 Py_INCREF(r);
5406 PyModule_AddObject(m, "HAS_ALPN", r);
5407
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005408 /* Mappings for error codes */
5409 err_codes_to_names = PyDict_New();
5410 err_names_to_codes = PyDict_New();
5411 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5412 return NULL;
5413 errcode = error_codes;
5414 while (errcode->mnemonic != NULL) {
5415 PyObject *mnemo, *key;
5416 mnemo = PyUnicode_FromString(errcode->mnemonic);
5417 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5418 if (mnemo == NULL || key == NULL)
5419 return NULL;
5420 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5421 return NULL;
5422 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5423 return NULL;
5424 Py_DECREF(key);
5425 Py_DECREF(mnemo);
5426 errcode++;
5427 }
5428 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5429 return NULL;
5430 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5431 return NULL;
5432
5433 lib_codes_to_names = PyDict_New();
5434 if (lib_codes_to_names == NULL)
5435 return NULL;
5436 libcode = library_codes;
5437 while (libcode->library != NULL) {
5438 PyObject *mnemo, *key;
5439 key = PyLong_FromLong(libcode->code);
5440 mnemo = PyUnicode_FromString(libcode->library);
5441 if (key == NULL || mnemo == NULL)
5442 return NULL;
5443 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5444 return NULL;
5445 Py_DECREF(key);
5446 Py_DECREF(mnemo);
5447 libcode++;
5448 }
5449 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5450 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005451
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005452 /* OpenSSL version */
5453 /* SSLeay() gives us the version of the library linked against,
5454 which could be different from the headers version.
5455 */
5456 libver = SSLeay();
5457 r = PyLong_FromUnsignedLong(libver);
5458 if (r == NULL)
5459 return NULL;
5460 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5461 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005462 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005463 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5464 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5465 return NULL;
5466 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5467 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5468 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005469
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005470 libver = OPENSSL_VERSION_NUMBER;
5471 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5472 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5473 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5474 return NULL;
5475
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005476 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005477}