blob: 68fd2dda25a5638e4acbe024c053cc09253d5262 [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
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200758 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000759
760error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200761 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000762 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000763}
764
Thomas Woutersed03b412007-08-28 21:37:11 +0000765static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000766_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000767
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000768 char namebuf[X509_NAME_MAXLEN];
769 int buflen;
770 PyObject *name_obj;
771 PyObject *value_obj;
772 PyObject *attr;
773 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000774
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000775 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
776 if (buflen < 0) {
777 _setSSLError(NULL, 0, __FILE__, __LINE__);
778 goto fail;
779 }
780 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
781 if (name_obj == NULL)
782 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000783
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000784 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
785 if (buflen < 0) {
786 _setSSLError(NULL, 0, __FILE__, __LINE__);
787 Py_DECREF(name_obj);
788 goto fail;
789 }
790 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000791 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 OPENSSL_free(valuebuf);
793 if (value_obj == NULL) {
794 Py_DECREF(name_obj);
795 goto fail;
796 }
797 attr = PyTuple_New(2);
798 if (attr == NULL) {
799 Py_DECREF(name_obj);
800 Py_DECREF(value_obj);
801 goto fail;
802 }
803 PyTuple_SET_ITEM(attr, 0, name_obj);
804 PyTuple_SET_ITEM(attr, 1, value_obj);
805 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000806
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000808 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000809}
810
811static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000812_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000813{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000814 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
815 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
816 PyObject *rdnt;
817 PyObject *attr = NULL; /* tuple to hold an attribute */
818 int entry_count = X509_NAME_entry_count(xname);
819 X509_NAME_ENTRY *entry;
820 ASN1_OBJECT *name;
821 ASN1_STRING *value;
822 int index_counter;
823 int rdn_level = -1;
824 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000825
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 dn = PyList_New(0);
827 if (dn == NULL)
828 return NULL;
829 /* now create another tuple to hold the top-level RDN */
830 rdn = PyList_New(0);
831 if (rdn == NULL)
832 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000833
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 for (index_counter = 0;
835 index_counter < entry_count;
836 index_counter++)
837 {
838 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000839
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 /* check to see if we've gotten to a new RDN */
841 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200842 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000843 /* yes, new RDN */
844 /* add old RDN to DN */
845 rdnt = PyList_AsTuple(rdn);
846 Py_DECREF(rdn);
847 if (rdnt == NULL)
848 goto fail0;
849 retcode = PyList_Append(dn, rdnt);
850 Py_DECREF(rdnt);
851 if (retcode < 0)
852 goto fail0;
853 /* create new RDN */
854 rdn = PyList_New(0);
855 if (rdn == NULL)
856 goto fail0;
857 }
858 }
Christian Heimes598894f2016-09-05 23:19:05 +0200859 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000860
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000861 /* now add this attribute to the current RDN */
862 name = X509_NAME_ENTRY_get_object(entry);
863 value = X509_NAME_ENTRY_get_data(entry);
864 attr = _create_tuple_for_attribute(name, value);
865 /*
866 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
867 entry->set,
868 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
869 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
870 */
871 if (attr == NULL)
872 goto fail1;
873 retcode = PyList_Append(rdn, attr);
874 Py_DECREF(attr);
875 if (retcode < 0)
876 goto fail1;
877 }
878 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100879 if (rdn != NULL) {
880 if (PyList_GET_SIZE(rdn) > 0) {
881 rdnt = PyList_AsTuple(rdn);
882 Py_DECREF(rdn);
883 if (rdnt == NULL)
884 goto fail0;
885 retcode = PyList_Append(dn, rdnt);
886 Py_DECREF(rdnt);
887 if (retcode < 0)
888 goto fail0;
889 }
890 else {
891 Py_DECREF(rdn);
892 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000893 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000894
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000895 /* convert list to tuple */
896 rdnt = PyList_AsTuple(dn);
897 Py_DECREF(dn);
898 if (rdnt == NULL)
899 return NULL;
900 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000901
902 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000903 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000904
905 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000906 Py_XDECREF(dn);
907 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000908}
909
910static PyObject *
911_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000912
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000913 /* this code follows the procedure outlined in
914 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
915 function to extract the STACK_OF(GENERAL_NAME),
916 then iterates through the stack to add the
917 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000918
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000919 int i, j;
920 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200921 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000922 X509_EXTENSION *ext = NULL;
923 GENERAL_NAMES *names = NULL;
924 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000925 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000926 BIO *biobuf = NULL;
927 char buf[2048];
928 char *vptr;
929 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000931
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 if (certificate == NULL)
933 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000934
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 /* get a memory buffer */
936 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000937
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200938 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000939 while ((i = X509_get_ext_by_NID(
940 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000941
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 if (peer_alt_names == Py_None) {
943 peer_alt_names = PyList_New(0);
944 if (peer_alt_names == NULL)
945 goto fail;
946 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000947
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 /* now decode the altName */
949 ext = X509_get_ext(certificate, i);
950 if(!(method = X509V3_EXT_get(ext))) {
951 PyErr_SetString
952 (PySSLErrorObject,
953 ERRSTR("No method for internalizing subjectAltName!"));
954 goto fail;
955 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000956
Christian Heimes598894f2016-09-05 23:19:05 +0200957 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000958 if (method->it)
959 names = (GENERAL_NAMES*)
960 (ASN1_item_d2i(NULL,
961 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200962 X509_EXTENSION_get_data(ext)->length,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000963 ASN1_ITEM_ptr(method->it)));
964 else
965 names = (GENERAL_NAMES*)
966 (method->d2i(NULL,
967 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200968 X509_EXTENSION_get_data(ext)->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000969
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000971 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200972 int gntype;
973 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000974
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000975 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200976 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200977 switch (gntype) {
978 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000979 /* we special-case DirName as a tuple of
980 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000981
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000982 t = PyTuple_New(2);
983 if (t == NULL) {
984 goto fail;
985 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000986
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000987 v = PyUnicode_FromString("DirName");
988 if (v == NULL) {
989 Py_DECREF(t);
990 goto fail;
991 }
992 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000993
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000994 v = _create_tuple_for_X509_NAME (name->d.dirn);
995 if (v == NULL) {
996 Py_DECREF(t);
997 goto fail;
998 }
999 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001000 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001001
Christian Heimes824f7f32013-08-17 00:54:47 +02001002 case GEN_EMAIL:
1003 case GEN_DNS:
1004 case GEN_URI:
1005 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1006 correctly, CVE-2013-4238 */
1007 t = PyTuple_New(2);
1008 if (t == NULL)
1009 goto fail;
1010 switch (gntype) {
1011 case GEN_EMAIL:
1012 v = PyUnicode_FromString("email");
1013 as = name->d.rfc822Name;
1014 break;
1015 case GEN_DNS:
1016 v = PyUnicode_FromString("DNS");
1017 as = name->d.dNSName;
1018 break;
1019 case GEN_URI:
1020 v = PyUnicode_FromString("URI");
1021 as = name->d.uniformResourceIdentifier;
1022 break;
1023 }
1024 if (v == NULL) {
1025 Py_DECREF(t);
1026 goto fail;
1027 }
1028 PyTuple_SET_ITEM(t, 0, v);
1029 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1030 ASN1_STRING_length(as));
1031 if (v == NULL) {
1032 Py_DECREF(t);
1033 goto fail;
1034 }
1035 PyTuple_SET_ITEM(t, 1, v);
1036 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001037
Christian Heimes1c03abd2016-09-06 23:25:35 +02001038 case GEN_RID:
1039 t = PyTuple_New(2);
1040 if (t == NULL)
1041 goto fail;
1042
1043 v = PyUnicode_FromString("Registered ID");
1044 if (v == NULL) {
1045 Py_DECREF(t);
1046 goto fail;
1047 }
1048 PyTuple_SET_ITEM(t, 0, v);
1049
1050 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1051 if (len < 0) {
1052 Py_DECREF(t);
1053 _setSSLError(NULL, 0, __FILE__, __LINE__);
1054 goto fail;
1055 } else if (len >= (int)sizeof(buf)) {
1056 v = PyUnicode_FromString("<INVALID>");
1057 } else {
1058 v = PyUnicode_FromStringAndSize(buf, len);
1059 }
1060 if (v == NULL) {
1061 Py_DECREF(t);
1062 goto fail;
1063 }
1064 PyTuple_SET_ITEM(t, 1, v);
1065 break;
1066
Christian Heimes824f7f32013-08-17 00:54:47 +02001067 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001069 switch (gntype) {
1070 /* check for new general name type */
1071 case GEN_OTHERNAME:
1072 case GEN_X400:
1073 case GEN_EDIPARTY:
1074 case GEN_IPADD:
1075 case GEN_RID:
1076 break;
1077 default:
1078 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1079 "Unknown general name type %d",
1080 gntype) == -1) {
1081 goto fail;
1082 }
1083 break;
1084 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001085 (void) BIO_reset(biobuf);
1086 GENERAL_NAME_print(biobuf, name);
1087 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1088 if (len < 0) {
1089 _setSSLError(NULL, 0, __FILE__, __LINE__);
1090 goto fail;
1091 }
1092 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001093 if (vptr == NULL) {
1094 PyErr_Format(PyExc_ValueError,
1095 "Invalid value %.200s",
1096 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001097 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001098 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 t = PyTuple_New(2);
1100 if (t == NULL)
1101 goto fail;
1102 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1103 if (v == NULL) {
1104 Py_DECREF(t);
1105 goto fail;
1106 }
1107 PyTuple_SET_ITEM(t, 0, v);
1108 v = PyUnicode_FromStringAndSize((vptr + 1),
1109 (len - (vptr - buf + 1)));
1110 if (v == NULL) {
1111 Py_DECREF(t);
1112 goto fail;
1113 }
1114 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001115 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001116 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001117
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001119
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 if (PyList_Append(peer_alt_names, t) < 0) {
1121 Py_DECREF(t);
1122 goto fail;
1123 }
1124 Py_DECREF(t);
1125 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001126 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 }
1128 BIO_free(biobuf);
1129 if (peer_alt_names != Py_None) {
1130 v = PyList_AsTuple(peer_alt_names);
1131 Py_DECREF(peer_alt_names);
1132 return v;
1133 } else {
1134 return peer_alt_names;
1135 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001136
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001137
1138 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001139 if (biobuf != NULL)
1140 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001141
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001142 if (peer_alt_names != Py_None) {
1143 Py_XDECREF(peer_alt_names);
1144 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001145
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001146 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001147}
1148
1149static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001150_get_aia_uri(X509 *certificate, int nid) {
1151 PyObject *lst = NULL, *ostr = NULL;
1152 int i, result;
1153 AUTHORITY_INFO_ACCESS *info;
1154
1155 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001156 if (info == NULL)
1157 return Py_None;
1158 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1159 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001160 return Py_None;
1161 }
1162
1163 if ((lst = PyList_New(0)) == NULL) {
1164 goto fail;
1165 }
1166
1167 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1168 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1169 ASN1_IA5STRING *uri;
1170
1171 if ((OBJ_obj2nid(ad->method) != nid) ||
1172 (ad->location->type != GEN_URI)) {
1173 continue;
1174 }
1175 uri = ad->location->d.uniformResourceIdentifier;
1176 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1177 uri->length);
1178 if (ostr == NULL) {
1179 goto fail;
1180 }
1181 result = PyList_Append(lst, ostr);
1182 Py_DECREF(ostr);
1183 if (result < 0) {
1184 goto fail;
1185 }
1186 }
1187 AUTHORITY_INFO_ACCESS_free(info);
1188
1189 /* convert to tuple or None */
1190 if (PyList_Size(lst) == 0) {
1191 Py_DECREF(lst);
1192 return Py_None;
1193 } else {
1194 PyObject *tup;
1195 tup = PyList_AsTuple(lst);
1196 Py_DECREF(lst);
1197 return tup;
1198 }
1199
1200 fail:
1201 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001202 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001203 return NULL;
1204}
1205
1206static PyObject *
1207_get_crl_dp(X509 *certificate) {
1208 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001209 int i, j;
1210 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001211
Christian Heimes598894f2016-09-05 23:19:05 +02001212 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001213
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001214 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001215 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001216
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001217 lst = PyList_New(0);
1218 if (lst == NULL)
1219 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001220
1221 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1222 DIST_POINT *dp;
1223 STACK_OF(GENERAL_NAME) *gns;
1224
1225 dp = sk_DIST_POINT_value(dps, i);
1226 gns = dp->distpoint->name.fullname;
1227
1228 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1229 GENERAL_NAME *gn;
1230 ASN1_IA5STRING *uri;
1231 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001232 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001233
1234 gn = sk_GENERAL_NAME_value(gns, j);
1235 if (gn->type != GEN_URI) {
1236 continue;
1237 }
1238 uri = gn->d.uniformResourceIdentifier;
1239 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1240 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001241 if (ouri == NULL)
1242 goto done;
1243
1244 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001245 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001246 if (err < 0)
1247 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001248 }
1249 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001250
1251 /* Convert to tuple. */
1252 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1253
1254 done:
1255 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001256 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001257 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001258}
1259
1260static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001261_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 PyObject *retval = NULL;
1264 BIO *biobuf = NULL;
1265 PyObject *peer;
1266 PyObject *peer_alt_names = NULL;
1267 PyObject *issuer;
1268 PyObject *version;
1269 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001270 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001271 ASN1_INTEGER *serialNumber;
1272 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001273 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001274 ASN1_TIME *notBefore, *notAfter;
1275 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001276
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001277 retval = PyDict_New();
1278 if (retval == NULL)
1279 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001280
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 peer = _create_tuple_for_X509_NAME(
1282 X509_get_subject_name(certificate));
1283 if (peer == NULL)
1284 goto fail0;
1285 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1286 Py_DECREF(peer);
1287 goto fail0;
1288 }
1289 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001290
Antoine Pitroufb046912010-11-09 20:21:19 +00001291 issuer = _create_tuple_for_X509_NAME(
1292 X509_get_issuer_name(certificate));
1293 if (issuer == NULL)
1294 goto fail0;
1295 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001296 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001297 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001298 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001299 Py_DECREF(issuer);
1300
1301 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001302 if (version == NULL)
1303 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001304 if (PyDict_SetItemString(retval, "version", version) < 0) {
1305 Py_DECREF(version);
1306 goto fail0;
1307 }
1308 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001309
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001310 /* get a memory buffer */
1311 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001312
Antoine Pitroufb046912010-11-09 20:21:19 +00001313 (void) BIO_reset(biobuf);
1314 serialNumber = X509_get_serialNumber(certificate);
1315 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1316 i2a_ASN1_INTEGER(biobuf, serialNumber);
1317 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1318 if (len < 0) {
1319 _setSSLError(NULL, 0, __FILE__, __LINE__);
1320 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001321 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001322 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1323 if (sn_obj == NULL)
1324 goto fail1;
1325 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1326 Py_DECREF(sn_obj);
1327 goto fail1;
1328 }
1329 Py_DECREF(sn_obj);
1330
1331 (void) BIO_reset(biobuf);
1332 notBefore = X509_get_notBefore(certificate);
1333 ASN1_TIME_print(biobuf, notBefore);
1334 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1335 if (len < 0) {
1336 _setSSLError(NULL, 0, __FILE__, __LINE__);
1337 goto fail1;
1338 }
1339 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1340 if (pnotBefore == NULL)
1341 goto fail1;
1342 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1343 Py_DECREF(pnotBefore);
1344 goto fail1;
1345 }
1346 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001347
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001348 (void) BIO_reset(biobuf);
1349 notAfter = X509_get_notAfter(certificate);
1350 ASN1_TIME_print(biobuf, notAfter);
1351 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1352 if (len < 0) {
1353 _setSSLError(NULL, 0, __FILE__, __LINE__);
1354 goto fail1;
1355 }
1356 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1357 if (pnotAfter == NULL)
1358 goto fail1;
1359 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1360 Py_DECREF(pnotAfter);
1361 goto fail1;
1362 }
1363 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001364
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001365 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001366
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001367 peer_alt_names = _get_peer_alt_names(certificate);
1368 if (peer_alt_names == NULL)
1369 goto fail1;
1370 else if (peer_alt_names != Py_None) {
1371 if (PyDict_SetItemString(retval, "subjectAltName",
1372 peer_alt_names) < 0) {
1373 Py_DECREF(peer_alt_names);
1374 goto fail1;
1375 }
1376 Py_DECREF(peer_alt_names);
1377 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001378
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001379 /* Authority Information Access: OCSP URIs */
1380 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1381 if (obj == NULL) {
1382 goto fail1;
1383 } else if (obj != Py_None) {
1384 result = PyDict_SetItemString(retval, "OCSP", obj);
1385 Py_DECREF(obj);
1386 if (result < 0) {
1387 goto fail1;
1388 }
1389 }
1390
1391 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1392 if (obj == NULL) {
1393 goto fail1;
1394 } else if (obj != Py_None) {
1395 result = PyDict_SetItemString(retval, "caIssuers", obj);
1396 Py_DECREF(obj);
1397 if (result < 0) {
1398 goto fail1;
1399 }
1400 }
1401
1402 /* CDP (CRL distribution points) */
1403 obj = _get_crl_dp(certificate);
1404 if (obj == NULL) {
1405 goto fail1;
1406 } else if (obj != Py_None) {
1407 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1408 Py_DECREF(obj);
1409 if (result < 0) {
1410 goto fail1;
1411 }
1412 }
1413
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001414 BIO_free(biobuf);
1415 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001416
1417 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001418 if (biobuf != NULL)
1419 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001420 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001421 Py_XDECREF(retval);
1422 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001423}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001424
Christian Heimes9a5395a2013-06-17 15:44:12 +02001425static PyObject *
1426_certificate_to_der(X509 *certificate)
1427{
1428 unsigned char *bytes_buf = NULL;
1429 int len;
1430 PyObject *retval;
1431
1432 bytes_buf = NULL;
1433 len = i2d_X509(certificate, &bytes_buf);
1434 if (len < 0) {
1435 _setSSLError(NULL, 0, __FILE__, __LINE__);
1436 return NULL;
1437 }
1438 /* this is actually an immutable bytes sequence */
1439 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1440 OPENSSL_free(bytes_buf);
1441 return retval;
1442}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001443
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001444/*[clinic input]
1445_ssl._test_decode_cert
1446 path: object(converter="PyUnicode_FSConverter")
1447 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001448
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001449[clinic start generated code]*/
1450
1451static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001452_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1453/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001454{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001455 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001456 X509 *x=NULL;
1457 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001458
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001459 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1460 PyErr_SetString(PySSLErrorObject,
1461 "Can't malloc memory to read file");
1462 goto fail0;
1463 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001464
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001465 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001466 PyErr_SetString(PySSLErrorObject,
1467 "Can't open file");
1468 goto fail0;
1469 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001470
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001471 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1472 if (x == NULL) {
1473 PyErr_SetString(PySSLErrorObject,
1474 "Error decoding PEM-encoded file");
1475 goto fail0;
1476 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001477
Antoine Pitroufb046912010-11-09 20:21:19 +00001478 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001479 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001480
1481 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001482 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001483 if (cert != NULL) BIO_free(cert);
1484 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001485}
1486
1487
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001488/*[clinic input]
1489_ssl._SSLSocket.peer_certificate
1490 der as binary_mode: bool = False
1491 /
1492
1493Returns the certificate for the peer.
1494
1495If no certificate was provided, returns None. If a certificate was
1496provided, but not validated, returns an empty dictionary. Otherwise
1497returns a dict containing information about the peer certificate.
1498
1499If the optional argument is True, returns a DER-encoded copy of the
1500peer certificate, or None if no certificate was provided. This will
1501return the certificate even if it wasn't validated.
1502[clinic start generated code]*/
1503
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001504static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001505_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1506/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001507{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001508 int verification;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001509
Antoine Pitrou20b85552013-09-29 19:50:53 +02001510 if (!self->handshake_done) {
1511 PyErr_SetString(PyExc_ValueError,
1512 "handshake not done yet");
1513 return NULL;
1514 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001515 if (!self->peer_cert)
1516 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001517
Antoine Pitrou721738f2012-08-15 23:20:39 +02001518 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001519 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001520 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001521 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001522 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001523 if ((verification & SSL_VERIFY_PEER) == 0)
1524 return PyDict_New();
1525 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001526 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001527 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001528}
1529
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001530static PyObject *
1531cipher_to_tuple(const SSL_CIPHER *cipher)
1532{
1533 const char *cipher_name, *cipher_protocol;
1534 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001535 if (retval == NULL)
1536 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001537
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001538 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001539 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001540 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001541 PyTuple_SET_ITEM(retval, 0, Py_None);
1542 } else {
1543 v = PyUnicode_FromString(cipher_name);
1544 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001545 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001546 PyTuple_SET_ITEM(retval, 0, v);
1547 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001548
1549 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001550 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001551 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001552 PyTuple_SET_ITEM(retval, 1, Py_None);
1553 } else {
1554 v = PyUnicode_FromString(cipher_protocol);
1555 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001556 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001557 PyTuple_SET_ITEM(retval, 1, v);
1558 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001559
1560 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001561 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001562 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001563 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001564
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001565 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001566
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001567 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568 Py_DECREF(retval);
1569 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001570}
1571
Christian Heimes25bfcd52016-09-06 00:04:45 +02001572#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1573static PyObject *
1574cipher_to_dict(const SSL_CIPHER *cipher)
1575{
1576 const char *cipher_name, *cipher_protocol;
1577
1578 unsigned long cipher_id;
1579 int alg_bits, strength_bits, len;
1580 char buf[512] = {0};
1581#if OPENSSL_VERSION_1_1
1582 int aead, nid;
1583 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1584#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001585
1586 /* can be NULL */
1587 cipher_name = SSL_CIPHER_get_name(cipher);
1588 cipher_protocol = SSL_CIPHER_get_version(cipher);
1589 cipher_id = SSL_CIPHER_get_id(cipher);
1590 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1591 len = strlen(buf);
1592 if (len > 1 && buf[len-1] == '\n')
1593 buf[len-1] = '\0';
1594 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1595
1596#if OPENSSL_VERSION_1_1
1597 aead = SSL_CIPHER_is_aead(cipher);
1598 nid = SSL_CIPHER_get_cipher_nid(cipher);
1599 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1600 nid = SSL_CIPHER_get_digest_nid(cipher);
1601 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1602 nid = SSL_CIPHER_get_kx_nid(cipher);
1603 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1604 nid = SSL_CIPHER_get_auth_nid(cipher);
1605 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1606#endif
1607
Victor Stinner410b9882016-09-12 12:00:23 +02001608 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001609 "{sksssssssisi"
1610#if OPENSSL_VERSION_1_1
1611 "sOssssssss"
1612#endif
1613 "}",
1614 "id", cipher_id,
1615 "name", cipher_name,
1616 "protocol", cipher_protocol,
1617 "description", buf,
1618 "strength_bits", strength_bits,
1619 "alg_bits", alg_bits
1620#if OPENSSL_VERSION_1_1
1621 ,"aead", aead ? Py_True : Py_False,
1622 "symmetric", skcipher,
1623 "digest", digest,
1624 "kea", kx,
1625 "auth", auth
1626#endif
1627 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001628}
1629#endif
1630
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001631/*[clinic input]
1632_ssl._SSLSocket.shared_ciphers
1633[clinic start generated code]*/
1634
1635static PyObject *
1636_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1637/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001638{
1639 STACK_OF(SSL_CIPHER) *ciphers;
1640 int i;
1641 PyObject *res;
1642
Christian Heimes598894f2016-09-05 23:19:05 +02001643 ciphers = SSL_get_ciphers(self->ssl);
1644 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001645 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001646 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1647 if (!res)
1648 return NULL;
1649 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1650 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1651 if (!tup) {
1652 Py_DECREF(res);
1653 return NULL;
1654 }
1655 PyList_SET_ITEM(res, i, tup);
1656 }
1657 return res;
1658}
1659
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001660/*[clinic input]
1661_ssl._SSLSocket.cipher
1662[clinic start generated code]*/
1663
1664static PyObject *
1665_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1666/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001667{
1668 const SSL_CIPHER *current;
1669
1670 if (self->ssl == NULL)
1671 Py_RETURN_NONE;
1672 current = SSL_get_current_cipher(self->ssl);
1673 if (current == NULL)
1674 Py_RETURN_NONE;
1675 return cipher_to_tuple(current);
1676}
1677
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001678/*[clinic input]
1679_ssl._SSLSocket.version
1680[clinic start generated code]*/
1681
1682static PyObject *
1683_ssl__SSLSocket_version_impl(PySSLSocket *self)
1684/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001685{
1686 const char *version;
1687
1688 if (self->ssl == NULL)
1689 Py_RETURN_NONE;
1690 version = SSL_get_version(self->ssl);
1691 if (!strcmp(version, "unknown"))
1692 Py_RETURN_NONE;
1693 return PyUnicode_FromString(version);
1694}
1695
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001696#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001697/*[clinic input]
1698_ssl._SSLSocket.selected_npn_protocol
1699[clinic start generated code]*/
1700
1701static PyObject *
1702_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1703/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1704{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001705 const unsigned char *out;
1706 unsigned int outlen;
1707
Victor Stinner4569cd52013-06-23 14:58:43 +02001708 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001709 &out, &outlen);
1710
1711 if (out == NULL)
1712 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001713 return PyUnicode_FromStringAndSize((char *)out, outlen);
1714}
1715#endif
1716
1717#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001718/*[clinic input]
1719_ssl._SSLSocket.selected_alpn_protocol
1720[clinic start generated code]*/
1721
1722static PyObject *
1723_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1724/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1725{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001726 const unsigned char *out;
1727 unsigned int outlen;
1728
1729 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1730
1731 if (out == NULL)
1732 Py_RETURN_NONE;
1733 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001734}
1735#endif
1736
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001737/*[clinic input]
1738_ssl._SSLSocket.compression
1739[clinic start generated code]*/
1740
1741static PyObject *
1742_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1743/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1744{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001745#ifdef OPENSSL_NO_COMP
1746 Py_RETURN_NONE;
1747#else
1748 const COMP_METHOD *comp_method;
1749 const char *short_name;
1750
1751 if (self->ssl == NULL)
1752 Py_RETURN_NONE;
1753 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001754 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001755 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001756 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001757 if (short_name == NULL)
1758 Py_RETURN_NONE;
1759 return PyUnicode_DecodeFSDefault(short_name);
1760#endif
1761}
1762
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001763static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1764 Py_INCREF(self->ctx);
1765 return self->ctx;
1766}
1767
1768static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1769 void *closure) {
1770
1771 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001772#if !HAVE_SNI
1773 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1774 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001775 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001776#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001777 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001778 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001779 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001780#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001781 } else {
1782 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1783 return -1;
1784 }
1785
1786 return 0;
1787}
1788
1789PyDoc_STRVAR(PySSL_set_context_doc,
1790"_setter_context(ctx)\n\
1791\
1792This changes the context associated with the SSLSocket. This is typically\n\
1793used from within a callback function set by the set_servername_callback\n\
1794on the SSLContext to change the certificate information associated with the\n\
1795SSLSocket before the cryptographic exchange handshake messages\n");
1796
1797
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001798static PyObject *
1799PySSL_get_server_side(PySSLSocket *self, void *c)
1800{
1801 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1802}
1803
1804PyDoc_STRVAR(PySSL_get_server_side_doc,
1805"Whether this is a server-side socket.");
1806
1807static PyObject *
1808PySSL_get_server_hostname(PySSLSocket *self, void *c)
1809{
1810 if (self->server_hostname == NULL)
1811 Py_RETURN_NONE;
1812 Py_INCREF(self->server_hostname);
1813 return self->server_hostname;
1814}
1815
1816PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1817"The currently set server hostname (for SNI).");
1818
1819static PyObject *
1820PySSL_get_owner(PySSLSocket *self, void *c)
1821{
1822 PyObject *owner;
1823
1824 if (self->owner == NULL)
1825 Py_RETURN_NONE;
1826
1827 owner = PyWeakref_GetObject(self->owner);
1828 Py_INCREF(owner);
1829 return owner;
1830}
1831
1832static int
1833PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1834{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001835 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001836 if (self->owner == NULL)
1837 return -1;
1838 return 0;
1839}
1840
1841PyDoc_STRVAR(PySSL_get_owner_doc,
1842"The Python-level owner of this object.\
1843Passed as \"self\" in servername callback.");
1844
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001845
Antoine Pitrou152efa22010-05-16 18:19:27 +00001846static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001847{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001848 if (self->peer_cert) /* Possible not to have one? */
1849 X509_free (self->peer_cert);
1850 if (self->ssl)
1851 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001852 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001853 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001854 Py_XDECREF(self->server_hostname);
1855 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001857}
1858
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001859/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001860 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001861 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001862 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001863
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001864static int
Victor Stinner14690702015-04-06 22:46:13 +02001865PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001866{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001867 int rc;
1868#ifdef HAVE_POLL
1869 struct pollfd pollfd;
1870 _PyTime_t ms;
1871#else
1872 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001873 fd_set fds;
1874 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001875#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001876
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001877 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001878 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001879 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001880 else if (timeout < 0) {
1881 if (s->sock_timeout > 0)
1882 return SOCKET_HAS_TIMED_OUT;
1883 else
1884 return SOCKET_IS_BLOCKING;
1885 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001886
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001887 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001888 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001889 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001890
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001891 /* Prefer poll, if available, since you can poll() any fd
1892 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001893#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001894 pollfd.fd = s->sock_fd;
1895 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001896
Victor Stinner14690702015-04-06 22:46:13 +02001897 /* timeout is in seconds, poll() uses milliseconds */
1898 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001899 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001900
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001901 PySSL_BEGIN_ALLOW_THREADS
1902 rc = poll(&pollfd, 1, (int)ms);
1903 PySSL_END_ALLOW_THREADS
1904#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001905 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001906 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001907 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001908
Victor Stinner14690702015-04-06 22:46:13 +02001909 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001910
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001911 FD_ZERO(&fds);
1912 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001913
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001914 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001915 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001916 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001917 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001918 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001919 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001920 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001921 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001922#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001923
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001924 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1925 (when we are able to write or when there's something to read) */
1926 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001927}
1928
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001929/*[clinic input]
1930_ssl._SSLSocket.write
1931 b: Py_buffer
1932 /
1933
1934Writes the bytes-like object b into the SSL object.
1935
1936Returns the number of bytes written.
1937[clinic start generated code]*/
1938
1939static PyObject *
1940_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1941/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001942{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001943 int len;
1944 int sockstate;
1945 int err;
1946 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001947 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001948 _PyTime_t timeout, deadline = 0;
1949 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001950
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001951 if (sock != NULL) {
1952 if (((PyObject*)sock) == Py_None) {
1953 _setSSLError("Underlying socket connection gone",
1954 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1955 return NULL;
1956 }
1957 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001958 }
1959
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001960 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001961 PyErr_Format(PyExc_OverflowError,
1962 "string longer than %d bytes", INT_MAX);
1963 goto error;
1964 }
1965
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001966 if (sock != NULL) {
1967 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001968 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001969 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1970 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1971 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001972
Victor Stinner14690702015-04-06 22:46:13 +02001973 timeout = GET_SOCKET_TIMEOUT(sock);
1974 has_timeout = (timeout > 0);
1975 if (has_timeout)
1976 deadline = _PyTime_GetMonotonicClock() + timeout;
1977
1978 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001979 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001980 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001981 "The write operation timed out");
1982 goto error;
1983 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1984 PyErr_SetString(PySSLErrorObject,
1985 "Underlying socket has been closed.");
1986 goto error;
1987 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1988 PyErr_SetString(PySSLErrorObject,
1989 "Underlying socket too large for select().");
1990 goto error;
1991 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001992
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001993 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001994 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001995 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001996 err = SSL_get_error(self->ssl, len);
1997 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001998
1999 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002000 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002001
Victor Stinner14690702015-04-06 22:46:13 +02002002 if (has_timeout)
2003 timeout = deadline - _PyTime_GetMonotonicClock();
2004
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002005 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002006 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002007 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002008 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002009 } else {
2010 sockstate = SOCKET_OPERATION_OK;
2011 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002012
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002013 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002014 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002015 "The write operation timed out");
2016 goto error;
2017 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2018 PyErr_SetString(PySSLErrorObject,
2019 "Underlying socket has been closed.");
2020 goto error;
2021 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2022 break;
2023 }
2024 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002025
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002026 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002027 if (len > 0)
2028 return PyLong_FromLong(len);
2029 else
2030 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002031
2032error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002033 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002034 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002035}
2036
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002037/*[clinic input]
2038_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002039
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002040Returns the number of already decrypted bytes available for read, pending on the connection.
2041[clinic start generated code]*/
2042
2043static PyObject *
2044_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2045/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002046{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002047 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002048
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002049 PySSL_BEGIN_ALLOW_THREADS
2050 count = SSL_pending(self->ssl);
2051 PySSL_END_ALLOW_THREADS
2052 if (count < 0)
2053 return PySSL_SetError(self, count, __FILE__, __LINE__);
2054 else
2055 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002056}
2057
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002058/*[clinic input]
2059_ssl._SSLSocket.read
2060 size as len: int
2061 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002062 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002063 ]
2064 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002065
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002066Read up to size bytes from the SSL socket.
2067[clinic start generated code]*/
2068
2069static PyObject *
2070_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2071 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002072/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002073{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002074 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002075 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002076 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002077 int sockstate;
2078 int err;
2079 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002080 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002081 _PyTime_t timeout, deadline = 0;
2082 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002083
Martin Panter5503d472016-03-27 05:35:19 +00002084 if (!group_right_1 && len < 0) {
2085 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2086 return NULL;
2087 }
2088
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002089 if (sock != NULL) {
2090 if (((PyObject*)sock) == Py_None) {
2091 _setSSLError("Underlying socket connection gone",
2092 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2093 return NULL;
2094 }
2095 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002096 }
2097
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002098 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002099 dest = PyBytes_FromStringAndSize(NULL, len);
2100 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002101 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002102 if (len == 0) {
2103 Py_XDECREF(sock);
2104 return dest;
2105 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002106 mem = PyBytes_AS_STRING(dest);
2107 }
2108 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002109 mem = buffer->buf;
2110 if (len <= 0 || len > buffer->len) {
2111 len = (int) buffer->len;
2112 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002113 PyErr_SetString(PyExc_OverflowError,
2114 "maximum length can't fit in a C 'int'");
2115 goto error;
2116 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002117 if (len == 0) {
2118 count = 0;
2119 goto done;
2120 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002121 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002122 }
2123
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002124 if (sock != NULL) {
2125 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002126 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002127 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2128 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2129 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002130
Victor Stinner14690702015-04-06 22:46:13 +02002131 timeout = GET_SOCKET_TIMEOUT(sock);
2132 has_timeout = (timeout > 0);
2133 if (has_timeout)
2134 deadline = _PyTime_GetMonotonicClock() + timeout;
2135
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002136 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002137 PySSL_BEGIN_ALLOW_THREADS
2138 count = SSL_read(self->ssl, mem, len);
2139 err = SSL_get_error(self->ssl, count);
2140 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002141
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002142 if (PyErr_CheckSignals())
2143 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002144
Victor Stinner14690702015-04-06 22:46:13 +02002145 if (has_timeout)
2146 timeout = deadline - _PyTime_GetMonotonicClock();
2147
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002148 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002149 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002150 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002151 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002152 } else if (err == SSL_ERROR_ZERO_RETURN &&
2153 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002154 {
2155 count = 0;
2156 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002157 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002158 else
2159 sockstate = SOCKET_OPERATION_OK;
2160
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002161 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002162 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002163 "The read operation timed out");
2164 goto error;
2165 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2166 break;
2167 }
2168 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002169
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002170 if (count <= 0) {
2171 PySSL_SetError(self, count, __FILE__, __LINE__);
2172 goto error;
2173 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002174
2175done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002176 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002177 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002178 _PyBytes_Resize(&dest, count);
2179 return dest;
2180 }
2181 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002182 return PyLong_FromLong(count);
2183 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002184
2185error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002186 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002187 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002188 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002189 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002190}
2191
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002192/*[clinic input]
2193_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002194
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002195Does the SSL shutdown handshake with the remote end.
2196
2197Returns the underlying socket object.
2198[clinic start generated code]*/
2199
2200static PyObject *
2201_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2202/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002203{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002204 int err, ssl_err, sockstate, nonblocking;
2205 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002206 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002207 _PyTime_t timeout, deadline = 0;
2208 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002209
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002210 if (sock != NULL) {
2211 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002212 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002213 _setSSLError("Underlying socket connection gone",
2214 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2215 return NULL;
2216 }
2217 Py_INCREF(sock);
2218
2219 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002220 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002221 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2222 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002223 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002224
Victor Stinner14690702015-04-06 22:46:13 +02002225 timeout = GET_SOCKET_TIMEOUT(sock);
2226 has_timeout = (timeout > 0);
2227 if (has_timeout)
2228 deadline = _PyTime_GetMonotonicClock() + timeout;
2229
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002230 while (1) {
2231 PySSL_BEGIN_ALLOW_THREADS
2232 /* Disable read-ahead so that unwrap can work correctly.
2233 * Otherwise OpenSSL might read in too much data,
2234 * eating clear text data that happens to be
2235 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002236 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002237 * function is used and the shutdown_seen_zero != 0
2238 * condition is met.
2239 */
2240 if (self->shutdown_seen_zero)
2241 SSL_set_read_ahead(self->ssl, 0);
2242 err = SSL_shutdown(self->ssl);
2243 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002244
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002245 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2246 if (err > 0)
2247 break;
2248 if (err == 0) {
2249 /* Don't loop endlessly; instead preserve legacy
2250 behaviour of trying SSL_shutdown() only twice.
2251 This looks necessary for OpenSSL < 0.9.8m */
2252 if (++zeros > 1)
2253 break;
2254 /* Shutdown was sent, now try receiving */
2255 self->shutdown_seen_zero = 1;
2256 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002257 }
2258
Victor Stinner14690702015-04-06 22:46:13 +02002259 if (has_timeout)
2260 timeout = deadline - _PyTime_GetMonotonicClock();
2261
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002262 /* Possibly retry shutdown until timeout or failure */
2263 ssl_err = SSL_get_error(self->ssl, err);
2264 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002265 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002266 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002267 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002268 else
2269 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002270
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002271 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2272 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002273 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002274 "The read operation timed out");
2275 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002276 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002277 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002278 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002279 }
2280 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2281 PyErr_SetString(PySSLErrorObject,
2282 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002283 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002284 }
2285 else if (sockstate != SOCKET_OPERATION_OK)
2286 /* Retain the SSL error code */
2287 break;
2288 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002289
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002290 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002291 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002292 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002293 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002294 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002295 /* It's already INCREF'ed */
2296 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002297 else
2298 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002299
2300error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002301 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002302 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002303}
2304
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002305/*[clinic input]
2306_ssl._SSLSocket.tls_unique_cb
2307
2308Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2309
2310If the TLS handshake is not yet complete, None is returned.
2311[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002312
Antoine Pitroud6494802011-07-21 01:11:30 +02002313static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002314_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2315/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002316{
2317 PyObject *retval = NULL;
2318 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002319 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002320
2321 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2322 /* if session is resumed XOR we are the client */
2323 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2324 }
2325 else {
2326 /* if a new session XOR we are the server */
2327 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2328 }
2329
2330 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002331 if (len == 0)
2332 Py_RETURN_NONE;
2333
2334 retval = PyBytes_FromStringAndSize(buf, len);
2335
2336 return retval;
2337}
2338
Christian Heimes99a65702016-09-10 23:44:53 +02002339#ifdef OPENSSL_VERSION_1_1
2340
2341static SSL_SESSION*
2342_ssl_session_dup(SSL_SESSION *session) {
2343 SSL_SESSION *newsession = NULL;
2344 int slen;
2345 unsigned char *senc = NULL, *p;
2346 const unsigned char *const_p;
2347
2348 if (session == NULL) {
2349 PyErr_SetString(PyExc_ValueError, "Invalid session");
2350 goto error;
2351 }
2352
2353 /* get length */
2354 slen = i2d_SSL_SESSION(session, NULL);
2355 if (slen == 0 || slen > 0xFF00) {
2356 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2357 goto error;
2358 }
2359 if ((senc = PyMem_Malloc(slen)) == NULL) {
2360 PyErr_NoMemory();
2361 goto error;
2362 }
2363 p = senc;
2364 if (!i2d_SSL_SESSION(session, &p)) {
2365 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2366 goto error;
2367 }
2368 const_p = senc;
2369 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2370 if (session == NULL) {
2371 goto error;
2372 }
2373 PyMem_Free(senc);
2374 return newsession;
2375 error:
2376 if (senc != NULL) {
2377 PyMem_Free(senc);
2378 }
2379 return NULL;
2380}
2381#endif
2382
2383static PyObject *
2384PySSL_get_session(PySSLSocket *self, void *closure) {
2385 /* get_session can return sessions from a server-side connection,
2386 * it does not check for handshake done or client socket. */
2387 PySSLSession *pysess;
2388 SSL_SESSION *session;
2389
2390#ifdef OPENSSL_VERSION_1_1
2391 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2392 * https://github.com/openssl/openssl/issues/1550 */
2393 session = SSL_get0_session(self->ssl); /* borrowed reference */
2394 if (session == NULL) {
2395 Py_RETURN_NONE;
2396 }
2397 if ((session = _ssl_session_dup(session)) == NULL) {
2398 return NULL;
2399 }
2400#else
2401 session = SSL_get1_session(self->ssl);
2402 if (session == NULL) {
2403 Py_RETURN_NONE;
2404 }
2405#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002406 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002407 if (pysess == NULL) {
2408 SSL_SESSION_free(session);
2409 return NULL;
2410 }
2411
2412 assert(self->ctx);
2413 pysess->ctx = self->ctx;
2414 Py_INCREF(pysess->ctx);
2415 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002416 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002417 return (PyObject *)pysess;
2418}
2419
2420static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2421 void *closure)
2422 {
2423 PySSLSession *pysess;
2424#ifdef OPENSSL_VERSION_1_1
2425 SSL_SESSION *session;
2426#endif
2427 int result;
2428
2429 if (!PySSLSession_Check(value)) {
2430 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2431 return -1;
2432 }
2433 pysess = (PySSLSession *)value;
2434
2435 if (self->ctx->ctx != pysess->ctx->ctx) {
2436 PyErr_SetString(PyExc_ValueError,
2437 "Session refers to a different SSLContext.");
2438 return -1;
2439 }
2440 if (self->socket_type != PY_SSL_CLIENT) {
2441 PyErr_SetString(PyExc_ValueError,
2442 "Cannot set session for server-side SSLSocket.");
2443 return -1;
2444 }
2445 if (self->handshake_done) {
2446 PyErr_SetString(PyExc_ValueError,
2447 "Cannot set session after handshake.");
2448 return -1;
2449 }
2450#ifdef OPENSSL_VERSION_1_1
2451 /* duplicate session */
2452 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2453 return -1;
2454 }
2455 result = SSL_set_session(self->ssl, session);
2456 /* free duplicate, SSL_set_session() bumps ref count */
2457 SSL_SESSION_free(session);
2458#else
2459 result = SSL_set_session(self->ssl, pysess->session);
2460#endif
2461 if (result == 0) {
2462 _setSSLError(NULL, 0, __FILE__, __LINE__);
2463 return -1;
2464 }
2465 return 0;
2466}
2467
2468PyDoc_STRVAR(PySSL_set_session_doc,
2469"_setter_session(session)\n\
2470\
2471Get / set SSLSession.");
2472
2473static PyObject *
2474PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2475 if (SSL_session_reused(self->ssl)) {
2476 Py_RETURN_TRUE;
2477 } else {
2478 Py_RETURN_FALSE;
2479 }
2480}
2481
2482PyDoc_STRVAR(PySSL_get_session_reused_doc,
2483"Was the client session reused during handshake?");
2484
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002485static PyGetSetDef ssl_getsetlist[] = {
2486 {"context", (getter) PySSL_get_context,
2487 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002488 {"server_side", (getter) PySSL_get_server_side, NULL,
2489 PySSL_get_server_side_doc},
2490 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2491 PySSL_get_server_hostname_doc},
2492 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2493 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002494 {"session", (getter) PySSL_get_session,
2495 (setter) PySSL_set_session, PySSL_set_session_doc},
2496 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2497 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002498 {NULL}, /* sentinel */
2499};
2500
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002501static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002502 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2503 _SSL__SSLSOCKET_WRITE_METHODDEF
2504 _SSL__SSLSOCKET_READ_METHODDEF
2505 _SSL__SSLSOCKET_PENDING_METHODDEF
2506 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2507 _SSL__SSLSOCKET_CIPHER_METHODDEF
2508 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2509 _SSL__SSLSOCKET_VERSION_METHODDEF
2510 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2511 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2512 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2513 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2514 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002515 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002516};
2517
Antoine Pitrou152efa22010-05-16 18:19:27 +00002518static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002519 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002520 "_ssl._SSLSocket", /*tp_name*/
2521 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002522 0, /*tp_itemsize*/
2523 /* methods */
2524 (destructor)PySSL_dealloc, /*tp_dealloc*/
2525 0, /*tp_print*/
2526 0, /*tp_getattr*/
2527 0, /*tp_setattr*/
2528 0, /*tp_reserved*/
2529 0, /*tp_repr*/
2530 0, /*tp_as_number*/
2531 0, /*tp_as_sequence*/
2532 0, /*tp_as_mapping*/
2533 0, /*tp_hash*/
2534 0, /*tp_call*/
2535 0, /*tp_str*/
2536 0, /*tp_getattro*/
2537 0, /*tp_setattro*/
2538 0, /*tp_as_buffer*/
2539 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2540 0, /*tp_doc*/
2541 0, /*tp_traverse*/
2542 0, /*tp_clear*/
2543 0, /*tp_richcompare*/
2544 0, /*tp_weaklistoffset*/
2545 0, /*tp_iter*/
2546 0, /*tp_iternext*/
2547 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002548 0, /*tp_members*/
2549 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002550};
2551
Antoine Pitrou152efa22010-05-16 18:19:27 +00002552
2553/*
2554 * _SSLContext objects
2555 */
2556
Christian Heimes5fe668c2016-09-12 00:01:11 +02002557static int
2558_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2559{
2560 int mode;
2561 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2562
2563 switch(n) {
2564 case PY_SSL_CERT_NONE:
2565 mode = SSL_VERIFY_NONE;
2566 break;
2567 case PY_SSL_CERT_OPTIONAL:
2568 mode = SSL_VERIFY_PEER;
2569 break;
2570 case PY_SSL_CERT_REQUIRED:
2571 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2572 break;
2573 default:
2574 PyErr_SetString(PyExc_ValueError,
2575 "invalid value for verify_mode");
2576 return -1;
2577 }
2578 /* keep current verify cb */
2579 verify_cb = SSL_CTX_get_verify_callback(ctx);
2580 SSL_CTX_set_verify(ctx, mode, verify_cb);
2581 return 0;
2582}
2583
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002584/*[clinic input]
2585@classmethod
2586_ssl._SSLContext.__new__
2587 protocol as proto_version: int
2588 /
2589[clinic start generated code]*/
2590
Antoine Pitrou152efa22010-05-16 18:19:27 +00002591static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002592_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2593/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002594{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002595 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002596 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002597 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002598 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002599#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002600 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002601#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002602
Antoine Pitrou152efa22010-05-16 18:19:27 +00002603 PySSL_BEGIN_ALLOW_THREADS
2604 if (proto_version == PY_SSL_VERSION_TLS1)
2605 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002606#if HAVE_TLSv1_2
2607 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2608 ctx = SSL_CTX_new(TLSv1_1_method());
2609 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2610 ctx = SSL_CTX_new(TLSv1_2_method());
2611#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002612#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002613 else if (proto_version == PY_SSL_VERSION_SSL3)
2614 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002615#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002616#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002617 else if (proto_version == PY_SSL_VERSION_SSL2)
2618 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002619#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002620 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002621 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002622 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2623 ctx = SSL_CTX_new(TLS_client_method());
2624 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2625 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002626 else
2627 proto_version = -1;
2628 PySSL_END_ALLOW_THREADS
2629
2630 if (proto_version == -1) {
2631 PyErr_SetString(PyExc_ValueError,
2632 "invalid protocol version");
2633 return NULL;
2634 }
2635 if (ctx == NULL) {
2636 PyErr_SetString(PySSLErrorObject,
2637 "failed to allocate SSL context");
2638 return NULL;
2639 }
2640
2641 assert(type != NULL && type->tp_alloc != NULL);
2642 self = (PySSLContext *) type->tp_alloc(type, 0);
2643 if (self == NULL) {
2644 SSL_CTX_free(ctx);
2645 return NULL;
2646 }
2647 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002648#ifdef OPENSSL_NPN_NEGOTIATED
2649 self->npn_protocols = NULL;
2650#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002651#ifdef HAVE_ALPN
2652 self->alpn_protocols = NULL;
2653#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002654#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002655 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002656#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002657 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002658 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2659 self->check_hostname = 1;
2660 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2661 Py_DECREF(self);
2662 return NULL;
2663 }
2664 } else {
2665 self->check_hostname = 0;
2666 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2667 Py_DECREF(self);
2668 return NULL;
2669 }
2670 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002671 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002672 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2673 if (proto_version != PY_SSL_VERSION_SSL2)
2674 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002675 if (proto_version != PY_SSL_VERSION_SSL3)
2676 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002677 /* Minimal security flags for server and client side context.
2678 * Client sockets ignore server-side parameters. */
2679#ifdef SSL_OP_NO_COMPRESSION
2680 options |= SSL_OP_NO_COMPRESSION;
2681#endif
2682#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2683 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2684#endif
2685#ifdef SSL_OP_SINGLE_DH_USE
2686 options |= SSL_OP_SINGLE_DH_USE;
2687#endif
2688#ifdef SSL_OP_SINGLE_ECDH_USE
2689 options |= SSL_OP_SINGLE_ECDH_USE;
2690#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002691 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002692
Christian Heimes358cfd42016-09-10 22:43:48 +02002693 /* A bare minimum cipher list without completly broken cipher suites.
2694 * It's far from perfect but gives users a better head start. */
2695 if (proto_version != PY_SSL_VERSION_SSL2) {
2696 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2697 } else {
2698 /* SSLv2 needs MD5 */
2699 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2700 }
2701 if (result == 0) {
2702 Py_DECREF(self);
2703 ERR_clear_error();
2704 PyErr_SetString(PySSLErrorObject,
2705 "No cipher can be selected.");
2706 return NULL;
2707 }
2708
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002709#if defined(SSL_MODE_RELEASE_BUFFERS)
2710 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2711 usage for no cost at all. However, don't do this for OpenSSL versions
2712 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2713 2014-0198. I can't find exactly which beta fixed this CVE, so be
2714 conservative and assume it wasn't fixed until release. We do this check
2715 at runtime to avoid problems from the dynamic linker.
2716 See #25672 for more on this. */
2717 libver = SSLeay();
2718 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2719 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2720 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2721 }
2722#endif
2723
2724
Donald Stufft8ae264c2017-03-02 11:45:29 -05002725#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002726 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2727 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002728 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2729 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002730#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002731 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2732#else
2733 {
2734 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2735 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2736 EC_KEY_free(key);
2737 }
2738#endif
2739#endif
2740
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002741#define SID_CTX "Python"
2742 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2743 sizeof(SID_CTX));
2744#undef SID_CTX
2745
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002746#ifdef X509_V_FLAG_TRUSTED_FIRST
2747 {
2748 /* Improve trust chain building when cross-signed intermediate
2749 certificates are present. See https://bugs.python.org/issue23476. */
2750 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2751 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2752 }
2753#endif
2754
Antoine Pitrou152efa22010-05-16 18:19:27 +00002755 return (PyObject *)self;
2756}
2757
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002758static int
2759context_traverse(PySSLContext *self, visitproc visit, void *arg)
2760{
2761#ifndef OPENSSL_NO_TLSEXT
2762 Py_VISIT(self->set_hostname);
2763#endif
2764 return 0;
2765}
2766
2767static int
2768context_clear(PySSLContext *self)
2769{
2770#ifndef OPENSSL_NO_TLSEXT
2771 Py_CLEAR(self->set_hostname);
2772#endif
2773 return 0;
2774}
2775
Antoine Pitrou152efa22010-05-16 18:19:27 +00002776static void
2777context_dealloc(PySSLContext *self)
2778{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002779 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002780 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002781#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002782 PyMem_FREE(self->npn_protocols);
2783#endif
2784#ifdef HAVE_ALPN
2785 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002786#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002787 Py_TYPE(self)->tp_free(self);
2788}
2789
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002790/*[clinic input]
2791_ssl._SSLContext.set_ciphers
2792 cipherlist: str
2793 /
2794[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002795
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002796static PyObject *
2797_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2798/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2799{
2800 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002801 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002802 /* Clearing the error queue is necessary on some OpenSSL versions,
2803 otherwise the error will be reported again when another SSL call
2804 is done. */
2805 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002806 PyErr_SetString(PySSLErrorObject,
2807 "No cipher can be selected.");
2808 return NULL;
2809 }
2810 Py_RETURN_NONE;
2811}
2812
Christian Heimes25bfcd52016-09-06 00:04:45 +02002813#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2814/*[clinic input]
2815_ssl._SSLContext.get_ciphers
2816[clinic start generated code]*/
2817
2818static PyObject *
2819_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2820/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2821{
2822 SSL *ssl = NULL;
2823 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002824 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002825 int i=0;
2826 PyObject *result = NULL, *dct;
2827
2828 ssl = SSL_new(self->ctx);
2829 if (ssl == NULL) {
2830 _setSSLError(NULL, 0, __FILE__, __LINE__);
2831 goto exit;
2832 }
2833 sk = SSL_get_ciphers(ssl);
2834
2835 result = PyList_New(sk_SSL_CIPHER_num(sk));
2836 if (result == NULL) {
2837 goto exit;
2838 }
2839
2840 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2841 cipher = sk_SSL_CIPHER_value(sk, i);
2842 dct = cipher_to_dict(cipher);
2843 if (dct == NULL) {
2844 Py_CLEAR(result);
2845 goto exit;
2846 }
2847 PyList_SET_ITEM(result, i, dct);
2848 }
2849
2850 exit:
2851 if (ssl != NULL)
2852 SSL_free(ssl);
2853 return result;
2854
2855}
2856#endif
2857
2858
Benjamin Petersonc54de472015-01-28 12:06:39 -05002859#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002860static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002861do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2862 const unsigned char *server_protocols, unsigned int server_protocols_len,
2863 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002864{
Benjamin Peterson88615022015-01-23 17:30:26 -05002865 int ret;
2866 if (client_protocols == NULL) {
2867 client_protocols = (unsigned char *)"";
2868 client_protocols_len = 0;
2869 }
2870 if (server_protocols == NULL) {
2871 server_protocols = (unsigned char *)"";
2872 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002873 }
2874
Benjamin Peterson88615022015-01-23 17:30:26 -05002875 ret = SSL_select_next_proto(out, outlen,
2876 server_protocols, server_protocols_len,
2877 client_protocols, client_protocols_len);
2878 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2879 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002880
2881 return SSL_TLSEXT_ERR_OK;
2882}
2883
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002884/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2885static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002886_advertiseNPN_cb(SSL *s,
2887 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002888 void *args)
2889{
2890 PySSLContext *ssl_ctx = (PySSLContext *) args;
2891
2892 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002893 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002894 *len = 0;
2895 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002896 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002897 *len = ssl_ctx->npn_protocols_len;
2898 }
2899
2900 return SSL_TLSEXT_ERR_OK;
2901}
2902/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2903static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002904_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002905 unsigned char **out, unsigned char *outlen,
2906 const unsigned char *server, unsigned int server_len,
2907 void *args)
2908{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002909 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002910 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002911 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002912}
2913#endif
2914
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002915/*[clinic input]
2916_ssl._SSLContext._set_npn_protocols
2917 protos: Py_buffer
2918 /
2919[clinic start generated code]*/
2920
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002921static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002922_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2923 Py_buffer *protos)
2924/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002925{
2926#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002927 PyMem_Free(self->npn_protocols);
2928 self->npn_protocols = PyMem_Malloc(protos->len);
2929 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002930 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002931 memcpy(self->npn_protocols, protos->buf, protos->len);
2932 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002933
2934 /* set both server and client callbacks, because the context can
2935 * be used to create both types of sockets */
2936 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2937 _advertiseNPN_cb,
2938 self);
2939 SSL_CTX_set_next_proto_select_cb(self->ctx,
2940 _selectNPN_cb,
2941 self);
2942
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002943 Py_RETURN_NONE;
2944#else
2945 PyErr_SetString(PyExc_NotImplementedError,
2946 "The NPN extension requires OpenSSL 1.0.1 or later.");
2947 return NULL;
2948#endif
2949}
2950
Benjamin Petersoncca27322015-01-23 16:35:37 -05002951#ifdef HAVE_ALPN
2952static int
2953_selectALPN_cb(SSL *s,
2954 const unsigned char **out, unsigned char *outlen,
2955 const unsigned char *client_protocols, unsigned int client_protocols_len,
2956 void *args)
2957{
2958 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002959 return do_protocol_selection(1, (unsigned char **)out, outlen,
2960 ctx->alpn_protocols, ctx->alpn_protocols_len,
2961 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002962}
2963#endif
2964
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002965/*[clinic input]
2966_ssl._SSLContext._set_alpn_protocols
2967 protos: Py_buffer
2968 /
2969[clinic start generated code]*/
2970
Benjamin Petersoncca27322015-01-23 16:35:37 -05002971static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002972_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2973 Py_buffer *protos)
2974/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002975{
2976#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002977 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002978 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002979 if (!self->alpn_protocols)
2980 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002981 memcpy(self->alpn_protocols, protos->buf, protos->len);
2982 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002983
2984 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2985 return PyErr_NoMemory();
2986 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2987
Benjamin Petersoncca27322015-01-23 16:35:37 -05002988 Py_RETURN_NONE;
2989#else
2990 PyErr_SetString(PyExc_NotImplementedError,
2991 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2992 return NULL;
2993#endif
2994}
2995
Antoine Pitrou152efa22010-05-16 18:19:27 +00002996static PyObject *
2997get_verify_mode(PySSLContext *self, void *c)
2998{
2999 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3000 case SSL_VERIFY_NONE:
3001 return PyLong_FromLong(PY_SSL_CERT_NONE);
3002 case SSL_VERIFY_PEER:
3003 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3004 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3005 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3006 }
3007 PyErr_SetString(PySSLErrorObject,
3008 "invalid return value from SSL_CTX_get_verify_mode");
3009 return NULL;
3010}
3011
3012static int
3013set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3014{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003015 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003016 if (!PyArg_Parse(arg, "i", &n))
3017 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003018 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003019 PyErr_SetString(PyExc_ValueError,
3020 "Cannot set verify_mode to CERT_NONE when "
3021 "check_hostname is enabled.");
3022 return -1;
3023 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003024 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003025}
3026
3027static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003028get_verify_flags(PySSLContext *self, void *c)
3029{
3030 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003031 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003032 unsigned long flags;
3033
3034 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003035 param = X509_STORE_get0_param(store);
3036 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003037 return PyLong_FromUnsignedLong(flags);
3038}
3039
3040static int
3041set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3042{
3043 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003044 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003045 unsigned long new_flags, flags, set, clear;
3046
3047 if (!PyArg_Parse(arg, "k", &new_flags))
3048 return -1;
3049 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003050 param = X509_STORE_get0_param(store);
3051 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003052 clear = flags & ~new_flags;
3053 set = ~flags & new_flags;
3054 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003055 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003056 _setSSLError(NULL, 0, __FILE__, __LINE__);
3057 return -1;
3058 }
3059 }
3060 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003061 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003062 _setSSLError(NULL, 0, __FILE__, __LINE__);
3063 return -1;
3064 }
3065 }
3066 return 0;
3067}
3068
3069static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003070get_options(PySSLContext *self, void *c)
3071{
3072 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3073}
3074
3075static int
3076set_options(PySSLContext *self, PyObject *arg, void *c)
3077{
3078 long new_opts, opts, set, clear;
3079 if (!PyArg_Parse(arg, "l", &new_opts))
3080 return -1;
3081 opts = SSL_CTX_get_options(self->ctx);
3082 clear = opts & ~new_opts;
3083 set = ~opts & new_opts;
3084 if (clear) {
3085#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3086 SSL_CTX_clear_options(self->ctx, clear);
3087#else
3088 PyErr_SetString(PyExc_ValueError,
3089 "can't clear options before OpenSSL 0.9.8m");
3090 return -1;
3091#endif
3092 }
3093 if (set)
3094 SSL_CTX_set_options(self->ctx, set);
3095 return 0;
3096}
3097
Christian Heimes1aa9a752013-12-02 02:41:19 +01003098static PyObject *
3099get_check_hostname(PySSLContext *self, void *c)
3100{
3101 return PyBool_FromLong(self->check_hostname);
3102}
3103
3104static int
3105set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3106{
3107 int check_hostname;
3108 if (!PyArg_Parse(arg, "p", &check_hostname))
3109 return -1;
3110 if (check_hostname &&
3111 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3112 PyErr_SetString(PyExc_ValueError,
3113 "check_hostname needs a SSL context with either "
3114 "CERT_OPTIONAL or CERT_REQUIRED");
3115 return -1;
3116 }
3117 self->check_hostname = check_hostname;
3118 return 0;
3119}
3120
3121
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003122typedef struct {
3123 PyThreadState *thread_state;
3124 PyObject *callable;
3125 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003126 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003127 int error;
3128} _PySSLPasswordInfo;
3129
3130static int
3131_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3132 const char *bad_type_error)
3133{
3134 /* Set the password and size fields of a _PySSLPasswordInfo struct
3135 from a unicode, bytes, or byte array object.
3136 The password field will be dynamically allocated and must be freed
3137 by the caller */
3138 PyObject *password_bytes = NULL;
3139 const char *data = NULL;
3140 Py_ssize_t size;
3141
3142 if (PyUnicode_Check(password)) {
3143 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3144 if (!password_bytes) {
3145 goto error;
3146 }
3147 data = PyBytes_AS_STRING(password_bytes);
3148 size = PyBytes_GET_SIZE(password_bytes);
3149 } else if (PyBytes_Check(password)) {
3150 data = PyBytes_AS_STRING(password);
3151 size = PyBytes_GET_SIZE(password);
3152 } else if (PyByteArray_Check(password)) {
3153 data = PyByteArray_AS_STRING(password);
3154 size = PyByteArray_GET_SIZE(password);
3155 } else {
3156 PyErr_SetString(PyExc_TypeError, bad_type_error);
3157 goto error;
3158 }
3159
Victor Stinner9ee02032013-06-23 15:08:23 +02003160 if (size > (Py_ssize_t)INT_MAX) {
3161 PyErr_Format(PyExc_ValueError,
3162 "password cannot be longer than %d bytes", INT_MAX);
3163 goto error;
3164 }
3165
Victor Stinner11ebff22013-07-07 17:07:52 +02003166 PyMem_Free(pw_info->password);
3167 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003168 if (!pw_info->password) {
3169 PyErr_SetString(PyExc_MemoryError,
3170 "unable to allocate password buffer");
3171 goto error;
3172 }
3173 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003174 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003175
3176 Py_XDECREF(password_bytes);
3177 return 1;
3178
3179error:
3180 Py_XDECREF(password_bytes);
3181 return 0;
3182}
3183
3184static int
3185_password_callback(char *buf, int size, int rwflag, void *userdata)
3186{
3187 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3188 PyObject *fn_ret = NULL;
3189
3190 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3191
3192 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003193 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003194 if (!fn_ret) {
3195 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3196 core python API, so we could use it to add a frame here */
3197 goto error;
3198 }
3199
3200 if (!_pwinfo_set(pw_info, fn_ret,
3201 "password callback must return a string")) {
3202 goto error;
3203 }
3204 Py_CLEAR(fn_ret);
3205 }
3206
3207 if (pw_info->size > size) {
3208 PyErr_Format(PyExc_ValueError,
3209 "password cannot be longer than %d bytes", size);
3210 goto error;
3211 }
3212
3213 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3214 memcpy(buf, pw_info->password, pw_info->size);
3215 return pw_info->size;
3216
3217error:
3218 Py_XDECREF(fn_ret);
3219 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3220 pw_info->error = 1;
3221 return -1;
3222}
3223
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003224/*[clinic input]
3225_ssl._SSLContext.load_cert_chain
3226 certfile: object
3227 keyfile: object = NULL
3228 password: object = NULL
3229
3230[clinic start generated code]*/
3231
Antoine Pitroub5218772010-05-21 09:56:06 +00003232static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003233_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3234 PyObject *keyfile, PyObject *password)
3235/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003236{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003237 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003238 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3239 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003240 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003241 int r;
3242
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003243 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003244 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003245 if (keyfile == Py_None)
3246 keyfile = NULL;
3247 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3248 PyErr_SetString(PyExc_TypeError,
3249 "certfile should be a valid filesystem path");
3250 return NULL;
3251 }
3252 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3253 PyErr_SetString(PyExc_TypeError,
3254 "keyfile should be a valid filesystem path");
3255 goto error;
3256 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003257 if (password && password != Py_None) {
3258 if (PyCallable_Check(password)) {
3259 pw_info.callable = password;
3260 } else if (!_pwinfo_set(&pw_info, password,
3261 "password should be a string or callable")) {
3262 goto error;
3263 }
3264 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3265 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3266 }
3267 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003268 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3269 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003270 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003271 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003272 if (pw_info.error) {
3273 ERR_clear_error();
3274 /* the password callback has already set the error information */
3275 }
3276 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003277 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003278 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003279 }
3280 else {
3281 _setSSLError(NULL, 0, __FILE__, __LINE__);
3282 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003283 goto error;
3284 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003285 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003286 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003287 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3288 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003289 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3290 Py_CLEAR(keyfile_bytes);
3291 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003292 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003293 if (pw_info.error) {
3294 ERR_clear_error();
3295 /* the password callback has already set the error information */
3296 }
3297 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003298 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003299 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003300 }
3301 else {
3302 _setSSLError(NULL, 0, __FILE__, __LINE__);
3303 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003304 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003305 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003306 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003307 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003308 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003309 if (r != 1) {
3310 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003311 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003312 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003313 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3314 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003315 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003316 Py_RETURN_NONE;
3317
3318error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003319 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3320 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003321 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003322 Py_XDECREF(keyfile_bytes);
3323 Py_XDECREF(certfile_bytes);
3324 return NULL;
3325}
3326
Christian Heimesefff7062013-11-21 03:35:02 +01003327/* internal helper function, returns -1 on error
3328 */
3329static int
3330_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3331 int filetype)
3332{
3333 BIO *biobuf = NULL;
3334 X509_STORE *store;
3335 int retval = 0, err, loaded = 0;
3336
3337 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3338
3339 if (len <= 0) {
3340 PyErr_SetString(PyExc_ValueError,
3341 "Empty certificate data");
3342 return -1;
3343 } else if (len > INT_MAX) {
3344 PyErr_SetString(PyExc_OverflowError,
3345 "Certificate data is too long.");
3346 return -1;
3347 }
3348
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003349 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003350 if (biobuf == NULL) {
3351 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3352 return -1;
3353 }
3354
3355 store = SSL_CTX_get_cert_store(self->ctx);
3356 assert(store != NULL);
3357
3358 while (1) {
3359 X509 *cert = NULL;
3360 int r;
3361
3362 if (filetype == SSL_FILETYPE_ASN1) {
3363 cert = d2i_X509_bio(biobuf, NULL);
3364 } else {
3365 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003366 SSL_CTX_get_default_passwd_cb(self->ctx),
3367 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3368 );
Christian Heimesefff7062013-11-21 03:35:02 +01003369 }
3370 if (cert == NULL) {
3371 break;
3372 }
3373 r = X509_STORE_add_cert(store, cert);
3374 X509_free(cert);
3375 if (!r) {
3376 err = ERR_peek_last_error();
3377 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3378 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3379 /* cert already in hash table, not an error */
3380 ERR_clear_error();
3381 } else {
3382 break;
3383 }
3384 }
3385 loaded++;
3386 }
3387
3388 err = ERR_peek_last_error();
3389 if ((filetype == SSL_FILETYPE_ASN1) &&
3390 (loaded > 0) &&
3391 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3392 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3393 /* EOF ASN1 file, not an error */
3394 ERR_clear_error();
3395 retval = 0;
3396 } else if ((filetype == SSL_FILETYPE_PEM) &&
3397 (loaded > 0) &&
3398 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3399 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3400 /* EOF PEM file, not an error */
3401 ERR_clear_error();
3402 retval = 0;
3403 } else {
3404 _setSSLError(NULL, 0, __FILE__, __LINE__);
3405 retval = -1;
3406 }
3407
3408 BIO_free(biobuf);
3409 return retval;
3410}
3411
3412
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003413/*[clinic input]
3414_ssl._SSLContext.load_verify_locations
3415 cafile: object = NULL
3416 capath: object = NULL
3417 cadata: object = NULL
3418
3419[clinic start generated code]*/
3420
Antoine Pitrou152efa22010-05-16 18:19:27 +00003421static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003422_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3423 PyObject *cafile,
3424 PyObject *capath,
3425 PyObject *cadata)
3426/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003427{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003428 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3429 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003430 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003431
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003432 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003433 if (cafile == Py_None)
3434 cafile = NULL;
3435 if (capath == Py_None)
3436 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003437 if (cadata == Py_None)
3438 cadata = NULL;
3439
3440 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003441 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003442 "cafile, capath and cadata cannot be all omitted");
3443 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003444 }
3445 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3446 PyErr_SetString(PyExc_TypeError,
3447 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003448 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003449 }
3450 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003451 PyErr_SetString(PyExc_TypeError,
3452 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003453 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003454 }
Christian Heimesefff7062013-11-21 03:35:02 +01003455
3456 /* validata cadata type and load cadata */
3457 if (cadata) {
3458 Py_buffer buf;
3459 PyObject *cadata_ascii = NULL;
3460
3461 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3462 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3463 PyBuffer_Release(&buf);
3464 PyErr_SetString(PyExc_TypeError,
3465 "cadata should be a contiguous buffer with "
3466 "a single dimension");
3467 goto error;
3468 }
3469 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3470 PyBuffer_Release(&buf);
3471 if (r == -1) {
3472 goto error;
3473 }
3474 } else {
3475 PyErr_Clear();
3476 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3477 if (cadata_ascii == NULL) {
3478 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003479 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003480 "bytes-like object");
3481 goto error;
3482 }
3483 r = _add_ca_certs(self,
3484 PyBytes_AS_STRING(cadata_ascii),
3485 PyBytes_GET_SIZE(cadata_ascii),
3486 SSL_FILETYPE_PEM);
3487 Py_DECREF(cadata_ascii);
3488 if (r == -1) {
3489 goto error;
3490 }
3491 }
3492 }
3493
3494 /* load cafile or capath */
3495 if (cafile || capath) {
3496 if (cafile)
3497 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3498 if (capath)
3499 capath_buf = PyBytes_AS_STRING(capath_bytes);
3500 PySSL_BEGIN_ALLOW_THREADS
3501 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3502 PySSL_END_ALLOW_THREADS
3503 if (r != 1) {
3504 ok = 0;
3505 if (errno != 0) {
3506 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003507 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003508 }
3509 else {
3510 _setSSLError(NULL, 0, __FILE__, __LINE__);
3511 }
3512 goto error;
3513 }
3514 }
3515 goto end;
3516
3517 error:
3518 ok = 0;
3519 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003520 Py_XDECREF(cafile_bytes);
3521 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003522 if (ok) {
3523 Py_RETURN_NONE;
3524 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003525 return NULL;
3526 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003527}
3528
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003529/*[clinic input]
3530_ssl._SSLContext.load_dh_params
3531 path as filepath: object
3532 /
3533
3534[clinic start generated code]*/
3535
Antoine Pitrou152efa22010-05-16 18:19:27 +00003536static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003537_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3538/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003539{
3540 FILE *f;
3541 DH *dh;
3542
Victor Stinnerdaf45552013-08-28 00:53:59 +02003543 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003544 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003545 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003546
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003547 errno = 0;
3548 PySSL_BEGIN_ALLOW_THREADS
3549 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003550 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003551 PySSL_END_ALLOW_THREADS
3552 if (dh == NULL) {
3553 if (errno != 0) {
3554 ERR_clear_error();
3555 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3556 }
3557 else {
3558 _setSSLError(NULL, 0, __FILE__, __LINE__);
3559 }
3560 return NULL;
3561 }
3562 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3563 _setSSLError(NULL, 0, __FILE__, __LINE__);
3564 DH_free(dh);
3565 Py_RETURN_NONE;
3566}
3567
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003568/*[clinic input]
3569_ssl._SSLContext._wrap_socket
3570 sock: object(subclass_of="PySocketModule.Sock_Type")
3571 server_side: int
3572 server_hostname as hostname_obj: object = None
3573
3574[clinic start generated code]*/
3575
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003576static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003577_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3578 int server_side, PyObject *hostname_obj)
3579/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003580{
Antoine Pitroud5323212010-10-22 18:19:07 +00003581 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003582 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003583
Antoine Pitroud5323212010-10-22 18:19:07 +00003584 /* server_hostname is either None (or absent), or to be encoded
3585 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003586 if (hostname_obj != Py_None) {
3587 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003588 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003589 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003590
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003591 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3592 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003593 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003594 if (hostname != NULL)
3595 PyMem_Free(hostname);
3596 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003597}
3598
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003599/*[clinic input]
3600_ssl._SSLContext._wrap_bio
3601 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3602 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3603 server_side: int
3604 server_hostname as hostname_obj: object = None
3605
3606[clinic start generated code]*/
3607
Antoine Pitroub0182c82010-10-12 20:09:02 +00003608static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003609_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3610 PySSLMemoryBIO *outgoing, int server_side,
3611 PyObject *hostname_obj)
3612/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003613{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003614 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003615 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003616
3617 /* server_hostname is either None (or absent), or to be encoded
3618 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003619 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003620 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3621 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003622 }
3623
3624 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3625 incoming, outgoing);
3626
3627 PyMem_Free(hostname);
3628 return res;
3629}
3630
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003631/*[clinic input]
3632_ssl._SSLContext.session_stats
3633[clinic start generated code]*/
3634
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003635static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003636_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3637/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003638{
3639 int r;
3640 PyObject *value, *stats = PyDict_New();
3641 if (!stats)
3642 return NULL;
3643
3644#define ADD_STATS(SSL_NAME, KEY_NAME) \
3645 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3646 if (value == NULL) \
3647 goto error; \
3648 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3649 Py_DECREF(value); \
3650 if (r < 0) \
3651 goto error;
3652
3653 ADD_STATS(number, "number");
3654 ADD_STATS(connect, "connect");
3655 ADD_STATS(connect_good, "connect_good");
3656 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3657 ADD_STATS(accept, "accept");
3658 ADD_STATS(accept_good, "accept_good");
3659 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3660 ADD_STATS(accept, "accept");
3661 ADD_STATS(hits, "hits");
3662 ADD_STATS(misses, "misses");
3663 ADD_STATS(timeouts, "timeouts");
3664 ADD_STATS(cache_full, "cache_full");
3665
3666#undef ADD_STATS
3667
3668 return stats;
3669
3670error:
3671 Py_DECREF(stats);
3672 return NULL;
3673}
3674
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003675/*[clinic input]
3676_ssl._SSLContext.set_default_verify_paths
3677[clinic start generated code]*/
3678
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003679static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003680_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3681/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003682{
3683 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3684 _setSSLError(NULL, 0, __FILE__, __LINE__);
3685 return NULL;
3686 }
3687 Py_RETURN_NONE;
3688}
3689
Antoine Pitrou501da612011-12-21 09:27:41 +01003690#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003691/*[clinic input]
3692_ssl._SSLContext.set_ecdh_curve
3693 name: object
3694 /
3695
3696[clinic start generated code]*/
3697
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003698static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003699_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3700/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003701{
3702 PyObject *name_bytes;
3703 int nid;
3704 EC_KEY *key;
3705
3706 if (!PyUnicode_FSConverter(name, &name_bytes))
3707 return NULL;
3708 assert(PyBytes_Check(name_bytes));
3709 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3710 Py_DECREF(name_bytes);
3711 if (nid == 0) {
3712 PyErr_Format(PyExc_ValueError,
3713 "unknown elliptic curve name %R", name);
3714 return NULL;
3715 }
3716 key = EC_KEY_new_by_curve_name(nid);
3717 if (key == NULL) {
3718 _setSSLError(NULL, 0, __FILE__, __LINE__);
3719 return NULL;
3720 }
3721 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3722 EC_KEY_free(key);
3723 Py_RETURN_NONE;
3724}
Antoine Pitrou501da612011-12-21 09:27:41 +01003725#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003726
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003727#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003728static int
3729_servername_callback(SSL *s, int *al, void *args)
3730{
3731 int ret;
3732 PySSLContext *ssl_ctx = (PySSLContext *) args;
3733 PySSLSocket *ssl;
3734 PyObject *servername_o;
3735 PyObject *servername_idna;
3736 PyObject *result;
3737 /* The high-level ssl.SSLSocket object */
3738 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003739 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003740#ifdef WITH_THREAD
3741 PyGILState_STATE gstate = PyGILState_Ensure();
3742#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003743
3744 if (ssl_ctx->set_hostname == NULL) {
3745 /* remove race condition in this the call back while if removing the
3746 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003747#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003748 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003749#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003750 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003751 }
3752
3753 ssl = SSL_get_app_data(s);
3754 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003755
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003756 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003757 * SSL connection and that has a .context attribute that can be changed to
3758 * identify the requested hostname. Since the official API is the Python
3759 * level API we want to pass the callback a Python level object rather than
3760 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3761 * SSLObject) that will be passed. Otherwise if there's a socket then that
3762 * will be passed. If both do not exist only then the C-level object is
3763 * passed. */
3764 if (ssl->owner)
3765 ssl_socket = PyWeakref_GetObject(ssl->owner);
3766 else if (ssl->Socket)
3767 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3768 else
3769 ssl_socket = (PyObject *) ssl;
3770
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003771 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003772 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003773 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003774
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003775 if (servername == NULL) {
3776 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3777 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003778 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003779 else {
3780 servername_o = PyBytes_FromString(servername);
3781 if (servername_o == NULL) {
3782 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3783 goto error;
3784 }
3785 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3786 if (servername_idna == NULL) {
3787 PyErr_WriteUnraisable(servername_o);
3788 Py_DECREF(servername_o);
3789 goto error;
3790 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003791 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003792 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3793 servername_idna, ssl_ctx, NULL);
3794 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003795 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003796 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003797
3798 if (result == NULL) {
3799 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3800 *al = SSL_AD_HANDSHAKE_FAILURE;
3801 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3802 }
3803 else {
3804 if (result != Py_None) {
3805 *al = (int) PyLong_AsLong(result);
3806 if (PyErr_Occurred()) {
3807 PyErr_WriteUnraisable(result);
3808 *al = SSL_AD_INTERNAL_ERROR;
3809 }
3810 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3811 }
3812 else {
3813 ret = SSL_TLSEXT_ERR_OK;
3814 }
3815 Py_DECREF(result);
3816 }
3817
Stefan Krah20d60802013-01-17 17:07:17 +01003818#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003819 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003820#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003821 return ret;
3822
3823error:
3824 Py_DECREF(ssl_socket);
3825 *al = SSL_AD_INTERNAL_ERROR;
3826 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003827#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003828 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003829#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003830 return ret;
3831}
Antoine Pitroua5963382013-03-30 16:39:00 +01003832#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003833
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003834/*[clinic input]
3835_ssl._SSLContext.set_servername_callback
3836 method as cb: object
3837 /
3838
3839Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3840
3841If the argument is None then the callback is disabled. The method is called
3842with the SSLSocket, the server name as a string, and the SSLContext object.
3843See RFC 6066 for details of the SNI extension.
3844[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003845
3846static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003847_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3848/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003849{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003850#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003851 Py_CLEAR(self->set_hostname);
3852 if (cb == Py_None) {
3853 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3854 }
3855 else {
3856 if (!PyCallable_Check(cb)) {
3857 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3858 PyErr_SetString(PyExc_TypeError,
3859 "not a callable object");
3860 return NULL;
3861 }
3862 Py_INCREF(cb);
3863 self->set_hostname = cb;
3864 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3865 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3866 }
3867 Py_RETURN_NONE;
3868#else
3869 PyErr_SetString(PyExc_NotImplementedError,
3870 "The TLS extension servername callback, "
3871 "SSL_CTX_set_tlsext_servername_callback, "
3872 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003873 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003874#endif
3875}
3876
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003877/*[clinic input]
3878_ssl._SSLContext.cert_store_stats
3879
3880Returns quantities of loaded X.509 certificates.
3881
3882X.509 certificates with a CA extension and certificate revocation lists
3883inside the context's cert store.
3884
3885NOTE: Certificates in a capath directory aren't loaded unless they have
3886been used at least once.
3887[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003888
3889static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003890_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3891/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003892{
3893 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003894 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003895 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003896 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003897
3898 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003899 objs = X509_STORE_get0_objects(store);
3900 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3901 obj = sk_X509_OBJECT_value(objs, i);
3902 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003903 case X509_LU_X509:
3904 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003905 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003906 ca++;
3907 }
3908 break;
3909 case X509_LU_CRL:
3910 crl++;
3911 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003912 default:
3913 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3914 * As far as I can tell they are internal states and never
3915 * stored in a cert store */
3916 break;
3917 }
3918 }
3919 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3920 "x509_ca", ca);
3921}
3922
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003923/*[clinic input]
3924_ssl._SSLContext.get_ca_certs
3925 binary_form: bool = False
3926
3927Returns a list of dicts with information of loaded CA certs.
3928
3929If the optional argument is True, returns a DER-encoded copy of the CA
3930certificate.
3931
3932NOTE: Certificates in a capath directory aren't loaded unless they have
3933been used at least once.
3934[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003935
3936static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003937_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3938/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003939{
3940 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003941 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003942 PyObject *ci = NULL, *rlist = NULL;
3943 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003944
3945 if ((rlist = PyList_New(0)) == NULL) {
3946 return NULL;
3947 }
3948
3949 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003950 objs = X509_STORE_get0_objects(store);
3951 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003952 X509_OBJECT *obj;
3953 X509 *cert;
3954
Christian Heimes598894f2016-09-05 23:19:05 +02003955 obj = sk_X509_OBJECT_value(objs, i);
3956 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003957 /* not a x509 cert */
3958 continue;
3959 }
3960 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003961 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003962 if (!X509_check_ca(cert)) {
3963 continue;
3964 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003965 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003966 ci = _certificate_to_der(cert);
3967 } else {
3968 ci = _decode_certificate(cert);
3969 }
3970 if (ci == NULL) {
3971 goto error;
3972 }
3973 if (PyList_Append(rlist, ci) == -1) {
3974 goto error;
3975 }
3976 Py_CLEAR(ci);
3977 }
3978 return rlist;
3979
3980 error:
3981 Py_XDECREF(ci);
3982 Py_XDECREF(rlist);
3983 return NULL;
3984}
3985
3986
Antoine Pitrou152efa22010-05-16 18:19:27 +00003987static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003988 {"check_hostname", (getter) get_check_hostname,
3989 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003990 {"options", (getter) get_options,
3991 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003992 {"verify_flags", (getter) get_verify_flags,
3993 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003994 {"verify_mode", (getter) get_verify_mode,
3995 (setter) set_verify_mode, NULL},
3996 {NULL}, /* sentinel */
3997};
3998
3999static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004000 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4001 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4002 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4003 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4004 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4005 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4006 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4007 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4008 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4009 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4010 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4011 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4012 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4013 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004014 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004015 {NULL, NULL} /* sentinel */
4016};
4017
4018static PyTypeObject PySSLContext_Type = {
4019 PyVarObject_HEAD_INIT(NULL, 0)
4020 "_ssl._SSLContext", /*tp_name*/
4021 sizeof(PySSLContext), /*tp_basicsize*/
4022 0, /*tp_itemsize*/
4023 (destructor)context_dealloc, /*tp_dealloc*/
4024 0, /*tp_print*/
4025 0, /*tp_getattr*/
4026 0, /*tp_setattr*/
4027 0, /*tp_reserved*/
4028 0, /*tp_repr*/
4029 0, /*tp_as_number*/
4030 0, /*tp_as_sequence*/
4031 0, /*tp_as_mapping*/
4032 0, /*tp_hash*/
4033 0, /*tp_call*/
4034 0, /*tp_str*/
4035 0, /*tp_getattro*/
4036 0, /*tp_setattro*/
4037 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004038 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004039 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004040 (traverseproc) context_traverse, /*tp_traverse*/
4041 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004042 0, /*tp_richcompare*/
4043 0, /*tp_weaklistoffset*/
4044 0, /*tp_iter*/
4045 0, /*tp_iternext*/
4046 context_methods, /*tp_methods*/
4047 0, /*tp_members*/
4048 context_getsetlist, /*tp_getset*/
4049 0, /*tp_base*/
4050 0, /*tp_dict*/
4051 0, /*tp_descr_get*/
4052 0, /*tp_descr_set*/
4053 0, /*tp_dictoffset*/
4054 0, /*tp_init*/
4055 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004056 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004057};
4058
4059
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004060/*
4061 * MemoryBIO objects
4062 */
4063
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004064/*[clinic input]
4065@classmethod
4066_ssl.MemoryBIO.__new__
4067
4068[clinic start generated code]*/
4069
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004070static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004071_ssl_MemoryBIO_impl(PyTypeObject *type)
4072/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004073{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004074 BIO *bio;
4075 PySSLMemoryBIO *self;
4076
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004077 bio = BIO_new(BIO_s_mem());
4078 if (bio == NULL) {
4079 PyErr_SetString(PySSLErrorObject,
4080 "failed to allocate BIO");
4081 return NULL;
4082 }
4083 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4084 * just that no data is currently available. The SSL routines should retry
4085 * the read, which we can achieve by calling BIO_set_retry_read(). */
4086 BIO_set_retry_read(bio);
4087 BIO_set_mem_eof_return(bio, -1);
4088
4089 assert(type != NULL && type->tp_alloc != NULL);
4090 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4091 if (self == NULL) {
4092 BIO_free(bio);
4093 return NULL;
4094 }
4095 self->bio = bio;
4096 self->eof_written = 0;
4097
4098 return (PyObject *) self;
4099}
4100
4101static void
4102memory_bio_dealloc(PySSLMemoryBIO *self)
4103{
4104 BIO_free(self->bio);
4105 Py_TYPE(self)->tp_free(self);
4106}
4107
4108static PyObject *
4109memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4110{
4111 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
4112}
4113
4114PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4115"The number of bytes pending in the memory BIO.");
4116
4117static PyObject *
4118memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4119{
4120 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4121 && self->eof_written);
4122}
4123
4124PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4125"Whether the memory BIO is at EOF.");
4126
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004127/*[clinic input]
4128_ssl.MemoryBIO.read
4129 size as len: int = -1
4130 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004131
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004132Read up to size bytes from the memory BIO.
4133
4134If size is not specified, read the entire buffer.
4135If the return value is an empty bytes instance, this means either
4136EOF or that no data is available. Use the "eof" property to
4137distinguish between the two.
4138[clinic start generated code]*/
4139
4140static PyObject *
4141_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4142/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4143{
4144 int avail, nbytes;
4145 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004146
4147 avail = BIO_ctrl_pending(self->bio);
4148 if ((len < 0) || (len > avail))
4149 len = avail;
4150
4151 result = PyBytes_FromStringAndSize(NULL, len);
4152 if ((result == NULL) || (len == 0))
4153 return result;
4154
4155 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4156 /* There should never be any short reads but check anyway. */
4157 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4158 Py_DECREF(result);
4159 return NULL;
4160 }
4161
4162 return result;
4163}
4164
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004165/*[clinic input]
4166_ssl.MemoryBIO.write
4167 b: Py_buffer
4168 /
4169
4170Writes the bytes b into the memory BIO.
4171
4172Returns the number of bytes written.
4173[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004174
4175static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004176_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4177/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004178{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004179 int nbytes;
4180
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004181 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004182 PyErr_Format(PyExc_OverflowError,
4183 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004184 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004185 }
4186
4187 if (self->eof_written) {
4188 PyErr_SetString(PySSLErrorObject,
4189 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004190 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004191 }
4192
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004193 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004194 if (nbytes < 0) {
4195 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004196 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004197 }
4198
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004199 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004200}
4201
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004202/*[clinic input]
4203_ssl.MemoryBIO.write_eof
4204
4205Write an EOF marker to the memory BIO.
4206
4207When all data has been read, the "eof" property will be True.
4208[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004209
4210static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004211_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4212/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004213{
4214 self->eof_written = 1;
4215 /* After an EOF is written, a zero return from read() should be a real EOF
4216 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4217 BIO_clear_retry_flags(self->bio);
4218 BIO_set_mem_eof_return(self->bio, 0);
4219
4220 Py_RETURN_NONE;
4221}
4222
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004223static PyGetSetDef memory_bio_getsetlist[] = {
4224 {"pending", (getter) memory_bio_get_pending, NULL,
4225 PySSL_memory_bio_pending_doc},
4226 {"eof", (getter) memory_bio_get_eof, NULL,
4227 PySSL_memory_bio_eof_doc},
4228 {NULL}, /* sentinel */
4229};
4230
4231static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004232 _SSL_MEMORYBIO_READ_METHODDEF
4233 _SSL_MEMORYBIO_WRITE_METHODDEF
4234 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004235 {NULL, NULL} /* sentinel */
4236};
4237
4238static PyTypeObject PySSLMemoryBIO_Type = {
4239 PyVarObject_HEAD_INIT(NULL, 0)
4240 "_ssl.MemoryBIO", /*tp_name*/
4241 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4242 0, /*tp_itemsize*/
4243 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4244 0, /*tp_print*/
4245 0, /*tp_getattr*/
4246 0, /*tp_setattr*/
4247 0, /*tp_reserved*/
4248 0, /*tp_repr*/
4249 0, /*tp_as_number*/
4250 0, /*tp_as_sequence*/
4251 0, /*tp_as_mapping*/
4252 0, /*tp_hash*/
4253 0, /*tp_call*/
4254 0, /*tp_str*/
4255 0, /*tp_getattro*/
4256 0, /*tp_setattro*/
4257 0, /*tp_as_buffer*/
4258 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4259 0, /*tp_doc*/
4260 0, /*tp_traverse*/
4261 0, /*tp_clear*/
4262 0, /*tp_richcompare*/
4263 0, /*tp_weaklistoffset*/
4264 0, /*tp_iter*/
4265 0, /*tp_iternext*/
4266 memory_bio_methods, /*tp_methods*/
4267 0, /*tp_members*/
4268 memory_bio_getsetlist, /*tp_getset*/
4269 0, /*tp_base*/
4270 0, /*tp_dict*/
4271 0, /*tp_descr_get*/
4272 0, /*tp_descr_set*/
4273 0, /*tp_dictoffset*/
4274 0, /*tp_init*/
4275 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004276 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004277};
4278
Antoine Pitrou152efa22010-05-16 18:19:27 +00004279
Christian Heimes99a65702016-09-10 23:44:53 +02004280/*
4281 * SSL Session object
4282 */
4283
4284static void
4285PySSLSession_dealloc(PySSLSession *self)
4286{
Christian Heimesa5d07652016-09-24 10:48:05 +02004287 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004288 Py_XDECREF(self->ctx);
4289 if (self->session != NULL) {
4290 SSL_SESSION_free(self->session);
4291 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004292 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004293}
4294
4295static PyObject *
4296PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4297{
4298 int result;
4299
4300 if (left == NULL || right == NULL) {
4301 PyErr_BadInternalCall();
4302 return NULL;
4303 }
4304
4305 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4306 Py_RETURN_NOTIMPLEMENTED;
4307 }
4308
4309 if (left == right) {
4310 result = 0;
4311 } else {
4312 const unsigned char *left_id, *right_id;
4313 unsigned int left_len, right_len;
4314 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4315 &left_len);
4316 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4317 &right_len);
4318 if (left_len == right_len) {
4319 result = memcmp(left_id, right_id, left_len);
4320 } else {
4321 result = 1;
4322 }
4323 }
4324
4325 switch (op) {
4326 case Py_EQ:
4327 if (result == 0) {
4328 Py_RETURN_TRUE;
4329 } else {
4330 Py_RETURN_FALSE;
4331 }
4332 break;
4333 case Py_NE:
4334 if (result != 0) {
4335 Py_RETURN_TRUE;
4336 } else {
4337 Py_RETURN_FALSE;
4338 }
4339 break;
4340 case Py_LT:
4341 case Py_LE:
4342 case Py_GT:
4343 case Py_GE:
4344 Py_RETURN_NOTIMPLEMENTED;
4345 break;
4346 default:
4347 PyErr_BadArgument();
4348 return NULL;
4349 }
4350}
4351
4352static int
4353PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4354{
4355 Py_VISIT(self->ctx);
4356 return 0;
4357}
4358
4359static int
4360PySSLSession_clear(PySSLSession *self)
4361{
4362 Py_CLEAR(self->ctx);
4363 return 0;
4364}
4365
4366
4367static PyObject *
4368PySSLSession_get_time(PySSLSession *self, void *closure) {
4369 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4370}
4371
4372PyDoc_STRVAR(PySSLSession_get_time_doc,
4373"Session creation time (seconds since epoch).");
4374
4375
4376static PyObject *
4377PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4378 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4379}
4380
4381PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4382"Session timeout (delta in seconds).");
4383
4384
4385static PyObject *
4386PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4387 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4388 return PyLong_FromUnsignedLong(hint);
4389}
4390
4391PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4392"Ticket life time hint.");
4393
4394
4395static PyObject *
4396PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4397 const unsigned char *id;
4398 unsigned int len;
4399 id = SSL_SESSION_get_id(self->session, &len);
4400 return PyBytes_FromStringAndSize((const char *)id, len);
4401}
4402
4403PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4404"Session id");
4405
4406
4407static PyObject *
4408PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4409 if (SSL_SESSION_has_ticket(self->session)) {
4410 Py_RETURN_TRUE;
4411 } else {
4412 Py_RETURN_FALSE;
4413 }
4414}
4415
4416PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4417"Does the session contain a ticket?");
4418
4419
4420static PyGetSetDef PySSLSession_getsetlist[] = {
4421 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4422 PySSLSession_get_has_ticket_doc},
4423 {"id", (getter) PySSLSession_get_session_id, NULL,
4424 PySSLSession_get_session_id_doc},
4425 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4426 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4427 {"time", (getter) PySSLSession_get_time, NULL,
4428 PySSLSession_get_time_doc},
4429 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4430 PySSLSession_get_timeout_doc},
4431 {NULL}, /* sentinel */
4432};
4433
4434static PyTypeObject PySSLSession_Type = {
4435 PyVarObject_HEAD_INIT(NULL, 0)
4436 "_ssl.Session", /*tp_name*/
4437 sizeof(PySSLSession), /*tp_basicsize*/
4438 0, /*tp_itemsize*/
4439 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4440 0, /*tp_print*/
4441 0, /*tp_getattr*/
4442 0, /*tp_setattr*/
4443 0, /*tp_reserved*/
4444 0, /*tp_repr*/
4445 0, /*tp_as_number*/
4446 0, /*tp_as_sequence*/
4447 0, /*tp_as_mapping*/
4448 0, /*tp_hash*/
4449 0, /*tp_call*/
4450 0, /*tp_str*/
4451 0, /*tp_getattro*/
4452 0, /*tp_setattro*/
4453 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004454 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004455 0, /*tp_doc*/
4456 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4457 (inquiry)PySSLSession_clear, /*tp_clear*/
4458 PySSLSession_richcompare, /*tp_richcompare*/
4459 0, /*tp_weaklistoffset*/
4460 0, /*tp_iter*/
4461 0, /*tp_iternext*/
4462 0, /*tp_methods*/
4463 0, /*tp_members*/
4464 PySSLSession_getsetlist, /*tp_getset*/
4465};
4466
4467
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004468/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004469/*[clinic input]
4470_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004471 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004472 entropy: double
4473 /
4474
4475Mix string into the OpenSSL PRNG state.
4476
4477entropy (a float) is a lower bound on the entropy contained in
4478string. See RFC 1750.
4479[clinic start generated code]*/
4480
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004481static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004482_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
4483/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004484{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004485 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004486 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004487
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004488 buf = (const char *)view->buf;
4489 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004490 do {
4491 written = Py_MIN(len, INT_MAX);
4492 RAND_add(buf, (int)written, entropy);
4493 buf += written;
4494 len -= written;
4495 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004496 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004497}
4498
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004499static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004500PySSL_RAND(int len, int pseudo)
4501{
4502 int ok;
4503 PyObject *bytes;
4504 unsigned long err;
4505 const char *errstr;
4506 PyObject *v;
4507
Victor Stinner1e81a392013-12-19 16:47:04 +01004508 if (len < 0) {
4509 PyErr_SetString(PyExc_ValueError, "num must be positive");
4510 return NULL;
4511 }
4512
Victor Stinner99c8b162011-05-24 12:05:19 +02004513 bytes = PyBytes_FromStringAndSize(NULL, len);
4514 if (bytes == NULL)
4515 return NULL;
4516 if (pseudo) {
4517 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4518 if (ok == 0 || ok == 1)
4519 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4520 }
4521 else {
4522 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4523 if (ok == 1)
4524 return bytes;
4525 }
4526 Py_DECREF(bytes);
4527
4528 err = ERR_get_error();
4529 errstr = ERR_reason_error_string(err);
4530 v = Py_BuildValue("(ks)", err, errstr);
4531 if (v != NULL) {
4532 PyErr_SetObject(PySSLErrorObject, v);
4533 Py_DECREF(v);
4534 }
4535 return NULL;
4536}
4537
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004538/*[clinic input]
4539_ssl.RAND_bytes
4540 n: int
4541 /
4542
4543Generate n cryptographically strong pseudo-random bytes.
4544[clinic start generated code]*/
4545
Victor Stinner99c8b162011-05-24 12:05:19 +02004546static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004547_ssl_RAND_bytes_impl(PyObject *module, int n)
4548/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004549{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004550 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004551}
4552
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004553/*[clinic input]
4554_ssl.RAND_pseudo_bytes
4555 n: int
4556 /
4557
4558Generate n pseudo-random bytes.
4559
4560Return a pair (bytes, is_cryptographic). is_cryptographic is True
4561if the bytes generated are cryptographically strong.
4562[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004563
4564static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004565_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4566/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004567{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004568 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004569}
4570
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004571/*[clinic input]
4572_ssl.RAND_status
4573
4574Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4575
4576It is necessary to seed the PRNG with RAND_add() on some platforms before
4577using the ssl() function.
4578[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004579
4580static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004581_ssl_RAND_status_impl(PyObject *module)
4582/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004583{
Christian Heimes217cfd12007-12-02 14:31:20 +00004584 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004585}
4586
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004587#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004588/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004589/*[clinic input]
4590_ssl.RAND_egd
4591 path: object(converter="PyUnicode_FSConverter")
4592 /
4593
4594Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4595
4596Returns number of bytes read. Raises SSLError if connection to EGD
4597fails or if it does not provide enough data to seed PRNG.
4598[clinic start generated code]*/
4599
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004600static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004601_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4602/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004603{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004604 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004605 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004606 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004607 PyErr_SetString(PySSLErrorObject,
4608 "EGD connection failed or EGD did not return "
4609 "enough data to seed the PRNG");
4610 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004611 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004612 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004613}
Christian Heimesa5d07652016-09-24 10:48:05 +02004614/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004615#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004616
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004617
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004618
4619/*[clinic input]
4620_ssl.get_default_verify_paths
4621
4622Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4623
4624The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4625[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004626
4627static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004628_ssl_get_default_verify_paths_impl(PyObject *module)
4629/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004630{
4631 PyObject *ofile_env = NULL;
4632 PyObject *ofile = NULL;
4633 PyObject *odir_env = NULL;
4634 PyObject *odir = NULL;
4635
Benjamin Petersond113c962015-07-18 10:59:13 -07004636#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004637 const char *tmp = (info); \
4638 target = NULL; \
4639 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4640 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4641 target = PyBytes_FromString(tmp); } \
4642 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004643 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004644
Benjamin Petersond113c962015-07-18 10:59:13 -07004645 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4646 CONVERT(X509_get_default_cert_file(), ofile);
4647 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4648 CONVERT(X509_get_default_cert_dir(), odir);
4649#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004650
Christian Heimes200bb1b2013-06-14 15:14:29 +02004651 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004652
4653 error:
4654 Py_XDECREF(ofile_env);
4655 Py_XDECREF(ofile);
4656 Py_XDECREF(odir_env);
4657 Py_XDECREF(odir);
4658 return NULL;
4659}
4660
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004661static PyObject*
4662asn1obj2py(ASN1_OBJECT *obj)
4663{
4664 int nid;
4665 const char *ln, *sn;
4666 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004667 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004668
4669 nid = OBJ_obj2nid(obj);
4670 if (nid == NID_undef) {
4671 PyErr_Format(PyExc_ValueError, "Unknown object");
4672 return NULL;
4673 }
4674 sn = OBJ_nid2sn(nid);
4675 ln = OBJ_nid2ln(nid);
4676 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4677 if (buflen < 0) {
4678 _setSSLError(NULL, 0, __FILE__, __LINE__);
4679 return NULL;
4680 }
4681 if (buflen) {
4682 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4683 } else {
4684 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4685 }
4686}
4687
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004688/*[clinic input]
4689_ssl.txt2obj
4690 txt: str
4691 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004692
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004693Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4694
4695By default objects are looked up by OID. With name=True short and
4696long name are also matched.
4697[clinic start generated code]*/
4698
4699static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004700_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4701/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004702{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004703 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004704 ASN1_OBJECT *obj;
4705
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004706 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4707 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004708 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004709 return NULL;
4710 }
4711 result = asn1obj2py(obj);
4712 ASN1_OBJECT_free(obj);
4713 return result;
4714}
4715
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004716/*[clinic input]
4717_ssl.nid2obj
4718 nid: int
4719 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004720
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004721Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4722[clinic start generated code]*/
4723
4724static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004725_ssl_nid2obj_impl(PyObject *module, int nid)
4726/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004727{
4728 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004729 ASN1_OBJECT *obj;
4730
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004731 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004732 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004733 return NULL;
4734 }
4735 obj = OBJ_nid2obj(nid);
4736 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004737 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004738 return NULL;
4739 }
4740 result = asn1obj2py(obj);
4741 ASN1_OBJECT_free(obj);
4742 return result;
4743}
4744
Christian Heimes46bebee2013-06-09 19:03:31 +02004745#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004746
4747static PyObject*
4748certEncodingType(DWORD encodingType)
4749{
4750 static PyObject *x509_asn = NULL;
4751 static PyObject *pkcs_7_asn = NULL;
4752
4753 if (x509_asn == NULL) {
4754 x509_asn = PyUnicode_InternFromString("x509_asn");
4755 if (x509_asn == NULL)
4756 return NULL;
4757 }
4758 if (pkcs_7_asn == NULL) {
4759 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4760 if (pkcs_7_asn == NULL)
4761 return NULL;
4762 }
4763 switch(encodingType) {
4764 case X509_ASN_ENCODING:
4765 Py_INCREF(x509_asn);
4766 return x509_asn;
4767 case PKCS_7_ASN_ENCODING:
4768 Py_INCREF(pkcs_7_asn);
4769 return pkcs_7_asn;
4770 default:
4771 return PyLong_FromLong(encodingType);
4772 }
4773}
4774
4775static PyObject*
4776parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4777{
4778 CERT_ENHKEY_USAGE *usage;
4779 DWORD size, error, i;
4780 PyObject *retval;
4781
4782 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4783 error = GetLastError();
4784 if (error == CRYPT_E_NOT_FOUND) {
4785 Py_RETURN_TRUE;
4786 }
4787 return PyErr_SetFromWindowsErr(error);
4788 }
4789
4790 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4791 if (usage == NULL) {
4792 return PyErr_NoMemory();
4793 }
4794
4795 /* Now get the actual enhanced usage property */
4796 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4797 PyMem_Free(usage);
4798 error = GetLastError();
4799 if (error == CRYPT_E_NOT_FOUND) {
4800 Py_RETURN_TRUE;
4801 }
4802 return PyErr_SetFromWindowsErr(error);
4803 }
4804 retval = PySet_New(NULL);
4805 if (retval == NULL) {
4806 goto error;
4807 }
4808 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4809 if (usage->rgpszUsageIdentifier[i]) {
4810 PyObject *oid;
4811 int err;
4812 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4813 if (oid == NULL) {
4814 Py_CLEAR(retval);
4815 goto error;
4816 }
4817 err = PySet_Add(retval, oid);
4818 Py_DECREF(oid);
4819 if (err == -1) {
4820 Py_CLEAR(retval);
4821 goto error;
4822 }
4823 }
4824 }
4825 error:
4826 PyMem_Free(usage);
4827 return retval;
4828}
4829
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004830/*[clinic input]
4831_ssl.enum_certificates
4832 store_name: str
4833
4834Retrieve certificates from Windows' cert store.
4835
4836store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4837more cert storages, too. The function returns a list of (bytes,
4838encoding_type, trust) tuples. The encoding_type flag can be interpreted
4839with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4840a set of OIDs or the boolean True.
4841[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004842
Christian Heimes46bebee2013-06-09 19:03:31 +02004843static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004844_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4845/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004846{
Christian Heimes46bebee2013-06-09 19:03:31 +02004847 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004848 PCCERT_CONTEXT pCertCtx = NULL;
4849 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004850 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004851
Christian Heimes44109d72013-11-22 01:51:30 +01004852 result = PyList_New(0);
4853 if (result == NULL) {
4854 return NULL;
4855 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004856 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4857 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4858 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004859 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004860 Py_DECREF(result);
4861 return PyErr_SetFromWindowsErr(GetLastError());
4862 }
4863
Christian Heimes44109d72013-11-22 01:51:30 +01004864 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4865 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4866 pCertCtx->cbCertEncoded);
4867 if (!cert) {
4868 Py_CLEAR(result);
4869 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004870 }
Christian Heimes44109d72013-11-22 01:51:30 +01004871 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4872 Py_CLEAR(result);
4873 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004874 }
Christian Heimes44109d72013-11-22 01:51:30 +01004875 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4876 if (keyusage == Py_True) {
4877 Py_DECREF(keyusage);
4878 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004879 }
Christian Heimes44109d72013-11-22 01:51:30 +01004880 if (keyusage == NULL) {
4881 Py_CLEAR(result);
4882 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004883 }
Christian Heimes44109d72013-11-22 01:51:30 +01004884 if ((tup = PyTuple_New(3)) == NULL) {
4885 Py_CLEAR(result);
4886 break;
4887 }
4888 PyTuple_SET_ITEM(tup, 0, cert);
4889 cert = NULL;
4890 PyTuple_SET_ITEM(tup, 1, enc);
4891 enc = NULL;
4892 PyTuple_SET_ITEM(tup, 2, keyusage);
4893 keyusage = NULL;
4894 if (PyList_Append(result, tup) < 0) {
4895 Py_CLEAR(result);
4896 break;
4897 }
4898 Py_CLEAR(tup);
4899 }
4900 if (pCertCtx) {
4901 /* loop ended with an error, need to clean up context manually */
4902 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004903 }
4904
4905 /* In error cases cert, enc and tup may not be NULL */
4906 Py_XDECREF(cert);
4907 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004908 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004909 Py_XDECREF(tup);
4910
4911 if (!CertCloseStore(hStore, 0)) {
4912 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004913 Py_XDECREF(result);
4914 return PyErr_SetFromWindowsErr(GetLastError());
4915 }
4916 return result;
4917}
4918
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004919/*[clinic input]
4920_ssl.enum_crls
4921 store_name: str
4922
4923Retrieve CRLs from Windows' cert store.
4924
4925store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4926more cert storages, too. The function returns a list of (bytes,
4927encoding_type) tuples. The encoding_type flag can be interpreted with
4928X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4929[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004930
4931static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004932_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4933/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004934{
Christian Heimes44109d72013-11-22 01:51:30 +01004935 HCERTSTORE hStore = NULL;
4936 PCCRL_CONTEXT pCrlCtx = NULL;
4937 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4938 PyObject *result = NULL;
4939
Christian Heimes44109d72013-11-22 01:51:30 +01004940 result = PyList_New(0);
4941 if (result == NULL) {
4942 return NULL;
4943 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004944 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4945 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4946 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004947 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004948 Py_DECREF(result);
4949 return PyErr_SetFromWindowsErr(GetLastError());
4950 }
Christian Heimes44109d72013-11-22 01:51:30 +01004951
4952 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4953 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4954 pCrlCtx->cbCrlEncoded);
4955 if (!crl) {
4956 Py_CLEAR(result);
4957 break;
4958 }
4959 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4960 Py_CLEAR(result);
4961 break;
4962 }
4963 if ((tup = PyTuple_New(2)) == NULL) {
4964 Py_CLEAR(result);
4965 break;
4966 }
4967 PyTuple_SET_ITEM(tup, 0, crl);
4968 crl = NULL;
4969 PyTuple_SET_ITEM(tup, 1, enc);
4970 enc = NULL;
4971
4972 if (PyList_Append(result, tup) < 0) {
4973 Py_CLEAR(result);
4974 break;
4975 }
4976 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004977 }
Christian Heimes44109d72013-11-22 01:51:30 +01004978 if (pCrlCtx) {
4979 /* loop ended with an error, need to clean up context manually */
4980 CertFreeCRLContext(pCrlCtx);
4981 }
4982
4983 /* In error cases cert, enc and tup may not be NULL */
4984 Py_XDECREF(crl);
4985 Py_XDECREF(enc);
4986 Py_XDECREF(tup);
4987
4988 if (!CertCloseStore(hStore, 0)) {
4989 /* This error case might shadow another exception.*/
4990 Py_XDECREF(result);
4991 return PyErr_SetFromWindowsErr(GetLastError());
4992 }
4993 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004994}
Christian Heimes44109d72013-11-22 01:51:30 +01004995
4996#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004997
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004998/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004999static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005000 _SSL__TEST_DECODE_CERT_METHODDEF
5001 _SSL_RAND_ADD_METHODDEF
5002 _SSL_RAND_BYTES_METHODDEF
5003 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5004 _SSL_RAND_EGD_METHODDEF
5005 _SSL_RAND_STATUS_METHODDEF
5006 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5007 _SSL_ENUM_CERTIFICATES_METHODDEF
5008 _SSL_ENUM_CRLS_METHODDEF
5009 _SSL_TXT2OBJ_METHODDEF
5010 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005011 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005012};
5013
5014
Christian Heimes598894f2016-09-05 23:19:05 +02005015#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005016
5017/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005018 * of the Python C thread library
5019 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5020 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005021
5022static PyThread_type_lock *_ssl_locks = NULL;
5023
Christian Heimes4d98ca92013-08-19 17:36:29 +02005024#if OPENSSL_VERSION_NUMBER >= 0x10000000
5025/* use new CRYPTO_THREADID API. */
5026static void
5027_ssl_threadid_callback(CRYPTO_THREADID *id)
5028{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005029 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005030}
5031#else
5032/* deprecated CRYPTO_set_id_callback() API. */
5033static unsigned long
5034_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005035 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005036}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005037#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005038
Bill Janssen6e027db2007-11-15 22:23:56 +00005039static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005040 (int mode, int n, const char *file, int line) {
5041 /* this function is needed to perform locking on shared data
5042 structures. (Note that OpenSSL uses a number of global data
5043 structures that will be implicitly shared whenever multiple
5044 threads use OpenSSL.) Multi-threaded applications will
5045 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005046
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005047 locking_function() must be able to handle up to
5048 CRYPTO_num_locks() different mutex locks. It sets the n-th
5049 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005050
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005051 file and line are the file number of the function setting the
5052 lock. They can be useful for debugging.
5053 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005054
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005055 if ((_ssl_locks == NULL) ||
5056 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5057 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005058
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005059 if (mode & CRYPTO_LOCK) {
5060 PyThread_acquire_lock(_ssl_locks[n], 1);
5061 } else {
5062 PyThread_release_lock(_ssl_locks[n]);
5063 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005064}
5065
5066static int _setup_ssl_threads(void) {
5067
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005068 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005069
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005070 if (_ssl_locks == NULL) {
5071 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005072 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5073 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005074 if (_ssl_locks == NULL) {
5075 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005076 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005077 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005078 for (i = 0; i < _ssl_locks_count; i++) {
5079 _ssl_locks[i] = PyThread_allocate_lock();
5080 if (_ssl_locks[i] == NULL) {
5081 unsigned int j;
5082 for (j = 0; j < i; j++) {
5083 PyThread_free_lock(_ssl_locks[j]);
5084 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005085 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005086 return 0;
5087 }
5088 }
5089 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005090#if OPENSSL_VERSION_NUMBER >= 0x10000000
5091 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5092#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005093 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005094#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005095 }
5096 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005097}
5098
Christian Heimes598894f2016-09-05 23:19:05 +02005099#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005100
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005101PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005102"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005103for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005104
Martin v. Löwis1a214512008-06-11 05:26:20 +00005105
5106static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005107 PyModuleDef_HEAD_INIT,
5108 "_ssl",
5109 module_doc,
5110 -1,
5111 PySSL_methods,
5112 NULL,
5113 NULL,
5114 NULL,
5115 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005116};
5117
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005118
5119static void
5120parse_openssl_version(unsigned long libver,
5121 unsigned int *major, unsigned int *minor,
5122 unsigned int *fix, unsigned int *patch,
5123 unsigned int *status)
5124{
5125 *status = libver & 0xF;
5126 libver >>= 4;
5127 *patch = libver & 0xFF;
5128 libver >>= 8;
5129 *fix = libver & 0xFF;
5130 libver >>= 8;
5131 *minor = libver & 0xFF;
5132 libver >>= 8;
5133 *major = libver & 0xFF;
5134}
5135
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005136PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005137PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005138{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005139 PyObject *m, *d, *r;
5140 unsigned long libver;
5141 unsigned int major, minor, fix, patch, status;
5142 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005143 struct py_ssl_error_code *errcode;
5144 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005145
Antoine Pitrou152efa22010-05-16 18:19:27 +00005146 if (PyType_Ready(&PySSLContext_Type) < 0)
5147 return NULL;
5148 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005149 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005150 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5151 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005152 if (PyType_Ready(&PySSLSession_Type) < 0)
5153 return NULL;
5154
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005155
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005156 m = PyModule_Create(&_sslmodule);
5157 if (m == NULL)
5158 return NULL;
5159 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005160
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005161 /* Load _socket module and its C API */
5162 socket_api = PySocketModule_ImportModuleAndAPI();
5163 if (!socket_api)
5164 return NULL;
5165 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005166
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005167 /* Init OpenSSL */
5168 SSL_load_error_strings();
5169 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005170#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02005171#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005172 /* note that this will start threading if not already started */
5173 if (!_setup_ssl_threads()) {
5174 return NULL;
5175 }
Christian Heimes598894f2016-09-05 23:19:05 +02005176#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5177 /* OpenSSL 1.1.0 builtin thread support is enabled */
5178 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005179#endif
Christian Heimes598894f2016-09-05 23:19:05 +02005180#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005181 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005182
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005183 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005184 sslerror_type_slots[0].pfunc = PyExc_OSError;
5185 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005186 if (PySSLErrorObject == NULL)
5187 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005188
Antoine Pitrou41032a62011-10-27 23:56:55 +02005189 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5190 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5191 PySSLErrorObject, NULL);
5192 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5193 "ssl.SSLWantReadError", SSLWantReadError_doc,
5194 PySSLErrorObject, NULL);
5195 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5196 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5197 PySSLErrorObject, NULL);
5198 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5199 "ssl.SSLSyscallError", SSLSyscallError_doc,
5200 PySSLErrorObject, NULL);
5201 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5202 "ssl.SSLEOFError", SSLEOFError_doc,
5203 PySSLErrorObject, NULL);
5204 if (PySSLZeroReturnErrorObject == NULL
5205 || PySSLWantReadErrorObject == NULL
5206 || PySSLWantWriteErrorObject == NULL
5207 || PySSLSyscallErrorObject == NULL
5208 || PySSLEOFErrorObject == NULL)
5209 return NULL;
5210 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5211 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5212 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5213 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5214 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5215 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005216 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005217 if (PyDict_SetItemString(d, "_SSLContext",
5218 (PyObject *)&PySSLContext_Type) != 0)
5219 return NULL;
5220 if (PyDict_SetItemString(d, "_SSLSocket",
5221 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005222 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005223 if (PyDict_SetItemString(d, "MemoryBIO",
5224 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5225 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005226 if (PyDict_SetItemString(d, "SSLSession",
5227 (PyObject *)&PySSLSession_Type) != 0)
5228 return NULL;
5229
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005230 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5231 PY_SSL_ERROR_ZERO_RETURN);
5232 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5233 PY_SSL_ERROR_WANT_READ);
5234 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5235 PY_SSL_ERROR_WANT_WRITE);
5236 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5237 PY_SSL_ERROR_WANT_X509_LOOKUP);
5238 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5239 PY_SSL_ERROR_SYSCALL);
5240 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5241 PY_SSL_ERROR_SSL);
5242 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5243 PY_SSL_ERROR_WANT_CONNECT);
5244 /* non ssl.h errorcodes */
5245 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5246 PY_SSL_ERROR_EOF);
5247 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5248 PY_SSL_ERROR_INVALID_ERROR_CODE);
5249 /* cert requirements */
5250 PyModule_AddIntConstant(m, "CERT_NONE",
5251 PY_SSL_CERT_NONE);
5252 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5253 PY_SSL_CERT_OPTIONAL);
5254 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5255 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005256 /* CRL verification for verification_flags */
5257 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5258 0);
5259 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5260 X509_V_FLAG_CRL_CHECK);
5261 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5262 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5263 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5264 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005265#ifdef X509_V_FLAG_TRUSTED_FIRST
5266 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5267 X509_V_FLAG_TRUSTED_FIRST);
5268#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005269
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005270 /* Alert Descriptions from ssl.h */
5271 /* note RESERVED constants no longer intended for use have been removed */
5272 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5273
5274#define ADD_AD_CONSTANT(s) \
5275 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5276 SSL_AD_##s)
5277
5278 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5279 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5280 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5281 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5282 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5283 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5284 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5285 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5286 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5287 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5288 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5289 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5290 ADD_AD_CONSTANT(UNKNOWN_CA);
5291 ADD_AD_CONSTANT(ACCESS_DENIED);
5292 ADD_AD_CONSTANT(DECODE_ERROR);
5293 ADD_AD_CONSTANT(DECRYPT_ERROR);
5294 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5295 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5296 ADD_AD_CONSTANT(INTERNAL_ERROR);
5297 ADD_AD_CONSTANT(USER_CANCELLED);
5298 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005299 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005300#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5301 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5302#endif
5303#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5304 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5305#endif
5306#ifdef SSL_AD_UNRECOGNIZED_NAME
5307 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5308#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005309#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5310 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5311#endif
5312#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5313 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5314#endif
5315#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5316 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5317#endif
5318
5319#undef ADD_AD_CONSTANT
5320
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005321 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005322#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005323 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5324 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005325#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005326#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005327 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5328 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005329#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005330 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005331 PY_SSL_VERSION_TLS);
5332 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5333 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005334 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5335 PY_SSL_VERSION_TLS_CLIENT);
5336 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5337 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005338 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5339 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005340#if HAVE_TLSv1_2
5341 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5342 PY_SSL_VERSION_TLS1_1);
5343 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5344 PY_SSL_VERSION_TLS1_2);
5345#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005346
Antoine Pitroub5218772010-05-21 09:56:06 +00005347 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005348 PyModule_AddIntConstant(m, "OP_ALL",
5349 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005350 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5351 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5352 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005353#if HAVE_TLSv1_2
5354 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5355 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5356#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005357 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5358 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005359 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005360 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005361#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005362 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005363#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005364#ifdef SSL_OP_NO_COMPRESSION
5365 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5366 SSL_OP_NO_COMPRESSION);
5367#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005368
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005369#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005370 r = Py_True;
5371#else
5372 r = Py_False;
5373#endif
5374 Py_INCREF(r);
5375 PyModule_AddObject(m, "HAS_SNI", r);
5376
Antoine Pitroud6494802011-07-21 01:11:30 +02005377 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005378 Py_INCREF(r);
5379 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5380
Antoine Pitrou501da612011-12-21 09:27:41 +01005381#ifdef OPENSSL_NO_ECDH
5382 r = Py_False;
5383#else
5384 r = Py_True;
5385#endif
5386 Py_INCREF(r);
5387 PyModule_AddObject(m, "HAS_ECDH", r);
5388
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005389#ifdef OPENSSL_NPN_NEGOTIATED
5390 r = Py_True;
5391#else
5392 r = Py_False;
5393#endif
5394 Py_INCREF(r);
5395 PyModule_AddObject(m, "HAS_NPN", r);
5396
Benjamin Petersoncca27322015-01-23 16:35:37 -05005397#ifdef HAVE_ALPN
5398 r = Py_True;
5399#else
5400 r = Py_False;
5401#endif
5402 Py_INCREF(r);
5403 PyModule_AddObject(m, "HAS_ALPN", r);
5404
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005405 /* Mappings for error codes */
5406 err_codes_to_names = PyDict_New();
5407 err_names_to_codes = PyDict_New();
5408 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5409 return NULL;
5410 errcode = error_codes;
5411 while (errcode->mnemonic != NULL) {
5412 PyObject *mnemo, *key;
5413 mnemo = PyUnicode_FromString(errcode->mnemonic);
5414 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5415 if (mnemo == NULL || key == NULL)
5416 return NULL;
5417 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5418 return NULL;
5419 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5420 return NULL;
5421 Py_DECREF(key);
5422 Py_DECREF(mnemo);
5423 errcode++;
5424 }
5425 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5426 return NULL;
5427 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5428 return NULL;
5429
5430 lib_codes_to_names = PyDict_New();
5431 if (lib_codes_to_names == NULL)
5432 return NULL;
5433 libcode = library_codes;
5434 while (libcode->library != NULL) {
5435 PyObject *mnemo, *key;
5436 key = PyLong_FromLong(libcode->code);
5437 mnemo = PyUnicode_FromString(libcode->library);
5438 if (key == NULL || mnemo == NULL)
5439 return NULL;
5440 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5441 return NULL;
5442 Py_DECREF(key);
5443 Py_DECREF(mnemo);
5444 libcode++;
5445 }
5446 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5447 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005448
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005449 /* OpenSSL version */
5450 /* SSLeay() gives us the version of the library linked against,
5451 which could be different from the headers version.
5452 */
5453 libver = SSLeay();
5454 r = PyLong_FromUnsignedLong(libver);
5455 if (r == NULL)
5456 return NULL;
5457 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5458 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005459 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005460 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5461 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5462 return NULL;
5463 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5464 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5465 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005466
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005467 libver = OPENSSL_VERSION_NUMBER;
5468 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5469 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5470 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5471 return NULL;
5472
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005473 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005474}