blob: 327fb37ebad526abb19af762acfbf41f0a8f7455 [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#if OPENSSL_VERSION_NUMBER >= 0x10001000L
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001213 /* Calls x509v3_cache_extensions and sets up crldp */
1214 X509_check_ca(certificate);
Christian Heimes949ec142013-11-21 16:26:51 +01001215#endif
Christian Heimes598894f2016-09-05 23:19:05 +02001216 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001217
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001218 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001219 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001220
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001221 lst = PyList_New(0);
1222 if (lst == NULL)
1223 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001224
1225 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1226 DIST_POINT *dp;
1227 STACK_OF(GENERAL_NAME) *gns;
1228
1229 dp = sk_DIST_POINT_value(dps, i);
1230 gns = dp->distpoint->name.fullname;
1231
1232 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1233 GENERAL_NAME *gn;
1234 ASN1_IA5STRING *uri;
1235 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001236 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001237
1238 gn = sk_GENERAL_NAME_value(gns, j);
1239 if (gn->type != GEN_URI) {
1240 continue;
1241 }
1242 uri = gn->d.uniformResourceIdentifier;
1243 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1244 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001245 if (ouri == NULL)
1246 goto done;
1247
1248 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001249 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001250 if (err < 0)
1251 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001252 }
1253 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001254
1255 /* Convert to tuple. */
1256 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1257
1258 done:
1259 Py_XDECREF(lst);
1260#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Peterson806fb252015-11-14 00:09:22 -08001261 sk_DIST_POINT_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001262#endif
1263 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001264}
1265
1266static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001267_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001268
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001269 PyObject *retval = NULL;
1270 BIO *biobuf = NULL;
1271 PyObject *peer;
1272 PyObject *peer_alt_names = NULL;
1273 PyObject *issuer;
1274 PyObject *version;
1275 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001276 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001277 ASN1_INTEGER *serialNumber;
1278 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001279 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 ASN1_TIME *notBefore, *notAfter;
1281 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001282
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001283 retval = PyDict_New();
1284 if (retval == NULL)
1285 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001286
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 peer = _create_tuple_for_X509_NAME(
1288 X509_get_subject_name(certificate));
1289 if (peer == NULL)
1290 goto fail0;
1291 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1292 Py_DECREF(peer);
1293 goto fail0;
1294 }
1295 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001296
Antoine Pitroufb046912010-11-09 20:21:19 +00001297 issuer = _create_tuple_for_X509_NAME(
1298 X509_get_issuer_name(certificate));
1299 if (issuer == NULL)
1300 goto fail0;
1301 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001302 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001303 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001304 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001305 Py_DECREF(issuer);
1306
1307 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001308 if (version == NULL)
1309 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001310 if (PyDict_SetItemString(retval, "version", version) < 0) {
1311 Py_DECREF(version);
1312 goto fail0;
1313 }
1314 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001315
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001316 /* get a memory buffer */
1317 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001318
Antoine Pitroufb046912010-11-09 20:21:19 +00001319 (void) BIO_reset(biobuf);
1320 serialNumber = X509_get_serialNumber(certificate);
1321 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1322 i2a_ASN1_INTEGER(biobuf, serialNumber);
1323 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1324 if (len < 0) {
1325 _setSSLError(NULL, 0, __FILE__, __LINE__);
1326 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001327 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001328 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1329 if (sn_obj == NULL)
1330 goto fail1;
1331 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1332 Py_DECREF(sn_obj);
1333 goto fail1;
1334 }
1335 Py_DECREF(sn_obj);
1336
1337 (void) BIO_reset(biobuf);
1338 notBefore = X509_get_notBefore(certificate);
1339 ASN1_TIME_print(biobuf, notBefore);
1340 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1341 if (len < 0) {
1342 _setSSLError(NULL, 0, __FILE__, __LINE__);
1343 goto fail1;
1344 }
1345 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1346 if (pnotBefore == NULL)
1347 goto fail1;
1348 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1349 Py_DECREF(pnotBefore);
1350 goto fail1;
1351 }
1352 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001353
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001354 (void) BIO_reset(biobuf);
1355 notAfter = X509_get_notAfter(certificate);
1356 ASN1_TIME_print(biobuf, notAfter);
1357 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1358 if (len < 0) {
1359 _setSSLError(NULL, 0, __FILE__, __LINE__);
1360 goto fail1;
1361 }
1362 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1363 if (pnotAfter == NULL)
1364 goto fail1;
1365 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1366 Py_DECREF(pnotAfter);
1367 goto fail1;
1368 }
1369 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001370
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001371 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001372
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001373 peer_alt_names = _get_peer_alt_names(certificate);
1374 if (peer_alt_names == NULL)
1375 goto fail1;
1376 else if (peer_alt_names != Py_None) {
1377 if (PyDict_SetItemString(retval, "subjectAltName",
1378 peer_alt_names) < 0) {
1379 Py_DECREF(peer_alt_names);
1380 goto fail1;
1381 }
1382 Py_DECREF(peer_alt_names);
1383 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001384
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001385 /* Authority Information Access: OCSP URIs */
1386 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1387 if (obj == NULL) {
1388 goto fail1;
1389 } else if (obj != Py_None) {
1390 result = PyDict_SetItemString(retval, "OCSP", obj);
1391 Py_DECREF(obj);
1392 if (result < 0) {
1393 goto fail1;
1394 }
1395 }
1396
1397 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1398 if (obj == NULL) {
1399 goto fail1;
1400 } else if (obj != Py_None) {
1401 result = PyDict_SetItemString(retval, "caIssuers", obj);
1402 Py_DECREF(obj);
1403 if (result < 0) {
1404 goto fail1;
1405 }
1406 }
1407
1408 /* CDP (CRL distribution points) */
1409 obj = _get_crl_dp(certificate);
1410 if (obj == NULL) {
1411 goto fail1;
1412 } else if (obj != Py_None) {
1413 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1414 Py_DECREF(obj);
1415 if (result < 0) {
1416 goto fail1;
1417 }
1418 }
1419
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001420 BIO_free(biobuf);
1421 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001422
1423 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001424 if (biobuf != NULL)
1425 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001426 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001427 Py_XDECREF(retval);
1428 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001429}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001430
Christian Heimes9a5395a2013-06-17 15:44:12 +02001431static PyObject *
1432_certificate_to_der(X509 *certificate)
1433{
1434 unsigned char *bytes_buf = NULL;
1435 int len;
1436 PyObject *retval;
1437
1438 bytes_buf = NULL;
1439 len = i2d_X509(certificate, &bytes_buf);
1440 if (len < 0) {
1441 _setSSLError(NULL, 0, __FILE__, __LINE__);
1442 return NULL;
1443 }
1444 /* this is actually an immutable bytes sequence */
1445 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1446 OPENSSL_free(bytes_buf);
1447 return retval;
1448}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001449
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001450/*[clinic input]
1451_ssl._test_decode_cert
1452 path: object(converter="PyUnicode_FSConverter")
1453 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001454
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001455[clinic start generated code]*/
1456
1457static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001458_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1459/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001460{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001461 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001462 X509 *x=NULL;
1463 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001464
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001465 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1466 PyErr_SetString(PySSLErrorObject,
1467 "Can't malloc memory to read file");
1468 goto fail0;
1469 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001470
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001471 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001472 PyErr_SetString(PySSLErrorObject,
1473 "Can't open file");
1474 goto fail0;
1475 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001476
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001477 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1478 if (x == NULL) {
1479 PyErr_SetString(PySSLErrorObject,
1480 "Error decoding PEM-encoded file");
1481 goto fail0;
1482 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001483
Antoine Pitroufb046912010-11-09 20:21:19 +00001484 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001485 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001486
1487 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001488 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001489 if (cert != NULL) BIO_free(cert);
1490 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001491}
1492
1493
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001494/*[clinic input]
1495_ssl._SSLSocket.peer_certificate
1496 der as binary_mode: bool = False
1497 /
1498
1499Returns the certificate for the peer.
1500
1501If no certificate was provided, returns None. If a certificate was
1502provided, but not validated, returns an empty dictionary. Otherwise
1503returns a dict containing information about the peer certificate.
1504
1505If the optional argument is True, returns a DER-encoded copy of the
1506peer certificate, or None if no certificate was provided. This will
1507return the certificate even if it wasn't validated.
1508[clinic start generated code]*/
1509
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001510static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001511_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1512/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001513{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001514 int verification;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001515
Antoine Pitrou20b85552013-09-29 19:50:53 +02001516 if (!self->handshake_done) {
1517 PyErr_SetString(PyExc_ValueError,
1518 "handshake not done yet");
1519 return NULL;
1520 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001521 if (!self->peer_cert)
1522 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001523
Antoine Pitrou721738f2012-08-15 23:20:39 +02001524 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001525 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001526 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001527 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001528 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001529 if ((verification & SSL_VERIFY_PEER) == 0)
1530 return PyDict_New();
1531 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001532 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001533 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001534}
1535
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001536static PyObject *
1537cipher_to_tuple(const SSL_CIPHER *cipher)
1538{
1539 const char *cipher_name, *cipher_protocol;
1540 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001541 if (retval == NULL)
1542 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001543
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001544 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001545 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001546 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001547 PyTuple_SET_ITEM(retval, 0, Py_None);
1548 } else {
1549 v = PyUnicode_FromString(cipher_name);
1550 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001551 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001552 PyTuple_SET_ITEM(retval, 0, v);
1553 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001554
1555 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001556 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001557 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558 PyTuple_SET_ITEM(retval, 1, Py_None);
1559 } else {
1560 v = PyUnicode_FromString(cipher_protocol);
1561 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, 1, v);
1564 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001565
1566 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001567 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001568 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001569 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001570
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001571 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001572
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001573 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001574 Py_DECREF(retval);
1575 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001576}
1577
Christian Heimes25bfcd52016-09-06 00:04:45 +02001578#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1579static PyObject *
1580cipher_to_dict(const SSL_CIPHER *cipher)
1581{
1582 const char *cipher_name, *cipher_protocol;
1583
1584 unsigned long cipher_id;
1585 int alg_bits, strength_bits, len;
1586 char buf[512] = {0};
1587#if OPENSSL_VERSION_1_1
1588 int aead, nid;
1589 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1590#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001591
1592 /* can be NULL */
1593 cipher_name = SSL_CIPHER_get_name(cipher);
1594 cipher_protocol = SSL_CIPHER_get_version(cipher);
1595 cipher_id = SSL_CIPHER_get_id(cipher);
1596 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1597 len = strlen(buf);
1598 if (len > 1 && buf[len-1] == '\n')
1599 buf[len-1] = '\0';
1600 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1601
1602#if OPENSSL_VERSION_1_1
1603 aead = SSL_CIPHER_is_aead(cipher);
1604 nid = SSL_CIPHER_get_cipher_nid(cipher);
1605 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1606 nid = SSL_CIPHER_get_digest_nid(cipher);
1607 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1608 nid = SSL_CIPHER_get_kx_nid(cipher);
1609 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1610 nid = SSL_CIPHER_get_auth_nid(cipher);
1611 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1612#endif
1613
Victor Stinner410b9882016-09-12 12:00:23 +02001614 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001615 "{sksssssssisi"
1616#if OPENSSL_VERSION_1_1
1617 "sOssssssss"
1618#endif
1619 "}",
1620 "id", cipher_id,
1621 "name", cipher_name,
1622 "protocol", cipher_protocol,
1623 "description", buf,
1624 "strength_bits", strength_bits,
1625 "alg_bits", alg_bits
1626#if OPENSSL_VERSION_1_1
1627 ,"aead", aead ? Py_True : Py_False,
1628 "symmetric", skcipher,
1629 "digest", digest,
1630 "kea", kx,
1631 "auth", auth
1632#endif
1633 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001634}
1635#endif
1636
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001637/*[clinic input]
1638_ssl._SSLSocket.shared_ciphers
1639[clinic start generated code]*/
1640
1641static PyObject *
1642_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1643/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001644{
1645 STACK_OF(SSL_CIPHER) *ciphers;
1646 int i;
1647 PyObject *res;
1648
Christian Heimes598894f2016-09-05 23:19:05 +02001649 ciphers = SSL_get_ciphers(self->ssl);
1650 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001651 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001652 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1653 if (!res)
1654 return NULL;
1655 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1656 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1657 if (!tup) {
1658 Py_DECREF(res);
1659 return NULL;
1660 }
1661 PyList_SET_ITEM(res, i, tup);
1662 }
1663 return res;
1664}
1665
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001666/*[clinic input]
1667_ssl._SSLSocket.cipher
1668[clinic start generated code]*/
1669
1670static PyObject *
1671_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1672/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001673{
1674 const SSL_CIPHER *current;
1675
1676 if (self->ssl == NULL)
1677 Py_RETURN_NONE;
1678 current = SSL_get_current_cipher(self->ssl);
1679 if (current == NULL)
1680 Py_RETURN_NONE;
1681 return cipher_to_tuple(current);
1682}
1683
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001684/*[clinic input]
1685_ssl._SSLSocket.version
1686[clinic start generated code]*/
1687
1688static PyObject *
1689_ssl__SSLSocket_version_impl(PySSLSocket *self)
1690/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001691{
1692 const char *version;
1693
1694 if (self->ssl == NULL)
1695 Py_RETURN_NONE;
1696 version = SSL_get_version(self->ssl);
1697 if (!strcmp(version, "unknown"))
1698 Py_RETURN_NONE;
1699 return PyUnicode_FromString(version);
1700}
1701
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001702#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001703/*[clinic input]
1704_ssl._SSLSocket.selected_npn_protocol
1705[clinic start generated code]*/
1706
1707static PyObject *
1708_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1709/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1710{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001711 const unsigned char *out;
1712 unsigned int outlen;
1713
Victor Stinner4569cd52013-06-23 14:58:43 +02001714 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001715 &out, &outlen);
1716
1717 if (out == NULL)
1718 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001719 return PyUnicode_FromStringAndSize((char *)out, outlen);
1720}
1721#endif
1722
1723#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001724/*[clinic input]
1725_ssl._SSLSocket.selected_alpn_protocol
1726[clinic start generated code]*/
1727
1728static PyObject *
1729_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1730/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1731{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001732 const unsigned char *out;
1733 unsigned int outlen;
1734
1735 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1736
1737 if (out == NULL)
1738 Py_RETURN_NONE;
1739 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001740}
1741#endif
1742
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001743/*[clinic input]
1744_ssl._SSLSocket.compression
1745[clinic start generated code]*/
1746
1747static PyObject *
1748_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1749/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1750{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001751#ifdef OPENSSL_NO_COMP
1752 Py_RETURN_NONE;
1753#else
1754 const COMP_METHOD *comp_method;
1755 const char *short_name;
1756
1757 if (self->ssl == NULL)
1758 Py_RETURN_NONE;
1759 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001760 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001761 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001762 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001763 if (short_name == NULL)
1764 Py_RETURN_NONE;
1765 return PyUnicode_DecodeFSDefault(short_name);
1766#endif
1767}
1768
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001769static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1770 Py_INCREF(self->ctx);
1771 return self->ctx;
1772}
1773
1774static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1775 void *closure) {
1776
1777 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001778#if !HAVE_SNI
1779 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1780 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001781 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001782#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001783 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001784 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001785 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001786#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001787 } else {
1788 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1789 return -1;
1790 }
1791
1792 return 0;
1793}
1794
1795PyDoc_STRVAR(PySSL_set_context_doc,
1796"_setter_context(ctx)\n\
1797\
1798This changes the context associated with the SSLSocket. This is typically\n\
1799used from within a callback function set by the set_servername_callback\n\
1800on the SSLContext to change the certificate information associated with the\n\
1801SSLSocket before the cryptographic exchange handshake messages\n");
1802
1803
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001804static PyObject *
1805PySSL_get_server_side(PySSLSocket *self, void *c)
1806{
1807 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1808}
1809
1810PyDoc_STRVAR(PySSL_get_server_side_doc,
1811"Whether this is a server-side socket.");
1812
1813static PyObject *
1814PySSL_get_server_hostname(PySSLSocket *self, void *c)
1815{
1816 if (self->server_hostname == NULL)
1817 Py_RETURN_NONE;
1818 Py_INCREF(self->server_hostname);
1819 return self->server_hostname;
1820}
1821
1822PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1823"The currently set server hostname (for SNI).");
1824
1825static PyObject *
1826PySSL_get_owner(PySSLSocket *self, void *c)
1827{
1828 PyObject *owner;
1829
1830 if (self->owner == NULL)
1831 Py_RETURN_NONE;
1832
1833 owner = PyWeakref_GetObject(self->owner);
1834 Py_INCREF(owner);
1835 return owner;
1836}
1837
1838static int
1839PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1840{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001841 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001842 if (self->owner == NULL)
1843 return -1;
1844 return 0;
1845}
1846
1847PyDoc_STRVAR(PySSL_get_owner_doc,
1848"The Python-level owner of this object.\
1849Passed as \"self\" in servername callback.");
1850
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001851
Antoine Pitrou152efa22010-05-16 18:19:27 +00001852static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001853{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001854 if (self->peer_cert) /* Possible not to have one? */
1855 X509_free (self->peer_cert);
1856 if (self->ssl)
1857 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001858 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001859 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001860 Py_XDECREF(self->server_hostname);
1861 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001862 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001863}
1864
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001865/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001866 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001867 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001868 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001869
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001870static int
Victor Stinner14690702015-04-06 22:46:13 +02001871PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001872{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001873 int rc;
1874#ifdef HAVE_POLL
1875 struct pollfd pollfd;
1876 _PyTime_t ms;
1877#else
1878 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001879 fd_set fds;
1880 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001881#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001882
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001883 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001884 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001885 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001886 else if (timeout < 0) {
1887 if (s->sock_timeout > 0)
1888 return SOCKET_HAS_TIMED_OUT;
1889 else
1890 return SOCKET_IS_BLOCKING;
1891 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001892
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001893 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001894 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001895 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001896
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001897 /* Prefer poll, if available, since you can poll() any fd
1898 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001899#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001900 pollfd.fd = s->sock_fd;
1901 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001902
Victor Stinner14690702015-04-06 22:46:13 +02001903 /* timeout is in seconds, poll() uses milliseconds */
1904 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001905 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001906
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001907 PySSL_BEGIN_ALLOW_THREADS
1908 rc = poll(&pollfd, 1, (int)ms);
1909 PySSL_END_ALLOW_THREADS
1910#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001911 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001912 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001913 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001914
Victor Stinner14690702015-04-06 22:46:13 +02001915 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001916
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001917 FD_ZERO(&fds);
1918 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001919
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001920 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001921 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001922 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001923 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001924 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001925 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001926 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001927 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001928#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001929
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001930 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1931 (when we are able to write or when there's something to read) */
1932 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001933}
1934
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001935/*[clinic input]
1936_ssl._SSLSocket.write
1937 b: Py_buffer
1938 /
1939
1940Writes the bytes-like object b into the SSL object.
1941
1942Returns the number of bytes written.
1943[clinic start generated code]*/
1944
1945static PyObject *
1946_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1947/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001948{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001949 int len;
1950 int sockstate;
1951 int err;
1952 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001953 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001954 _PyTime_t timeout, deadline = 0;
1955 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001956
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001957 if (sock != NULL) {
1958 if (((PyObject*)sock) == Py_None) {
1959 _setSSLError("Underlying socket connection gone",
1960 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1961 return NULL;
1962 }
1963 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001964 }
1965
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001966 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001967 PyErr_Format(PyExc_OverflowError,
1968 "string longer than %d bytes", INT_MAX);
1969 goto error;
1970 }
1971
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001972 if (sock != NULL) {
1973 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001974 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001975 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1976 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1977 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001978
Victor Stinner14690702015-04-06 22:46:13 +02001979 timeout = GET_SOCKET_TIMEOUT(sock);
1980 has_timeout = (timeout > 0);
1981 if (has_timeout)
1982 deadline = _PyTime_GetMonotonicClock() + timeout;
1983
1984 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001985 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001986 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001987 "The write operation timed out");
1988 goto error;
1989 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1990 PyErr_SetString(PySSLErrorObject,
1991 "Underlying socket has been closed.");
1992 goto error;
1993 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1994 PyErr_SetString(PySSLErrorObject,
1995 "Underlying socket too large for select().");
1996 goto error;
1997 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001998
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001999 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002000 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002001 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002002 err = SSL_get_error(self->ssl, len);
2003 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002004
2005 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002006 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002007
Victor Stinner14690702015-04-06 22:46:13 +02002008 if (has_timeout)
2009 timeout = deadline - _PyTime_GetMonotonicClock();
2010
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002011 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002012 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002013 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002014 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002015 } else {
2016 sockstate = SOCKET_OPERATION_OK;
2017 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002018
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002019 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002020 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002021 "The write operation timed out");
2022 goto error;
2023 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2024 PyErr_SetString(PySSLErrorObject,
2025 "Underlying socket has been closed.");
2026 goto error;
2027 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2028 break;
2029 }
2030 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002031
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002032 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002033 if (len > 0)
2034 return PyLong_FromLong(len);
2035 else
2036 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002037
2038error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002039 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002040 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002041}
2042
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002043/*[clinic input]
2044_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002045
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002046Returns the number of already decrypted bytes available for read, pending on the connection.
2047[clinic start generated code]*/
2048
2049static PyObject *
2050_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2051/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002052{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002053 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002054
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002055 PySSL_BEGIN_ALLOW_THREADS
2056 count = SSL_pending(self->ssl);
2057 PySSL_END_ALLOW_THREADS
2058 if (count < 0)
2059 return PySSL_SetError(self, count, __FILE__, __LINE__);
2060 else
2061 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002062}
2063
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002064/*[clinic input]
2065_ssl._SSLSocket.read
2066 size as len: int
2067 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002068 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002069 ]
2070 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002071
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002072Read up to size bytes from the SSL socket.
2073[clinic start generated code]*/
2074
2075static PyObject *
2076_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2077 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002078/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002079{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002080 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002081 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002082 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002083 int sockstate;
2084 int err;
2085 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002086 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002087 _PyTime_t timeout, deadline = 0;
2088 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002089
Martin Panter5503d472016-03-27 05:35:19 +00002090 if (!group_right_1 && len < 0) {
2091 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2092 return NULL;
2093 }
2094
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002095 if (sock != NULL) {
2096 if (((PyObject*)sock) == Py_None) {
2097 _setSSLError("Underlying socket connection gone",
2098 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2099 return NULL;
2100 }
2101 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002102 }
2103
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002104 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002105 dest = PyBytes_FromStringAndSize(NULL, len);
2106 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002107 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002108 if (len == 0) {
2109 Py_XDECREF(sock);
2110 return dest;
2111 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002112 mem = PyBytes_AS_STRING(dest);
2113 }
2114 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002115 mem = buffer->buf;
2116 if (len <= 0 || len > buffer->len) {
2117 len = (int) buffer->len;
2118 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002119 PyErr_SetString(PyExc_OverflowError,
2120 "maximum length can't fit in a C 'int'");
2121 goto error;
2122 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002123 if (len == 0) {
2124 count = 0;
2125 goto done;
2126 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002127 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002128 }
2129
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002130 if (sock != NULL) {
2131 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002132 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002133 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2134 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2135 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002136
Victor Stinner14690702015-04-06 22:46:13 +02002137 timeout = GET_SOCKET_TIMEOUT(sock);
2138 has_timeout = (timeout > 0);
2139 if (has_timeout)
2140 deadline = _PyTime_GetMonotonicClock() + timeout;
2141
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002142 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002143 PySSL_BEGIN_ALLOW_THREADS
2144 count = SSL_read(self->ssl, mem, len);
2145 err = SSL_get_error(self->ssl, count);
2146 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002147
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002148 if (PyErr_CheckSignals())
2149 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002150
Victor Stinner14690702015-04-06 22:46:13 +02002151 if (has_timeout)
2152 timeout = deadline - _PyTime_GetMonotonicClock();
2153
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002154 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002155 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002156 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002157 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002158 } else if (err == SSL_ERROR_ZERO_RETURN &&
2159 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002160 {
2161 count = 0;
2162 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002163 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002164 else
2165 sockstate = SOCKET_OPERATION_OK;
2166
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002167 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002168 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002169 "The read operation timed out");
2170 goto error;
2171 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2172 break;
2173 }
2174 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002175
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002176 if (count <= 0) {
2177 PySSL_SetError(self, count, __FILE__, __LINE__);
2178 goto error;
2179 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002180
2181done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002182 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002183 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002184 _PyBytes_Resize(&dest, count);
2185 return dest;
2186 }
2187 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002188 return PyLong_FromLong(count);
2189 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002190
2191error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002192 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002193 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002194 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002195 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002196}
2197
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002198/*[clinic input]
2199_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002200
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002201Does the SSL shutdown handshake with the remote end.
2202
2203Returns the underlying socket object.
2204[clinic start generated code]*/
2205
2206static PyObject *
2207_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2208/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002209{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002210 int err, ssl_err, sockstate, nonblocking;
2211 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002212 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002213 _PyTime_t timeout, deadline = 0;
2214 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002215
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002216 if (sock != NULL) {
2217 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002218 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002219 _setSSLError("Underlying socket connection gone",
2220 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2221 return NULL;
2222 }
2223 Py_INCREF(sock);
2224
2225 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002226 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002227 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2228 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002229 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002230
Victor Stinner14690702015-04-06 22:46:13 +02002231 timeout = GET_SOCKET_TIMEOUT(sock);
2232 has_timeout = (timeout > 0);
2233 if (has_timeout)
2234 deadline = _PyTime_GetMonotonicClock() + timeout;
2235
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002236 while (1) {
2237 PySSL_BEGIN_ALLOW_THREADS
2238 /* Disable read-ahead so that unwrap can work correctly.
2239 * Otherwise OpenSSL might read in too much data,
2240 * eating clear text data that happens to be
2241 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002242 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002243 * function is used and the shutdown_seen_zero != 0
2244 * condition is met.
2245 */
2246 if (self->shutdown_seen_zero)
2247 SSL_set_read_ahead(self->ssl, 0);
2248 err = SSL_shutdown(self->ssl);
2249 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002250
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002251 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2252 if (err > 0)
2253 break;
2254 if (err == 0) {
2255 /* Don't loop endlessly; instead preserve legacy
2256 behaviour of trying SSL_shutdown() only twice.
2257 This looks necessary for OpenSSL < 0.9.8m */
2258 if (++zeros > 1)
2259 break;
2260 /* Shutdown was sent, now try receiving */
2261 self->shutdown_seen_zero = 1;
2262 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002263 }
2264
Victor Stinner14690702015-04-06 22:46:13 +02002265 if (has_timeout)
2266 timeout = deadline - _PyTime_GetMonotonicClock();
2267
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002268 /* Possibly retry shutdown until timeout or failure */
2269 ssl_err = SSL_get_error(self->ssl, err);
2270 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002271 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002272 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002273 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002274 else
2275 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002276
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002277 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2278 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002279 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002280 "The read operation timed out");
2281 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002282 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002283 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002284 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002285 }
2286 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2287 PyErr_SetString(PySSLErrorObject,
2288 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002289 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002290 }
2291 else if (sockstate != SOCKET_OPERATION_OK)
2292 /* Retain the SSL error code */
2293 break;
2294 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002295
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002296 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002297 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002298 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002299 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002300 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002301 /* It's already INCREF'ed */
2302 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002303 else
2304 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002305
2306error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002307 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002308 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002309}
2310
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002311/*[clinic input]
2312_ssl._SSLSocket.tls_unique_cb
2313
2314Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2315
2316If the TLS handshake is not yet complete, None is returned.
2317[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002318
Antoine Pitroud6494802011-07-21 01:11:30 +02002319static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002320_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2321/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002322{
2323 PyObject *retval = NULL;
2324 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002325 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002326
2327 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2328 /* if session is resumed XOR we are the client */
2329 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2330 }
2331 else {
2332 /* if a new session XOR we are the server */
2333 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2334 }
2335
2336 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002337 if (len == 0)
2338 Py_RETURN_NONE;
2339
2340 retval = PyBytes_FromStringAndSize(buf, len);
2341
2342 return retval;
2343}
2344
Christian Heimes99a65702016-09-10 23:44:53 +02002345#ifdef OPENSSL_VERSION_1_1
2346
2347static SSL_SESSION*
2348_ssl_session_dup(SSL_SESSION *session) {
2349 SSL_SESSION *newsession = NULL;
2350 int slen;
2351 unsigned char *senc = NULL, *p;
2352 const unsigned char *const_p;
2353
2354 if (session == NULL) {
2355 PyErr_SetString(PyExc_ValueError, "Invalid session");
2356 goto error;
2357 }
2358
2359 /* get length */
2360 slen = i2d_SSL_SESSION(session, NULL);
2361 if (slen == 0 || slen > 0xFF00) {
2362 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2363 goto error;
2364 }
2365 if ((senc = PyMem_Malloc(slen)) == NULL) {
2366 PyErr_NoMemory();
2367 goto error;
2368 }
2369 p = senc;
2370 if (!i2d_SSL_SESSION(session, &p)) {
2371 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2372 goto error;
2373 }
2374 const_p = senc;
2375 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2376 if (session == NULL) {
2377 goto error;
2378 }
2379 PyMem_Free(senc);
2380 return newsession;
2381 error:
2382 if (senc != NULL) {
2383 PyMem_Free(senc);
2384 }
2385 return NULL;
2386}
2387#endif
2388
2389static PyObject *
2390PySSL_get_session(PySSLSocket *self, void *closure) {
2391 /* get_session can return sessions from a server-side connection,
2392 * it does not check for handshake done or client socket. */
2393 PySSLSession *pysess;
2394 SSL_SESSION *session;
2395
2396#ifdef OPENSSL_VERSION_1_1
2397 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2398 * https://github.com/openssl/openssl/issues/1550 */
2399 session = SSL_get0_session(self->ssl); /* borrowed reference */
2400 if (session == NULL) {
2401 Py_RETURN_NONE;
2402 }
2403 if ((session = _ssl_session_dup(session)) == NULL) {
2404 return NULL;
2405 }
2406#else
2407 session = SSL_get1_session(self->ssl);
2408 if (session == NULL) {
2409 Py_RETURN_NONE;
2410 }
2411#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002412 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002413 if (pysess == NULL) {
2414 SSL_SESSION_free(session);
2415 return NULL;
2416 }
2417
2418 assert(self->ctx);
2419 pysess->ctx = self->ctx;
2420 Py_INCREF(pysess->ctx);
2421 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002422 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002423 return (PyObject *)pysess;
2424}
2425
2426static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2427 void *closure)
2428 {
2429 PySSLSession *pysess;
2430#ifdef OPENSSL_VERSION_1_1
2431 SSL_SESSION *session;
2432#endif
2433 int result;
2434
2435 if (!PySSLSession_Check(value)) {
2436 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2437 return -1;
2438 }
2439 pysess = (PySSLSession *)value;
2440
2441 if (self->ctx->ctx != pysess->ctx->ctx) {
2442 PyErr_SetString(PyExc_ValueError,
2443 "Session refers to a different SSLContext.");
2444 return -1;
2445 }
2446 if (self->socket_type != PY_SSL_CLIENT) {
2447 PyErr_SetString(PyExc_ValueError,
2448 "Cannot set session for server-side SSLSocket.");
2449 return -1;
2450 }
2451 if (self->handshake_done) {
2452 PyErr_SetString(PyExc_ValueError,
2453 "Cannot set session after handshake.");
2454 return -1;
2455 }
2456#ifdef OPENSSL_VERSION_1_1
2457 /* duplicate session */
2458 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2459 return -1;
2460 }
2461 result = SSL_set_session(self->ssl, session);
2462 /* free duplicate, SSL_set_session() bumps ref count */
2463 SSL_SESSION_free(session);
2464#else
2465 result = SSL_set_session(self->ssl, pysess->session);
2466#endif
2467 if (result == 0) {
2468 _setSSLError(NULL, 0, __FILE__, __LINE__);
2469 return -1;
2470 }
2471 return 0;
2472}
2473
2474PyDoc_STRVAR(PySSL_set_session_doc,
2475"_setter_session(session)\n\
2476\
2477Get / set SSLSession.");
2478
2479static PyObject *
2480PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2481 if (SSL_session_reused(self->ssl)) {
2482 Py_RETURN_TRUE;
2483 } else {
2484 Py_RETURN_FALSE;
2485 }
2486}
2487
2488PyDoc_STRVAR(PySSL_get_session_reused_doc,
2489"Was the client session reused during handshake?");
2490
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002491static PyGetSetDef ssl_getsetlist[] = {
2492 {"context", (getter) PySSL_get_context,
2493 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002494 {"server_side", (getter) PySSL_get_server_side, NULL,
2495 PySSL_get_server_side_doc},
2496 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2497 PySSL_get_server_hostname_doc},
2498 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2499 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002500 {"session", (getter) PySSL_get_session,
2501 (setter) PySSL_set_session, PySSL_set_session_doc},
2502 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2503 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002504 {NULL}, /* sentinel */
2505};
2506
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002507static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002508 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2509 _SSL__SSLSOCKET_WRITE_METHODDEF
2510 _SSL__SSLSOCKET_READ_METHODDEF
2511 _SSL__SSLSOCKET_PENDING_METHODDEF
2512 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2513 _SSL__SSLSOCKET_CIPHER_METHODDEF
2514 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2515 _SSL__SSLSOCKET_VERSION_METHODDEF
2516 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2517 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2518 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2519 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2520 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002521 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002522};
2523
Antoine Pitrou152efa22010-05-16 18:19:27 +00002524static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002525 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002526 "_ssl._SSLSocket", /*tp_name*/
2527 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002528 0, /*tp_itemsize*/
2529 /* methods */
2530 (destructor)PySSL_dealloc, /*tp_dealloc*/
2531 0, /*tp_print*/
2532 0, /*tp_getattr*/
2533 0, /*tp_setattr*/
2534 0, /*tp_reserved*/
2535 0, /*tp_repr*/
2536 0, /*tp_as_number*/
2537 0, /*tp_as_sequence*/
2538 0, /*tp_as_mapping*/
2539 0, /*tp_hash*/
2540 0, /*tp_call*/
2541 0, /*tp_str*/
2542 0, /*tp_getattro*/
2543 0, /*tp_setattro*/
2544 0, /*tp_as_buffer*/
2545 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2546 0, /*tp_doc*/
2547 0, /*tp_traverse*/
2548 0, /*tp_clear*/
2549 0, /*tp_richcompare*/
2550 0, /*tp_weaklistoffset*/
2551 0, /*tp_iter*/
2552 0, /*tp_iternext*/
2553 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002554 0, /*tp_members*/
2555 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002556};
2557
Antoine Pitrou152efa22010-05-16 18:19:27 +00002558
2559/*
2560 * _SSLContext objects
2561 */
2562
Christian Heimes5fe668c2016-09-12 00:01:11 +02002563static int
2564_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2565{
2566 int mode;
2567 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2568
2569 switch(n) {
2570 case PY_SSL_CERT_NONE:
2571 mode = SSL_VERIFY_NONE;
2572 break;
2573 case PY_SSL_CERT_OPTIONAL:
2574 mode = SSL_VERIFY_PEER;
2575 break;
2576 case PY_SSL_CERT_REQUIRED:
2577 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2578 break;
2579 default:
2580 PyErr_SetString(PyExc_ValueError,
2581 "invalid value for verify_mode");
2582 return -1;
2583 }
2584 /* keep current verify cb */
2585 verify_cb = SSL_CTX_get_verify_callback(ctx);
2586 SSL_CTX_set_verify(ctx, mode, verify_cb);
2587 return 0;
2588}
2589
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002590/*[clinic input]
2591@classmethod
2592_ssl._SSLContext.__new__
2593 protocol as proto_version: int
2594 /
2595[clinic start generated code]*/
2596
Antoine Pitrou152efa22010-05-16 18:19:27 +00002597static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002598_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2599/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002600{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002601 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002602 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002603 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002604 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002605#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002606 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002607#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002608
Antoine Pitrou152efa22010-05-16 18:19:27 +00002609 PySSL_BEGIN_ALLOW_THREADS
2610 if (proto_version == PY_SSL_VERSION_TLS1)
2611 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002612#if HAVE_TLSv1_2
2613 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2614 ctx = SSL_CTX_new(TLSv1_1_method());
2615 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2616 ctx = SSL_CTX_new(TLSv1_2_method());
2617#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002618#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002619 else if (proto_version == PY_SSL_VERSION_SSL3)
2620 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002621#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002622#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002623 else if (proto_version == PY_SSL_VERSION_SSL2)
2624 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002625#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002626 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002627 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002628 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2629 ctx = SSL_CTX_new(TLS_client_method());
2630 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2631 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002632 else
2633 proto_version = -1;
2634 PySSL_END_ALLOW_THREADS
2635
2636 if (proto_version == -1) {
2637 PyErr_SetString(PyExc_ValueError,
2638 "invalid protocol version");
2639 return NULL;
2640 }
2641 if (ctx == NULL) {
2642 PyErr_SetString(PySSLErrorObject,
2643 "failed to allocate SSL context");
2644 return NULL;
2645 }
2646
2647 assert(type != NULL && type->tp_alloc != NULL);
2648 self = (PySSLContext *) type->tp_alloc(type, 0);
2649 if (self == NULL) {
2650 SSL_CTX_free(ctx);
2651 return NULL;
2652 }
2653 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002654#ifdef OPENSSL_NPN_NEGOTIATED
2655 self->npn_protocols = NULL;
2656#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002657#ifdef HAVE_ALPN
2658 self->alpn_protocols = NULL;
2659#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002660#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002661 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002662#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002663 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002664 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2665 self->check_hostname = 1;
2666 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2667 Py_DECREF(self);
2668 return NULL;
2669 }
2670 } else {
2671 self->check_hostname = 0;
2672 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2673 Py_DECREF(self);
2674 return NULL;
2675 }
2676 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002677 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002678 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2679 if (proto_version != PY_SSL_VERSION_SSL2)
2680 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002681 if (proto_version != PY_SSL_VERSION_SSL3)
2682 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002683 /* Minimal security flags for server and client side context.
2684 * Client sockets ignore server-side parameters. */
2685#ifdef SSL_OP_NO_COMPRESSION
2686 options |= SSL_OP_NO_COMPRESSION;
2687#endif
2688#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2689 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2690#endif
2691#ifdef SSL_OP_SINGLE_DH_USE
2692 options |= SSL_OP_SINGLE_DH_USE;
2693#endif
2694#ifdef SSL_OP_SINGLE_ECDH_USE
2695 options |= SSL_OP_SINGLE_ECDH_USE;
2696#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002697 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002698
Christian Heimes358cfd42016-09-10 22:43:48 +02002699 /* A bare minimum cipher list without completly broken cipher suites.
2700 * It's far from perfect but gives users a better head start. */
2701 if (proto_version != PY_SSL_VERSION_SSL2) {
2702 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2703 } else {
2704 /* SSLv2 needs MD5 */
2705 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2706 }
2707 if (result == 0) {
2708 Py_DECREF(self);
2709 ERR_clear_error();
2710 PyErr_SetString(PySSLErrorObject,
2711 "No cipher can be selected.");
2712 return NULL;
2713 }
2714
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002715#if defined(SSL_MODE_RELEASE_BUFFERS)
2716 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2717 usage for no cost at all. However, don't do this for OpenSSL versions
2718 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2719 2014-0198. I can't find exactly which beta fixed this CVE, so be
2720 conservative and assume it wasn't fixed until release. We do this check
2721 at runtime to avoid problems from the dynamic linker.
2722 See #25672 for more on this. */
2723 libver = SSLeay();
2724 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2725 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2726 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2727 }
2728#endif
2729
2730
Donald Stufft8ae264c2017-03-02 11:45:29 -05002731#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002732 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2733 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002734 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2735 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002736#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002737 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2738#else
2739 {
2740 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2741 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2742 EC_KEY_free(key);
2743 }
2744#endif
2745#endif
2746
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002747#define SID_CTX "Python"
2748 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2749 sizeof(SID_CTX));
2750#undef SID_CTX
2751
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002752#ifdef X509_V_FLAG_TRUSTED_FIRST
2753 {
2754 /* Improve trust chain building when cross-signed intermediate
2755 certificates are present. See https://bugs.python.org/issue23476. */
2756 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2757 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2758 }
2759#endif
2760
Antoine Pitrou152efa22010-05-16 18:19:27 +00002761 return (PyObject *)self;
2762}
2763
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002764static int
2765context_traverse(PySSLContext *self, visitproc visit, void *arg)
2766{
2767#ifndef OPENSSL_NO_TLSEXT
2768 Py_VISIT(self->set_hostname);
2769#endif
2770 return 0;
2771}
2772
2773static int
2774context_clear(PySSLContext *self)
2775{
2776#ifndef OPENSSL_NO_TLSEXT
2777 Py_CLEAR(self->set_hostname);
2778#endif
2779 return 0;
2780}
2781
Antoine Pitrou152efa22010-05-16 18:19:27 +00002782static void
2783context_dealloc(PySSLContext *self)
2784{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002785 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002786 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002787#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002788 PyMem_FREE(self->npn_protocols);
2789#endif
2790#ifdef HAVE_ALPN
2791 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002792#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002793 Py_TYPE(self)->tp_free(self);
2794}
2795
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002796/*[clinic input]
2797_ssl._SSLContext.set_ciphers
2798 cipherlist: str
2799 /
2800[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002801
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002802static PyObject *
2803_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2804/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2805{
2806 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002807 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002808 /* Clearing the error queue is necessary on some OpenSSL versions,
2809 otherwise the error will be reported again when another SSL call
2810 is done. */
2811 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002812 PyErr_SetString(PySSLErrorObject,
2813 "No cipher can be selected.");
2814 return NULL;
2815 }
2816 Py_RETURN_NONE;
2817}
2818
Christian Heimes25bfcd52016-09-06 00:04:45 +02002819#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2820/*[clinic input]
2821_ssl._SSLContext.get_ciphers
2822[clinic start generated code]*/
2823
2824static PyObject *
2825_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2826/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2827{
2828 SSL *ssl = NULL;
2829 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002830 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002831 int i=0;
2832 PyObject *result = NULL, *dct;
2833
2834 ssl = SSL_new(self->ctx);
2835 if (ssl == NULL) {
2836 _setSSLError(NULL, 0, __FILE__, __LINE__);
2837 goto exit;
2838 }
2839 sk = SSL_get_ciphers(ssl);
2840
2841 result = PyList_New(sk_SSL_CIPHER_num(sk));
2842 if (result == NULL) {
2843 goto exit;
2844 }
2845
2846 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2847 cipher = sk_SSL_CIPHER_value(sk, i);
2848 dct = cipher_to_dict(cipher);
2849 if (dct == NULL) {
2850 Py_CLEAR(result);
2851 goto exit;
2852 }
2853 PyList_SET_ITEM(result, i, dct);
2854 }
2855
2856 exit:
2857 if (ssl != NULL)
2858 SSL_free(ssl);
2859 return result;
2860
2861}
2862#endif
2863
2864
Benjamin Petersonc54de472015-01-28 12:06:39 -05002865#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002866static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002867do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2868 const unsigned char *server_protocols, unsigned int server_protocols_len,
2869 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002870{
Benjamin Peterson88615022015-01-23 17:30:26 -05002871 int ret;
2872 if (client_protocols == NULL) {
2873 client_protocols = (unsigned char *)"";
2874 client_protocols_len = 0;
2875 }
2876 if (server_protocols == NULL) {
2877 server_protocols = (unsigned char *)"";
2878 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002879 }
2880
Benjamin Peterson88615022015-01-23 17:30:26 -05002881 ret = SSL_select_next_proto(out, outlen,
2882 server_protocols, server_protocols_len,
2883 client_protocols, client_protocols_len);
2884 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2885 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002886
2887 return SSL_TLSEXT_ERR_OK;
2888}
2889
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002890/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2891static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002892_advertiseNPN_cb(SSL *s,
2893 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002894 void *args)
2895{
2896 PySSLContext *ssl_ctx = (PySSLContext *) args;
2897
2898 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002899 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002900 *len = 0;
2901 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002902 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002903 *len = ssl_ctx->npn_protocols_len;
2904 }
2905
2906 return SSL_TLSEXT_ERR_OK;
2907}
2908/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2909static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002910_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002911 unsigned char **out, unsigned char *outlen,
2912 const unsigned char *server, unsigned int server_len,
2913 void *args)
2914{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002915 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002916 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002917 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002918}
2919#endif
2920
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002921/*[clinic input]
2922_ssl._SSLContext._set_npn_protocols
2923 protos: Py_buffer
2924 /
2925[clinic start generated code]*/
2926
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002927static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002928_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2929 Py_buffer *protos)
2930/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002931{
2932#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002933 PyMem_Free(self->npn_protocols);
2934 self->npn_protocols = PyMem_Malloc(protos->len);
2935 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002936 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002937 memcpy(self->npn_protocols, protos->buf, protos->len);
2938 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002939
2940 /* set both server and client callbacks, because the context can
2941 * be used to create both types of sockets */
2942 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2943 _advertiseNPN_cb,
2944 self);
2945 SSL_CTX_set_next_proto_select_cb(self->ctx,
2946 _selectNPN_cb,
2947 self);
2948
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002949 Py_RETURN_NONE;
2950#else
2951 PyErr_SetString(PyExc_NotImplementedError,
2952 "The NPN extension requires OpenSSL 1.0.1 or later.");
2953 return NULL;
2954#endif
2955}
2956
Benjamin Petersoncca27322015-01-23 16:35:37 -05002957#ifdef HAVE_ALPN
2958static int
2959_selectALPN_cb(SSL *s,
2960 const unsigned char **out, unsigned char *outlen,
2961 const unsigned char *client_protocols, unsigned int client_protocols_len,
2962 void *args)
2963{
2964 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002965 return do_protocol_selection(1, (unsigned char **)out, outlen,
2966 ctx->alpn_protocols, ctx->alpn_protocols_len,
2967 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002968}
2969#endif
2970
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002971/*[clinic input]
2972_ssl._SSLContext._set_alpn_protocols
2973 protos: Py_buffer
2974 /
2975[clinic start generated code]*/
2976
Benjamin Petersoncca27322015-01-23 16:35:37 -05002977static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002978_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2979 Py_buffer *protos)
2980/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002981{
2982#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002983 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002984 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002985 if (!self->alpn_protocols)
2986 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002987 memcpy(self->alpn_protocols, protos->buf, protos->len);
2988 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002989
2990 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2991 return PyErr_NoMemory();
2992 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2993
Benjamin Petersoncca27322015-01-23 16:35:37 -05002994 Py_RETURN_NONE;
2995#else
2996 PyErr_SetString(PyExc_NotImplementedError,
2997 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2998 return NULL;
2999#endif
3000}
3001
Antoine Pitrou152efa22010-05-16 18:19:27 +00003002static PyObject *
3003get_verify_mode(PySSLContext *self, void *c)
3004{
3005 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3006 case SSL_VERIFY_NONE:
3007 return PyLong_FromLong(PY_SSL_CERT_NONE);
3008 case SSL_VERIFY_PEER:
3009 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3010 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3011 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3012 }
3013 PyErr_SetString(PySSLErrorObject,
3014 "invalid return value from SSL_CTX_get_verify_mode");
3015 return NULL;
3016}
3017
3018static int
3019set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3020{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003021 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003022 if (!PyArg_Parse(arg, "i", &n))
3023 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003024 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003025 PyErr_SetString(PyExc_ValueError,
3026 "Cannot set verify_mode to CERT_NONE when "
3027 "check_hostname is enabled.");
3028 return -1;
3029 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003030 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003031}
3032
3033static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003034get_verify_flags(PySSLContext *self, void *c)
3035{
3036 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003037 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003038 unsigned long flags;
3039
3040 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003041 param = X509_STORE_get0_param(store);
3042 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003043 return PyLong_FromUnsignedLong(flags);
3044}
3045
3046static int
3047set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3048{
3049 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003050 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003051 unsigned long new_flags, flags, set, clear;
3052
3053 if (!PyArg_Parse(arg, "k", &new_flags))
3054 return -1;
3055 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003056 param = X509_STORE_get0_param(store);
3057 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003058 clear = flags & ~new_flags;
3059 set = ~flags & new_flags;
3060 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003061 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003062 _setSSLError(NULL, 0, __FILE__, __LINE__);
3063 return -1;
3064 }
3065 }
3066 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003067 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003068 _setSSLError(NULL, 0, __FILE__, __LINE__);
3069 return -1;
3070 }
3071 }
3072 return 0;
3073}
3074
3075static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003076get_options(PySSLContext *self, void *c)
3077{
3078 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3079}
3080
3081static int
3082set_options(PySSLContext *self, PyObject *arg, void *c)
3083{
3084 long new_opts, opts, set, clear;
3085 if (!PyArg_Parse(arg, "l", &new_opts))
3086 return -1;
3087 opts = SSL_CTX_get_options(self->ctx);
3088 clear = opts & ~new_opts;
3089 set = ~opts & new_opts;
3090 if (clear) {
3091#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3092 SSL_CTX_clear_options(self->ctx, clear);
3093#else
3094 PyErr_SetString(PyExc_ValueError,
3095 "can't clear options before OpenSSL 0.9.8m");
3096 return -1;
3097#endif
3098 }
3099 if (set)
3100 SSL_CTX_set_options(self->ctx, set);
3101 return 0;
3102}
3103
Christian Heimes1aa9a752013-12-02 02:41:19 +01003104static PyObject *
3105get_check_hostname(PySSLContext *self, void *c)
3106{
3107 return PyBool_FromLong(self->check_hostname);
3108}
3109
3110static int
3111set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3112{
3113 int check_hostname;
3114 if (!PyArg_Parse(arg, "p", &check_hostname))
3115 return -1;
3116 if (check_hostname &&
3117 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3118 PyErr_SetString(PyExc_ValueError,
3119 "check_hostname needs a SSL context with either "
3120 "CERT_OPTIONAL or CERT_REQUIRED");
3121 return -1;
3122 }
3123 self->check_hostname = check_hostname;
3124 return 0;
3125}
3126
3127
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003128typedef struct {
3129 PyThreadState *thread_state;
3130 PyObject *callable;
3131 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003132 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003133 int error;
3134} _PySSLPasswordInfo;
3135
3136static int
3137_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3138 const char *bad_type_error)
3139{
3140 /* Set the password and size fields of a _PySSLPasswordInfo struct
3141 from a unicode, bytes, or byte array object.
3142 The password field will be dynamically allocated and must be freed
3143 by the caller */
3144 PyObject *password_bytes = NULL;
3145 const char *data = NULL;
3146 Py_ssize_t size;
3147
3148 if (PyUnicode_Check(password)) {
3149 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3150 if (!password_bytes) {
3151 goto error;
3152 }
3153 data = PyBytes_AS_STRING(password_bytes);
3154 size = PyBytes_GET_SIZE(password_bytes);
3155 } else if (PyBytes_Check(password)) {
3156 data = PyBytes_AS_STRING(password);
3157 size = PyBytes_GET_SIZE(password);
3158 } else if (PyByteArray_Check(password)) {
3159 data = PyByteArray_AS_STRING(password);
3160 size = PyByteArray_GET_SIZE(password);
3161 } else {
3162 PyErr_SetString(PyExc_TypeError, bad_type_error);
3163 goto error;
3164 }
3165
Victor Stinner9ee02032013-06-23 15:08:23 +02003166 if (size > (Py_ssize_t)INT_MAX) {
3167 PyErr_Format(PyExc_ValueError,
3168 "password cannot be longer than %d bytes", INT_MAX);
3169 goto error;
3170 }
3171
Victor Stinner11ebff22013-07-07 17:07:52 +02003172 PyMem_Free(pw_info->password);
3173 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003174 if (!pw_info->password) {
3175 PyErr_SetString(PyExc_MemoryError,
3176 "unable to allocate password buffer");
3177 goto error;
3178 }
3179 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003180 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003181
3182 Py_XDECREF(password_bytes);
3183 return 1;
3184
3185error:
3186 Py_XDECREF(password_bytes);
3187 return 0;
3188}
3189
3190static int
3191_password_callback(char *buf, int size, int rwflag, void *userdata)
3192{
3193 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3194 PyObject *fn_ret = NULL;
3195
3196 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3197
3198 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003199 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003200 if (!fn_ret) {
3201 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3202 core python API, so we could use it to add a frame here */
3203 goto error;
3204 }
3205
3206 if (!_pwinfo_set(pw_info, fn_ret,
3207 "password callback must return a string")) {
3208 goto error;
3209 }
3210 Py_CLEAR(fn_ret);
3211 }
3212
3213 if (pw_info->size > size) {
3214 PyErr_Format(PyExc_ValueError,
3215 "password cannot be longer than %d bytes", size);
3216 goto error;
3217 }
3218
3219 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3220 memcpy(buf, pw_info->password, pw_info->size);
3221 return pw_info->size;
3222
3223error:
3224 Py_XDECREF(fn_ret);
3225 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3226 pw_info->error = 1;
3227 return -1;
3228}
3229
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003230/*[clinic input]
3231_ssl._SSLContext.load_cert_chain
3232 certfile: object
3233 keyfile: object = NULL
3234 password: object = NULL
3235
3236[clinic start generated code]*/
3237
Antoine Pitroub5218772010-05-21 09:56:06 +00003238static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003239_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3240 PyObject *keyfile, PyObject *password)
3241/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003242{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003243 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003244 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3245 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003246 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003247 int r;
3248
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003249 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003250 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003251 if (keyfile == Py_None)
3252 keyfile = NULL;
3253 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3254 PyErr_SetString(PyExc_TypeError,
3255 "certfile should be a valid filesystem path");
3256 return NULL;
3257 }
3258 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3259 PyErr_SetString(PyExc_TypeError,
3260 "keyfile should be a valid filesystem path");
3261 goto error;
3262 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003263 if (password && password != Py_None) {
3264 if (PyCallable_Check(password)) {
3265 pw_info.callable = password;
3266 } else if (!_pwinfo_set(&pw_info, password,
3267 "password should be a string or callable")) {
3268 goto error;
3269 }
3270 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3271 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3272 }
3273 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003274 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3275 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003276 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003277 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003278 if (pw_info.error) {
3279 ERR_clear_error();
3280 /* the password callback has already set the error information */
3281 }
3282 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003283 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003284 PyErr_SetFromErrno(PyExc_IOError);
3285 }
3286 else {
3287 _setSSLError(NULL, 0, __FILE__, __LINE__);
3288 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003289 goto error;
3290 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003291 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003292 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003293 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3294 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003295 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3296 Py_CLEAR(keyfile_bytes);
3297 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003298 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003299 if (pw_info.error) {
3300 ERR_clear_error();
3301 /* the password callback has already set the error information */
3302 }
3303 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003304 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003305 PyErr_SetFromErrno(PyExc_IOError);
3306 }
3307 else {
3308 _setSSLError(NULL, 0, __FILE__, __LINE__);
3309 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003310 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003311 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003312 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003313 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003314 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003315 if (r != 1) {
3316 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003317 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003318 }
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_RETURN_NONE;
3323
3324error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003325 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3326 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003327 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003328 Py_XDECREF(keyfile_bytes);
3329 Py_XDECREF(certfile_bytes);
3330 return NULL;
3331}
3332
Christian Heimesefff7062013-11-21 03:35:02 +01003333/* internal helper function, returns -1 on error
3334 */
3335static int
3336_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3337 int filetype)
3338{
3339 BIO *biobuf = NULL;
3340 X509_STORE *store;
3341 int retval = 0, err, loaded = 0;
3342
3343 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3344
3345 if (len <= 0) {
3346 PyErr_SetString(PyExc_ValueError,
3347 "Empty certificate data");
3348 return -1;
3349 } else if (len > INT_MAX) {
3350 PyErr_SetString(PyExc_OverflowError,
3351 "Certificate data is too long.");
3352 return -1;
3353 }
3354
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003355 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003356 if (biobuf == NULL) {
3357 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3358 return -1;
3359 }
3360
3361 store = SSL_CTX_get_cert_store(self->ctx);
3362 assert(store != NULL);
3363
3364 while (1) {
3365 X509 *cert = NULL;
3366 int r;
3367
3368 if (filetype == SSL_FILETYPE_ASN1) {
3369 cert = d2i_X509_bio(biobuf, NULL);
3370 } else {
3371 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003372 SSL_CTX_get_default_passwd_cb(self->ctx),
3373 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3374 );
Christian Heimesefff7062013-11-21 03:35:02 +01003375 }
3376 if (cert == NULL) {
3377 break;
3378 }
3379 r = X509_STORE_add_cert(store, cert);
3380 X509_free(cert);
3381 if (!r) {
3382 err = ERR_peek_last_error();
3383 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3384 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3385 /* cert already in hash table, not an error */
3386 ERR_clear_error();
3387 } else {
3388 break;
3389 }
3390 }
3391 loaded++;
3392 }
3393
3394 err = ERR_peek_last_error();
3395 if ((filetype == SSL_FILETYPE_ASN1) &&
3396 (loaded > 0) &&
3397 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3398 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3399 /* EOF ASN1 file, not an error */
3400 ERR_clear_error();
3401 retval = 0;
3402 } else if ((filetype == SSL_FILETYPE_PEM) &&
3403 (loaded > 0) &&
3404 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3405 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3406 /* EOF PEM file, not an error */
3407 ERR_clear_error();
3408 retval = 0;
3409 } else {
3410 _setSSLError(NULL, 0, __FILE__, __LINE__);
3411 retval = -1;
3412 }
3413
3414 BIO_free(biobuf);
3415 return retval;
3416}
3417
3418
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003419/*[clinic input]
3420_ssl._SSLContext.load_verify_locations
3421 cafile: object = NULL
3422 capath: object = NULL
3423 cadata: object = NULL
3424
3425[clinic start generated code]*/
3426
Antoine Pitrou152efa22010-05-16 18:19:27 +00003427static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003428_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3429 PyObject *cafile,
3430 PyObject *capath,
3431 PyObject *cadata)
3432/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003433{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003434 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3435 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003436 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003437
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003438 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003439 if (cafile == Py_None)
3440 cafile = NULL;
3441 if (capath == Py_None)
3442 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003443 if (cadata == Py_None)
3444 cadata = NULL;
3445
3446 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003447 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003448 "cafile, capath and cadata cannot be all omitted");
3449 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003450 }
3451 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3452 PyErr_SetString(PyExc_TypeError,
3453 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003454 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003455 }
3456 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003457 PyErr_SetString(PyExc_TypeError,
3458 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003459 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003460 }
Christian Heimesefff7062013-11-21 03:35:02 +01003461
3462 /* validata cadata type and load cadata */
3463 if (cadata) {
3464 Py_buffer buf;
3465 PyObject *cadata_ascii = NULL;
3466
3467 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3468 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3469 PyBuffer_Release(&buf);
3470 PyErr_SetString(PyExc_TypeError,
3471 "cadata should be a contiguous buffer with "
3472 "a single dimension");
3473 goto error;
3474 }
3475 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3476 PyBuffer_Release(&buf);
3477 if (r == -1) {
3478 goto error;
3479 }
3480 } else {
3481 PyErr_Clear();
3482 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3483 if (cadata_ascii == NULL) {
3484 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003485 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003486 "bytes-like object");
3487 goto error;
3488 }
3489 r = _add_ca_certs(self,
3490 PyBytes_AS_STRING(cadata_ascii),
3491 PyBytes_GET_SIZE(cadata_ascii),
3492 SSL_FILETYPE_PEM);
3493 Py_DECREF(cadata_ascii);
3494 if (r == -1) {
3495 goto error;
3496 }
3497 }
3498 }
3499
3500 /* load cafile or capath */
3501 if (cafile || capath) {
3502 if (cafile)
3503 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3504 if (capath)
3505 capath_buf = PyBytes_AS_STRING(capath_bytes);
3506 PySSL_BEGIN_ALLOW_THREADS
3507 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3508 PySSL_END_ALLOW_THREADS
3509 if (r != 1) {
3510 ok = 0;
3511 if (errno != 0) {
3512 ERR_clear_error();
3513 PyErr_SetFromErrno(PyExc_IOError);
3514 }
3515 else {
3516 _setSSLError(NULL, 0, __FILE__, __LINE__);
3517 }
3518 goto error;
3519 }
3520 }
3521 goto end;
3522
3523 error:
3524 ok = 0;
3525 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003526 Py_XDECREF(cafile_bytes);
3527 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003528 if (ok) {
3529 Py_RETURN_NONE;
3530 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003531 return NULL;
3532 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003533}
3534
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003535/*[clinic input]
3536_ssl._SSLContext.load_dh_params
3537 path as filepath: object
3538 /
3539
3540[clinic start generated code]*/
3541
Antoine Pitrou152efa22010-05-16 18:19:27 +00003542static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003543_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3544/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003545{
3546 FILE *f;
3547 DH *dh;
3548
Victor Stinnerdaf45552013-08-28 00:53:59 +02003549 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003550 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003551 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003552
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003553 errno = 0;
3554 PySSL_BEGIN_ALLOW_THREADS
3555 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003556 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003557 PySSL_END_ALLOW_THREADS
3558 if (dh == NULL) {
3559 if (errno != 0) {
3560 ERR_clear_error();
3561 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3562 }
3563 else {
3564 _setSSLError(NULL, 0, __FILE__, __LINE__);
3565 }
3566 return NULL;
3567 }
3568 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3569 _setSSLError(NULL, 0, __FILE__, __LINE__);
3570 DH_free(dh);
3571 Py_RETURN_NONE;
3572}
3573
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003574/*[clinic input]
3575_ssl._SSLContext._wrap_socket
3576 sock: object(subclass_of="PySocketModule.Sock_Type")
3577 server_side: int
3578 server_hostname as hostname_obj: object = None
3579
3580[clinic start generated code]*/
3581
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003582static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003583_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3584 int server_side, PyObject *hostname_obj)
3585/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003586{
Antoine Pitroud5323212010-10-22 18:19:07 +00003587 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003588 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003589
Antoine Pitroud5323212010-10-22 18:19:07 +00003590 /* server_hostname is either None (or absent), or to be encoded
3591 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003592 if (hostname_obj != Py_None) {
3593 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003594 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003595 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003596
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003597 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3598 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003599 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003600 if (hostname != NULL)
3601 PyMem_Free(hostname);
3602 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003603}
3604
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003605/*[clinic input]
3606_ssl._SSLContext._wrap_bio
3607 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3608 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3609 server_side: int
3610 server_hostname as hostname_obj: object = None
3611
3612[clinic start generated code]*/
3613
Antoine Pitroub0182c82010-10-12 20:09:02 +00003614static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003615_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3616 PySSLMemoryBIO *outgoing, int server_side,
3617 PyObject *hostname_obj)
3618/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003619{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003620 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003621 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003622
3623 /* server_hostname is either None (or absent), or to be encoded
3624 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003625 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003626 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3627 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003628 }
3629
3630 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3631 incoming, outgoing);
3632
3633 PyMem_Free(hostname);
3634 return res;
3635}
3636
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003637/*[clinic input]
3638_ssl._SSLContext.session_stats
3639[clinic start generated code]*/
3640
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003641static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003642_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3643/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003644{
3645 int r;
3646 PyObject *value, *stats = PyDict_New();
3647 if (!stats)
3648 return NULL;
3649
3650#define ADD_STATS(SSL_NAME, KEY_NAME) \
3651 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3652 if (value == NULL) \
3653 goto error; \
3654 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3655 Py_DECREF(value); \
3656 if (r < 0) \
3657 goto error;
3658
3659 ADD_STATS(number, "number");
3660 ADD_STATS(connect, "connect");
3661 ADD_STATS(connect_good, "connect_good");
3662 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3663 ADD_STATS(accept, "accept");
3664 ADD_STATS(accept_good, "accept_good");
3665 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3666 ADD_STATS(accept, "accept");
3667 ADD_STATS(hits, "hits");
3668 ADD_STATS(misses, "misses");
3669 ADD_STATS(timeouts, "timeouts");
3670 ADD_STATS(cache_full, "cache_full");
3671
3672#undef ADD_STATS
3673
3674 return stats;
3675
3676error:
3677 Py_DECREF(stats);
3678 return NULL;
3679}
3680
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003681/*[clinic input]
3682_ssl._SSLContext.set_default_verify_paths
3683[clinic start generated code]*/
3684
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003685static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003686_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3687/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003688{
3689 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3690 _setSSLError(NULL, 0, __FILE__, __LINE__);
3691 return NULL;
3692 }
3693 Py_RETURN_NONE;
3694}
3695
Antoine Pitrou501da612011-12-21 09:27:41 +01003696#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003697/*[clinic input]
3698_ssl._SSLContext.set_ecdh_curve
3699 name: object
3700 /
3701
3702[clinic start generated code]*/
3703
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003704static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003705_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3706/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003707{
3708 PyObject *name_bytes;
3709 int nid;
3710 EC_KEY *key;
3711
3712 if (!PyUnicode_FSConverter(name, &name_bytes))
3713 return NULL;
3714 assert(PyBytes_Check(name_bytes));
3715 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3716 Py_DECREF(name_bytes);
3717 if (nid == 0) {
3718 PyErr_Format(PyExc_ValueError,
3719 "unknown elliptic curve name %R", name);
3720 return NULL;
3721 }
3722 key = EC_KEY_new_by_curve_name(nid);
3723 if (key == NULL) {
3724 _setSSLError(NULL, 0, __FILE__, __LINE__);
3725 return NULL;
3726 }
3727 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3728 EC_KEY_free(key);
3729 Py_RETURN_NONE;
3730}
Antoine Pitrou501da612011-12-21 09:27:41 +01003731#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003732
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003733#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003734static int
3735_servername_callback(SSL *s, int *al, void *args)
3736{
3737 int ret;
3738 PySSLContext *ssl_ctx = (PySSLContext *) args;
3739 PySSLSocket *ssl;
3740 PyObject *servername_o;
3741 PyObject *servername_idna;
3742 PyObject *result;
3743 /* The high-level ssl.SSLSocket object */
3744 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003745 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003746#ifdef WITH_THREAD
3747 PyGILState_STATE gstate = PyGILState_Ensure();
3748#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003749
3750 if (ssl_ctx->set_hostname == NULL) {
3751 /* remove race condition in this the call back while if removing the
3752 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003753#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003754 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003755#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003756 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003757 }
3758
3759 ssl = SSL_get_app_data(s);
3760 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003761
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003762 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003763 * SSL connection and that has a .context attribute that can be changed to
3764 * identify the requested hostname. Since the official API is the Python
3765 * level API we want to pass the callback a Python level object rather than
3766 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3767 * SSLObject) that will be passed. Otherwise if there's a socket then that
3768 * will be passed. If both do not exist only then the C-level object is
3769 * passed. */
3770 if (ssl->owner)
3771 ssl_socket = PyWeakref_GetObject(ssl->owner);
3772 else if (ssl->Socket)
3773 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3774 else
3775 ssl_socket = (PyObject *) ssl;
3776
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003777 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003778 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003779 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003780
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003781 if (servername == NULL) {
3782 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3783 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003784 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003785 else {
3786 servername_o = PyBytes_FromString(servername);
3787 if (servername_o == NULL) {
3788 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3789 goto error;
3790 }
3791 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3792 if (servername_idna == NULL) {
3793 PyErr_WriteUnraisable(servername_o);
3794 Py_DECREF(servername_o);
3795 goto error;
3796 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003797 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003798 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3799 servername_idna, ssl_ctx, NULL);
3800 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003801 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003802 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003803
3804 if (result == NULL) {
3805 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3806 *al = SSL_AD_HANDSHAKE_FAILURE;
3807 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3808 }
3809 else {
3810 if (result != Py_None) {
3811 *al = (int) PyLong_AsLong(result);
3812 if (PyErr_Occurred()) {
3813 PyErr_WriteUnraisable(result);
3814 *al = SSL_AD_INTERNAL_ERROR;
3815 }
3816 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3817 }
3818 else {
3819 ret = SSL_TLSEXT_ERR_OK;
3820 }
3821 Py_DECREF(result);
3822 }
3823
Stefan Krah20d60802013-01-17 17:07:17 +01003824#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003825 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003826#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003827 return ret;
3828
3829error:
3830 Py_DECREF(ssl_socket);
3831 *al = SSL_AD_INTERNAL_ERROR;
3832 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003833#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003834 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003835#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003836 return ret;
3837}
Antoine Pitroua5963382013-03-30 16:39:00 +01003838#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003839
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003840/*[clinic input]
3841_ssl._SSLContext.set_servername_callback
3842 method as cb: object
3843 /
3844
3845Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3846
3847If the argument is None then the callback is disabled. The method is called
3848with the SSLSocket, the server name as a string, and the SSLContext object.
3849See RFC 6066 for details of the SNI extension.
3850[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003851
3852static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003853_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3854/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003855{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003856#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003857 Py_CLEAR(self->set_hostname);
3858 if (cb == Py_None) {
3859 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3860 }
3861 else {
3862 if (!PyCallable_Check(cb)) {
3863 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3864 PyErr_SetString(PyExc_TypeError,
3865 "not a callable object");
3866 return NULL;
3867 }
3868 Py_INCREF(cb);
3869 self->set_hostname = cb;
3870 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3871 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3872 }
3873 Py_RETURN_NONE;
3874#else
3875 PyErr_SetString(PyExc_NotImplementedError,
3876 "The TLS extension servername callback, "
3877 "SSL_CTX_set_tlsext_servername_callback, "
3878 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003879 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003880#endif
3881}
3882
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003883/*[clinic input]
3884_ssl._SSLContext.cert_store_stats
3885
3886Returns quantities of loaded X.509 certificates.
3887
3888X.509 certificates with a CA extension and certificate revocation lists
3889inside the context's cert store.
3890
3891NOTE: Certificates in a capath directory aren't loaded unless they have
3892been used at least once.
3893[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003894
3895static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003896_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3897/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003898{
3899 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003900 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003901 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003902 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003903
3904 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003905 objs = X509_STORE_get0_objects(store);
3906 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3907 obj = sk_X509_OBJECT_value(objs, i);
3908 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003909 case X509_LU_X509:
3910 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003911 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003912 ca++;
3913 }
3914 break;
3915 case X509_LU_CRL:
3916 crl++;
3917 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003918 default:
3919 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3920 * As far as I can tell they are internal states and never
3921 * stored in a cert store */
3922 break;
3923 }
3924 }
3925 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3926 "x509_ca", ca);
3927}
3928
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003929/*[clinic input]
3930_ssl._SSLContext.get_ca_certs
3931 binary_form: bool = False
3932
3933Returns a list of dicts with information of loaded CA certs.
3934
3935If the optional argument is True, returns a DER-encoded copy of the CA
3936certificate.
3937
3938NOTE: Certificates in a capath directory aren't loaded unless they have
3939been used at least once.
3940[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003941
3942static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003943_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3944/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003945{
3946 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003947 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003948 PyObject *ci = NULL, *rlist = NULL;
3949 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003950
3951 if ((rlist = PyList_New(0)) == NULL) {
3952 return NULL;
3953 }
3954
3955 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003956 objs = X509_STORE_get0_objects(store);
3957 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003958 X509_OBJECT *obj;
3959 X509 *cert;
3960
Christian Heimes598894f2016-09-05 23:19:05 +02003961 obj = sk_X509_OBJECT_value(objs, i);
3962 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003963 /* not a x509 cert */
3964 continue;
3965 }
3966 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003967 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003968 if (!X509_check_ca(cert)) {
3969 continue;
3970 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003971 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003972 ci = _certificate_to_der(cert);
3973 } else {
3974 ci = _decode_certificate(cert);
3975 }
3976 if (ci == NULL) {
3977 goto error;
3978 }
3979 if (PyList_Append(rlist, ci) == -1) {
3980 goto error;
3981 }
3982 Py_CLEAR(ci);
3983 }
3984 return rlist;
3985
3986 error:
3987 Py_XDECREF(ci);
3988 Py_XDECREF(rlist);
3989 return NULL;
3990}
3991
3992
Antoine Pitrou152efa22010-05-16 18:19:27 +00003993static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003994 {"check_hostname", (getter) get_check_hostname,
3995 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003996 {"options", (getter) get_options,
3997 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003998 {"verify_flags", (getter) get_verify_flags,
3999 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004000 {"verify_mode", (getter) get_verify_mode,
4001 (setter) set_verify_mode, NULL},
4002 {NULL}, /* sentinel */
4003};
4004
4005static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004006 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4007 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4008 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4009 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4010 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4011 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4012 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4013 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4014 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4015 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4016 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4017 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4018 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4019 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004020 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004021 {NULL, NULL} /* sentinel */
4022};
4023
4024static PyTypeObject PySSLContext_Type = {
4025 PyVarObject_HEAD_INIT(NULL, 0)
4026 "_ssl._SSLContext", /*tp_name*/
4027 sizeof(PySSLContext), /*tp_basicsize*/
4028 0, /*tp_itemsize*/
4029 (destructor)context_dealloc, /*tp_dealloc*/
4030 0, /*tp_print*/
4031 0, /*tp_getattr*/
4032 0, /*tp_setattr*/
4033 0, /*tp_reserved*/
4034 0, /*tp_repr*/
4035 0, /*tp_as_number*/
4036 0, /*tp_as_sequence*/
4037 0, /*tp_as_mapping*/
4038 0, /*tp_hash*/
4039 0, /*tp_call*/
4040 0, /*tp_str*/
4041 0, /*tp_getattro*/
4042 0, /*tp_setattro*/
4043 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004044 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004045 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004046 (traverseproc) context_traverse, /*tp_traverse*/
4047 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004048 0, /*tp_richcompare*/
4049 0, /*tp_weaklistoffset*/
4050 0, /*tp_iter*/
4051 0, /*tp_iternext*/
4052 context_methods, /*tp_methods*/
4053 0, /*tp_members*/
4054 context_getsetlist, /*tp_getset*/
4055 0, /*tp_base*/
4056 0, /*tp_dict*/
4057 0, /*tp_descr_get*/
4058 0, /*tp_descr_set*/
4059 0, /*tp_dictoffset*/
4060 0, /*tp_init*/
4061 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004062 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004063};
4064
4065
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004066/*
4067 * MemoryBIO objects
4068 */
4069
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004070/*[clinic input]
4071@classmethod
4072_ssl.MemoryBIO.__new__
4073
4074[clinic start generated code]*/
4075
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004076static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004077_ssl_MemoryBIO_impl(PyTypeObject *type)
4078/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004079{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004080 BIO *bio;
4081 PySSLMemoryBIO *self;
4082
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004083 bio = BIO_new(BIO_s_mem());
4084 if (bio == NULL) {
4085 PyErr_SetString(PySSLErrorObject,
4086 "failed to allocate BIO");
4087 return NULL;
4088 }
4089 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4090 * just that no data is currently available. The SSL routines should retry
4091 * the read, which we can achieve by calling BIO_set_retry_read(). */
4092 BIO_set_retry_read(bio);
4093 BIO_set_mem_eof_return(bio, -1);
4094
4095 assert(type != NULL && type->tp_alloc != NULL);
4096 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4097 if (self == NULL) {
4098 BIO_free(bio);
4099 return NULL;
4100 }
4101 self->bio = bio;
4102 self->eof_written = 0;
4103
4104 return (PyObject *) self;
4105}
4106
4107static void
4108memory_bio_dealloc(PySSLMemoryBIO *self)
4109{
4110 BIO_free(self->bio);
4111 Py_TYPE(self)->tp_free(self);
4112}
4113
4114static PyObject *
4115memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4116{
4117 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
4118}
4119
4120PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4121"The number of bytes pending in the memory BIO.");
4122
4123static PyObject *
4124memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4125{
4126 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4127 && self->eof_written);
4128}
4129
4130PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4131"Whether the memory BIO is at EOF.");
4132
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004133/*[clinic input]
4134_ssl.MemoryBIO.read
4135 size as len: int = -1
4136 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004137
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004138Read up to size bytes from the memory BIO.
4139
4140If size is not specified, read the entire buffer.
4141If the return value is an empty bytes instance, this means either
4142EOF or that no data is available. Use the "eof" property to
4143distinguish between the two.
4144[clinic start generated code]*/
4145
4146static PyObject *
4147_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4148/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4149{
4150 int avail, nbytes;
4151 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004152
4153 avail = BIO_ctrl_pending(self->bio);
4154 if ((len < 0) || (len > avail))
4155 len = avail;
4156
4157 result = PyBytes_FromStringAndSize(NULL, len);
4158 if ((result == NULL) || (len == 0))
4159 return result;
4160
4161 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4162 /* There should never be any short reads but check anyway. */
4163 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4164 Py_DECREF(result);
4165 return NULL;
4166 }
4167
4168 return result;
4169}
4170
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004171/*[clinic input]
4172_ssl.MemoryBIO.write
4173 b: Py_buffer
4174 /
4175
4176Writes the bytes b into the memory BIO.
4177
4178Returns the number of bytes written.
4179[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004180
4181static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004182_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4183/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004184{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004185 int nbytes;
4186
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004187 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004188 PyErr_Format(PyExc_OverflowError,
4189 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004190 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004191 }
4192
4193 if (self->eof_written) {
4194 PyErr_SetString(PySSLErrorObject,
4195 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004196 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004197 }
4198
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004199 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004200 if (nbytes < 0) {
4201 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004202 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004203 }
4204
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004205 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004206}
4207
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004208/*[clinic input]
4209_ssl.MemoryBIO.write_eof
4210
4211Write an EOF marker to the memory BIO.
4212
4213When all data has been read, the "eof" property will be True.
4214[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004215
4216static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004217_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4218/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004219{
4220 self->eof_written = 1;
4221 /* After an EOF is written, a zero return from read() should be a real EOF
4222 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4223 BIO_clear_retry_flags(self->bio);
4224 BIO_set_mem_eof_return(self->bio, 0);
4225
4226 Py_RETURN_NONE;
4227}
4228
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004229static PyGetSetDef memory_bio_getsetlist[] = {
4230 {"pending", (getter) memory_bio_get_pending, NULL,
4231 PySSL_memory_bio_pending_doc},
4232 {"eof", (getter) memory_bio_get_eof, NULL,
4233 PySSL_memory_bio_eof_doc},
4234 {NULL}, /* sentinel */
4235};
4236
4237static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004238 _SSL_MEMORYBIO_READ_METHODDEF
4239 _SSL_MEMORYBIO_WRITE_METHODDEF
4240 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004241 {NULL, NULL} /* sentinel */
4242};
4243
4244static PyTypeObject PySSLMemoryBIO_Type = {
4245 PyVarObject_HEAD_INIT(NULL, 0)
4246 "_ssl.MemoryBIO", /*tp_name*/
4247 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4248 0, /*tp_itemsize*/
4249 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4250 0, /*tp_print*/
4251 0, /*tp_getattr*/
4252 0, /*tp_setattr*/
4253 0, /*tp_reserved*/
4254 0, /*tp_repr*/
4255 0, /*tp_as_number*/
4256 0, /*tp_as_sequence*/
4257 0, /*tp_as_mapping*/
4258 0, /*tp_hash*/
4259 0, /*tp_call*/
4260 0, /*tp_str*/
4261 0, /*tp_getattro*/
4262 0, /*tp_setattro*/
4263 0, /*tp_as_buffer*/
4264 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4265 0, /*tp_doc*/
4266 0, /*tp_traverse*/
4267 0, /*tp_clear*/
4268 0, /*tp_richcompare*/
4269 0, /*tp_weaklistoffset*/
4270 0, /*tp_iter*/
4271 0, /*tp_iternext*/
4272 memory_bio_methods, /*tp_methods*/
4273 0, /*tp_members*/
4274 memory_bio_getsetlist, /*tp_getset*/
4275 0, /*tp_base*/
4276 0, /*tp_dict*/
4277 0, /*tp_descr_get*/
4278 0, /*tp_descr_set*/
4279 0, /*tp_dictoffset*/
4280 0, /*tp_init*/
4281 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004282 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004283};
4284
Antoine Pitrou152efa22010-05-16 18:19:27 +00004285
Christian Heimes99a65702016-09-10 23:44:53 +02004286/*
4287 * SSL Session object
4288 */
4289
4290static void
4291PySSLSession_dealloc(PySSLSession *self)
4292{
Christian Heimesa5d07652016-09-24 10:48:05 +02004293 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004294 Py_XDECREF(self->ctx);
4295 if (self->session != NULL) {
4296 SSL_SESSION_free(self->session);
4297 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004298 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004299}
4300
4301static PyObject *
4302PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4303{
4304 int result;
4305
4306 if (left == NULL || right == NULL) {
4307 PyErr_BadInternalCall();
4308 return NULL;
4309 }
4310
4311 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4312 Py_RETURN_NOTIMPLEMENTED;
4313 }
4314
4315 if (left == right) {
4316 result = 0;
4317 } else {
4318 const unsigned char *left_id, *right_id;
4319 unsigned int left_len, right_len;
4320 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4321 &left_len);
4322 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4323 &right_len);
4324 if (left_len == right_len) {
4325 result = memcmp(left_id, right_id, left_len);
4326 } else {
4327 result = 1;
4328 }
4329 }
4330
4331 switch (op) {
4332 case Py_EQ:
4333 if (result == 0) {
4334 Py_RETURN_TRUE;
4335 } else {
4336 Py_RETURN_FALSE;
4337 }
4338 break;
4339 case Py_NE:
4340 if (result != 0) {
4341 Py_RETURN_TRUE;
4342 } else {
4343 Py_RETURN_FALSE;
4344 }
4345 break;
4346 case Py_LT:
4347 case Py_LE:
4348 case Py_GT:
4349 case Py_GE:
4350 Py_RETURN_NOTIMPLEMENTED;
4351 break;
4352 default:
4353 PyErr_BadArgument();
4354 return NULL;
4355 }
4356}
4357
4358static int
4359PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4360{
4361 Py_VISIT(self->ctx);
4362 return 0;
4363}
4364
4365static int
4366PySSLSession_clear(PySSLSession *self)
4367{
4368 Py_CLEAR(self->ctx);
4369 return 0;
4370}
4371
4372
4373static PyObject *
4374PySSLSession_get_time(PySSLSession *self, void *closure) {
4375 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4376}
4377
4378PyDoc_STRVAR(PySSLSession_get_time_doc,
4379"Session creation time (seconds since epoch).");
4380
4381
4382static PyObject *
4383PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4384 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4385}
4386
4387PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4388"Session timeout (delta in seconds).");
4389
4390
4391static PyObject *
4392PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4393 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4394 return PyLong_FromUnsignedLong(hint);
4395}
4396
4397PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4398"Ticket life time hint.");
4399
4400
4401static PyObject *
4402PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4403 const unsigned char *id;
4404 unsigned int len;
4405 id = SSL_SESSION_get_id(self->session, &len);
4406 return PyBytes_FromStringAndSize((const char *)id, len);
4407}
4408
4409PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4410"Session id");
4411
4412
4413static PyObject *
4414PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4415 if (SSL_SESSION_has_ticket(self->session)) {
4416 Py_RETURN_TRUE;
4417 } else {
4418 Py_RETURN_FALSE;
4419 }
4420}
4421
4422PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4423"Does the session contain a ticket?");
4424
4425
4426static PyGetSetDef PySSLSession_getsetlist[] = {
4427 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4428 PySSLSession_get_has_ticket_doc},
4429 {"id", (getter) PySSLSession_get_session_id, NULL,
4430 PySSLSession_get_session_id_doc},
4431 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4432 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4433 {"time", (getter) PySSLSession_get_time, NULL,
4434 PySSLSession_get_time_doc},
4435 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4436 PySSLSession_get_timeout_doc},
4437 {NULL}, /* sentinel */
4438};
4439
4440static PyTypeObject PySSLSession_Type = {
4441 PyVarObject_HEAD_INIT(NULL, 0)
4442 "_ssl.Session", /*tp_name*/
4443 sizeof(PySSLSession), /*tp_basicsize*/
4444 0, /*tp_itemsize*/
4445 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4446 0, /*tp_print*/
4447 0, /*tp_getattr*/
4448 0, /*tp_setattr*/
4449 0, /*tp_reserved*/
4450 0, /*tp_repr*/
4451 0, /*tp_as_number*/
4452 0, /*tp_as_sequence*/
4453 0, /*tp_as_mapping*/
4454 0, /*tp_hash*/
4455 0, /*tp_call*/
4456 0, /*tp_str*/
4457 0, /*tp_getattro*/
4458 0, /*tp_setattro*/
4459 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004460 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004461 0, /*tp_doc*/
4462 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4463 (inquiry)PySSLSession_clear, /*tp_clear*/
4464 PySSLSession_richcompare, /*tp_richcompare*/
4465 0, /*tp_weaklistoffset*/
4466 0, /*tp_iter*/
4467 0, /*tp_iternext*/
4468 0, /*tp_methods*/
4469 0, /*tp_members*/
4470 PySSLSession_getsetlist, /*tp_getset*/
4471};
4472
4473
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004474/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004475/*[clinic input]
4476_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004477 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004478 entropy: double
4479 /
4480
4481Mix string into the OpenSSL PRNG state.
4482
4483entropy (a float) is a lower bound on the entropy contained in
4484string. See RFC 1750.
4485[clinic start generated code]*/
4486
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004487static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004488_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
4489/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004490{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004491 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004492 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004493
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004494 buf = (const char *)view->buf;
4495 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004496 do {
4497 written = Py_MIN(len, INT_MAX);
4498 RAND_add(buf, (int)written, entropy);
4499 buf += written;
4500 len -= written;
4501 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004502 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004503}
4504
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004505static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004506PySSL_RAND(int len, int pseudo)
4507{
4508 int ok;
4509 PyObject *bytes;
4510 unsigned long err;
4511 const char *errstr;
4512 PyObject *v;
4513
Victor Stinner1e81a392013-12-19 16:47:04 +01004514 if (len < 0) {
4515 PyErr_SetString(PyExc_ValueError, "num must be positive");
4516 return NULL;
4517 }
4518
Victor Stinner99c8b162011-05-24 12:05:19 +02004519 bytes = PyBytes_FromStringAndSize(NULL, len);
4520 if (bytes == NULL)
4521 return NULL;
4522 if (pseudo) {
4523 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4524 if (ok == 0 || ok == 1)
4525 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4526 }
4527 else {
4528 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4529 if (ok == 1)
4530 return bytes;
4531 }
4532 Py_DECREF(bytes);
4533
4534 err = ERR_get_error();
4535 errstr = ERR_reason_error_string(err);
4536 v = Py_BuildValue("(ks)", err, errstr);
4537 if (v != NULL) {
4538 PyErr_SetObject(PySSLErrorObject, v);
4539 Py_DECREF(v);
4540 }
4541 return NULL;
4542}
4543
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004544/*[clinic input]
4545_ssl.RAND_bytes
4546 n: int
4547 /
4548
4549Generate n cryptographically strong pseudo-random bytes.
4550[clinic start generated code]*/
4551
Victor Stinner99c8b162011-05-24 12:05:19 +02004552static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004553_ssl_RAND_bytes_impl(PyObject *module, int n)
4554/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004555{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004556 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004557}
4558
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004559/*[clinic input]
4560_ssl.RAND_pseudo_bytes
4561 n: int
4562 /
4563
4564Generate n pseudo-random bytes.
4565
4566Return a pair (bytes, is_cryptographic). is_cryptographic is True
4567if the bytes generated are cryptographically strong.
4568[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004569
4570static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004571_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4572/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004573{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004574 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004575}
4576
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004577/*[clinic input]
4578_ssl.RAND_status
4579
4580Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4581
4582It is necessary to seed the PRNG with RAND_add() on some platforms before
4583using the ssl() function.
4584[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004585
4586static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004587_ssl_RAND_status_impl(PyObject *module)
4588/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004589{
Christian Heimes217cfd12007-12-02 14:31:20 +00004590 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004591}
4592
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004593#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004594/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004595/*[clinic input]
4596_ssl.RAND_egd
4597 path: object(converter="PyUnicode_FSConverter")
4598 /
4599
4600Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4601
4602Returns number of bytes read. Raises SSLError if connection to EGD
4603fails or if it does not provide enough data to seed PRNG.
4604[clinic start generated code]*/
4605
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004606static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004607_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4608/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004609{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004610 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004611 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004612 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004613 PyErr_SetString(PySSLErrorObject,
4614 "EGD connection failed or EGD did not return "
4615 "enough data to seed the PRNG");
4616 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004617 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004618 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004619}
Christian Heimesa5d07652016-09-24 10:48:05 +02004620/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004621#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004622
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004623
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004624
4625/*[clinic input]
4626_ssl.get_default_verify_paths
4627
4628Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4629
4630The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4631[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004632
4633static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004634_ssl_get_default_verify_paths_impl(PyObject *module)
4635/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004636{
4637 PyObject *ofile_env = NULL;
4638 PyObject *ofile = NULL;
4639 PyObject *odir_env = NULL;
4640 PyObject *odir = NULL;
4641
Benjamin Petersond113c962015-07-18 10:59:13 -07004642#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004643 const char *tmp = (info); \
4644 target = NULL; \
4645 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4646 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4647 target = PyBytes_FromString(tmp); } \
4648 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004649 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004650
Benjamin Petersond113c962015-07-18 10:59:13 -07004651 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4652 CONVERT(X509_get_default_cert_file(), ofile);
4653 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4654 CONVERT(X509_get_default_cert_dir(), odir);
4655#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004656
Christian Heimes200bb1b2013-06-14 15:14:29 +02004657 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004658
4659 error:
4660 Py_XDECREF(ofile_env);
4661 Py_XDECREF(ofile);
4662 Py_XDECREF(odir_env);
4663 Py_XDECREF(odir);
4664 return NULL;
4665}
4666
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004667static PyObject*
4668asn1obj2py(ASN1_OBJECT *obj)
4669{
4670 int nid;
4671 const char *ln, *sn;
4672 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004673 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004674
4675 nid = OBJ_obj2nid(obj);
4676 if (nid == NID_undef) {
4677 PyErr_Format(PyExc_ValueError, "Unknown object");
4678 return NULL;
4679 }
4680 sn = OBJ_nid2sn(nid);
4681 ln = OBJ_nid2ln(nid);
4682 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4683 if (buflen < 0) {
4684 _setSSLError(NULL, 0, __FILE__, __LINE__);
4685 return NULL;
4686 }
4687 if (buflen) {
4688 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4689 } else {
4690 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4691 }
4692}
4693
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004694/*[clinic input]
4695_ssl.txt2obj
4696 txt: str
4697 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004698
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004699Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4700
4701By default objects are looked up by OID. With name=True short and
4702long name are also matched.
4703[clinic start generated code]*/
4704
4705static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004706_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4707/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004708{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004709 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004710 ASN1_OBJECT *obj;
4711
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004712 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4713 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004714 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004715 return NULL;
4716 }
4717 result = asn1obj2py(obj);
4718 ASN1_OBJECT_free(obj);
4719 return result;
4720}
4721
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004722/*[clinic input]
4723_ssl.nid2obj
4724 nid: int
4725 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004726
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004727Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4728[clinic start generated code]*/
4729
4730static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004731_ssl_nid2obj_impl(PyObject *module, int nid)
4732/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004733{
4734 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004735 ASN1_OBJECT *obj;
4736
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004737 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004738 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004739 return NULL;
4740 }
4741 obj = OBJ_nid2obj(nid);
4742 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004743 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004744 return NULL;
4745 }
4746 result = asn1obj2py(obj);
4747 ASN1_OBJECT_free(obj);
4748 return result;
4749}
4750
Christian Heimes46bebee2013-06-09 19:03:31 +02004751#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004752
4753static PyObject*
4754certEncodingType(DWORD encodingType)
4755{
4756 static PyObject *x509_asn = NULL;
4757 static PyObject *pkcs_7_asn = NULL;
4758
4759 if (x509_asn == NULL) {
4760 x509_asn = PyUnicode_InternFromString("x509_asn");
4761 if (x509_asn == NULL)
4762 return NULL;
4763 }
4764 if (pkcs_7_asn == NULL) {
4765 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4766 if (pkcs_7_asn == NULL)
4767 return NULL;
4768 }
4769 switch(encodingType) {
4770 case X509_ASN_ENCODING:
4771 Py_INCREF(x509_asn);
4772 return x509_asn;
4773 case PKCS_7_ASN_ENCODING:
4774 Py_INCREF(pkcs_7_asn);
4775 return pkcs_7_asn;
4776 default:
4777 return PyLong_FromLong(encodingType);
4778 }
4779}
4780
4781static PyObject*
4782parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4783{
4784 CERT_ENHKEY_USAGE *usage;
4785 DWORD size, error, i;
4786 PyObject *retval;
4787
4788 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4789 error = GetLastError();
4790 if (error == CRYPT_E_NOT_FOUND) {
4791 Py_RETURN_TRUE;
4792 }
4793 return PyErr_SetFromWindowsErr(error);
4794 }
4795
4796 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4797 if (usage == NULL) {
4798 return PyErr_NoMemory();
4799 }
4800
4801 /* Now get the actual enhanced usage property */
4802 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4803 PyMem_Free(usage);
4804 error = GetLastError();
4805 if (error == CRYPT_E_NOT_FOUND) {
4806 Py_RETURN_TRUE;
4807 }
4808 return PyErr_SetFromWindowsErr(error);
4809 }
4810 retval = PySet_New(NULL);
4811 if (retval == NULL) {
4812 goto error;
4813 }
4814 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4815 if (usage->rgpszUsageIdentifier[i]) {
4816 PyObject *oid;
4817 int err;
4818 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4819 if (oid == NULL) {
4820 Py_CLEAR(retval);
4821 goto error;
4822 }
4823 err = PySet_Add(retval, oid);
4824 Py_DECREF(oid);
4825 if (err == -1) {
4826 Py_CLEAR(retval);
4827 goto error;
4828 }
4829 }
4830 }
4831 error:
4832 PyMem_Free(usage);
4833 return retval;
4834}
4835
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004836/*[clinic input]
4837_ssl.enum_certificates
4838 store_name: str
4839
4840Retrieve certificates from Windows' cert store.
4841
4842store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4843more cert storages, too. The function returns a list of (bytes,
4844encoding_type, trust) tuples. The encoding_type flag can be interpreted
4845with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4846a set of OIDs or the boolean True.
4847[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004848
Christian Heimes46bebee2013-06-09 19:03:31 +02004849static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004850_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4851/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004852{
Christian Heimes46bebee2013-06-09 19:03:31 +02004853 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004854 PCCERT_CONTEXT pCertCtx = NULL;
4855 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004856 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004857
Christian Heimes44109d72013-11-22 01:51:30 +01004858 result = PyList_New(0);
4859 if (result == NULL) {
4860 return NULL;
4861 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004862 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4863 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4864 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004865 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004866 Py_DECREF(result);
4867 return PyErr_SetFromWindowsErr(GetLastError());
4868 }
4869
Christian Heimes44109d72013-11-22 01:51:30 +01004870 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4871 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4872 pCertCtx->cbCertEncoded);
4873 if (!cert) {
4874 Py_CLEAR(result);
4875 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004876 }
Christian Heimes44109d72013-11-22 01:51:30 +01004877 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4878 Py_CLEAR(result);
4879 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004880 }
Christian Heimes44109d72013-11-22 01:51:30 +01004881 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4882 if (keyusage == Py_True) {
4883 Py_DECREF(keyusage);
4884 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004885 }
Christian Heimes44109d72013-11-22 01:51:30 +01004886 if (keyusage == NULL) {
4887 Py_CLEAR(result);
4888 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004889 }
Christian Heimes44109d72013-11-22 01:51:30 +01004890 if ((tup = PyTuple_New(3)) == NULL) {
4891 Py_CLEAR(result);
4892 break;
4893 }
4894 PyTuple_SET_ITEM(tup, 0, cert);
4895 cert = NULL;
4896 PyTuple_SET_ITEM(tup, 1, enc);
4897 enc = NULL;
4898 PyTuple_SET_ITEM(tup, 2, keyusage);
4899 keyusage = NULL;
4900 if (PyList_Append(result, tup) < 0) {
4901 Py_CLEAR(result);
4902 break;
4903 }
4904 Py_CLEAR(tup);
4905 }
4906 if (pCertCtx) {
4907 /* loop ended with an error, need to clean up context manually */
4908 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004909 }
4910
4911 /* In error cases cert, enc and tup may not be NULL */
4912 Py_XDECREF(cert);
4913 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004914 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004915 Py_XDECREF(tup);
4916
4917 if (!CertCloseStore(hStore, 0)) {
4918 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004919 Py_XDECREF(result);
4920 return PyErr_SetFromWindowsErr(GetLastError());
4921 }
4922 return result;
4923}
4924
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004925/*[clinic input]
4926_ssl.enum_crls
4927 store_name: str
4928
4929Retrieve CRLs from Windows' cert store.
4930
4931store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4932more cert storages, too. The function returns a list of (bytes,
4933encoding_type) tuples. The encoding_type flag can be interpreted with
4934X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4935[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004936
4937static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004938_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4939/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004940{
Christian Heimes44109d72013-11-22 01:51:30 +01004941 HCERTSTORE hStore = NULL;
4942 PCCRL_CONTEXT pCrlCtx = NULL;
4943 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4944 PyObject *result = NULL;
4945
Christian Heimes44109d72013-11-22 01:51:30 +01004946 result = PyList_New(0);
4947 if (result == NULL) {
4948 return NULL;
4949 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004950 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4951 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4952 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004953 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004954 Py_DECREF(result);
4955 return PyErr_SetFromWindowsErr(GetLastError());
4956 }
Christian Heimes44109d72013-11-22 01:51:30 +01004957
4958 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4959 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4960 pCrlCtx->cbCrlEncoded);
4961 if (!crl) {
4962 Py_CLEAR(result);
4963 break;
4964 }
4965 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4966 Py_CLEAR(result);
4967 break;
4968 }
4969 if ((tup = PyTuple_New(2)) == NULL) {
4970 Py_CLEAR(result);
4971 break;
4972 }
4973 PyTuple_SET_ITEM(tup, 0, crl);
4974 crl = NULL;
4975 PyTuple_SET_ITEM(tup, 1, enc);
4976 enc = NULL;
4977
4978 if (PyList_Append(result, tup) < 0) {
4979 Py_CLEAR(result);
4980 break;
4981 }
4982 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004983 }
Christian Heimes44109d72013-11-22 01:51:30 +01004984 if (pCrlCtx) {
4985 /* loop ended with an error, need to clean up context manually */
4986 CertFreeCRLContext(pCrlCtx);
4987 }
4988
4989 /* In error cases cert, enc and tup may not be NULL */
4990 Py_XDECREF(crl);
4991 Py_XDECREF(enc);
4992 Py_XDECREF(tup);
4993
4994 if (!CertCloseStore(hStore, 0)) {
4995 /* This error case might shadow another exception.*/
4996 Py_XDECREF(result);
4997 return PyErr_SetFromWindowsErr(GetLastError());
4998 }
4999 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005000}
Christian Heimes44109d72013-11-22 01:51:30 +01005001
5002#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005003
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005004/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005005static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005006 _SSL__TEST_DECODE_CERT_METHODDEF
5007 _SSL_RAND_ADD_METHODDEF
5008 _SSL_RAND_BYTES_METHODDEF
5009 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5010 _SSL_RAND_EGD_METHODDEF
5011 _SSL_RAND_STATUS_METHODDEF
5012 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5013 _SSL_ENUM_CERTIFICATES_METHODDEF
5014 _SSL_ENUM_CRLS_METHODDEF
5015 _SSL_TXT2OBJ_METHODDEF
5016 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005017 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005018};
5019
5020
Christian Heimes598894f2016-09-05 23:19:05 +02005021#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005022
5023/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005024 * of the Python C thread library
5025 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5026 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005027
5028static PyThread_type_lock *_ssl_locks = NULL;
5029
Christian Heimes4d98ca92013-08-19 17:36:29 +02005030#if OPENSSL_VERSION_NUMBER >= 0x10000000
5031/* use new CRYPTO_THREADID API. */
5032static void
5033_ssl_threadid_callback(CRYPTO_THREADID *id)
5034{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005035 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005036}
5037#else
5038/* deprecated CRYPTO_set_id_callback() API. */
5039static unsigned long
5040_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005041 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005042}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005043#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005044
Bill Janssen6e027db2007-11-15 22:23:56 +00005045static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005046 (int mode, int n, const char *file, int line) {
5047 /* this function is needed to perform locking on shared data
5048 structures. (Note that OpenSSL uses a number of global data
5049 structures that will be implicitly shared whenever multiple
5050 threads use OpenSSL.) Multi-threaded applications will
5051 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005052
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005053 locking_function() must be able to handle up to
5054 CRYPTO_num_locks() different mutex locks. It sets the n-th
5055 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005056
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005057 file and line are the file number of the function setting the
5058 lock. They can be useful for debugging.
5059 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005060
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005061 if ((_ssl_locks == NULL) ||
5062 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5063 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005064
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005065 if (mode & CRYPTO_LOCK) {
5066 PyThread_acquire_lock(_ssl_locks[n], 1);
5067 } else {
5068 PyThread_release_lock(_ssl_locks[n]);
5069 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005070}
5071
5072static int _setup_ssl_threads(void) {
5073
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005074 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005076 if (_ssl_locks == NULL) {
5077 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005078 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5079 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005080 if (_ssl_locks == NULL) {
5081 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005082 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005083 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005084 for (i = 0; i < _ssl_locks_count; i++) {
5085 _ssl_locks[i] = PyThread_allocate_lock();
5086 if (_ssl_locks[i] == NULL) {
5087 unsigned int j;
5088 for (j = 0; j < i; j++) {
5089 PyThread_free_lock(_ssl_locks[j]);
5090 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005091 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005092 return 0;
5093 }
5094 }
5095 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005096#if OPENSSL_VERSION_NUMBER >= 0x10000000
5097 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5098#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005099 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005100#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005101 }
5102 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005103}
5104
Christian Heimes598894f2016-09-05 23:19:05 +02005105#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005106
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005107PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005108"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005109for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005110
Martin v. Löwis1a214512008-06-11 05:26:20 +00005111
5112static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005113 PyModuleDef_HEAD_INIT,
5114 "_ssl",
5115 module_doc,
5116 -1,
5117 PySSL_methods,
5118 NULL,
5119 NULL,
5120 NULL,
5121 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005122};
5123
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005124
5125static void
5126parse_openssl_version(unsigned long libver,
5127 unsigned int *major, unsigned int *minor,
5128 unsigned int *fix, unsigned int *patch,
5129 unsigned int *status)
5130{
5131 *status = libver & 0xF;
5132 libver >>= 4;
5133 *patch = libver & 0xFF;
5134 libver >>= 8;
5135 *fix = libver & 0xFF;
5136 libver >>= 8;
5137 *minor = libver & 0xFF;
5138 libver >>= 8;
5139 *major = libver & 0xFF;
5140}
5141
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005142PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005143PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005144{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005145 PyObject *m, *d, *r;
5146 unsigned long libver;
5147 unsigned int major, minor, fix, patch, status;
5148 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005149 struct py_ssl_error_code *errcode;
5150 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005151
Antoine Pitrou152efa22010-05-16 18:19:27 +00005152 if (PyType_Ready(&PySSLContext_Type) < 0)
5153 return NULL;
5154 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005155 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005156 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5157 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005158 if (PyType_Ready(&PySSLSession_Type) < 0)
5159 return NULL;
5160
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005161
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005162 m = PyModule_Create(&_sslmodule);
5163 if (m == NULL)
5164 return NULL;
5165 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005166
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005167 /* Load _socket module and its C API */
5168 socket_api = PySocketModule_ImportModuleAndAPI();
5169 if (!socket_api)
5170 return NULL;
5171 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005172
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005173 /* Init OpenSSL */
5174 SSL_load_error_strings();
5175 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005176#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02005177#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005178 /* note that this will start threading if not already started */
5179 if (!_setup_ssl_threads()) {
5180 return NULL;
5181 }
Christian Heimes598894f2016-09-05 23:19:05 +02005182#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5183 /* OpenSSL 1.1.0 builtin thread support is enabled */
5184 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005185#endif
Christian Heimes598894f2016-09-05 23:19:05 +02005186#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005187 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005188
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005189 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005190 sslerror_type_slots[0].pfunc = PyExc_OSError;
5191 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005192 if (PySSLErrorObject == NULL)
5193 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005194
Antoine Pitrou41032a62011-10-27 23:56:55 +02005195 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5196 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5197 PySSLErrorObject, NULL);
5198 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5199 "ssl.SSLWantReadError", SSLWantReadError_doc,
5200 PySSLErrorObject, NULL);
5201 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5202 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5203 PySSLErrorObject, NULL);
5204 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5205 "ssl.SSLSyscallError", SSLSyscallError_doc,
5206 PySSLErrorObject, NULL);
5207 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5208 "ssl.SSLEOFError", SSLEOFError_doc,
5209 PySSLErrorObject, NULL);
5210 if (PySSLZeroReturnErrorObject == NULL
5211 || PySSLWantReadErrorObject == NULL
5212 || PySSLWantWriteErrorObject == NULL
5213 || PySSLSyscallErrorObject == NULL
5214 || PySSLEOFErrorObject == NULL)
5215 return NULL;
5216 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5217 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5218 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5219 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5220 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5221 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005222 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005223 if (PyDict_SetItemString(d, "_SSLContext",
5224 (PyObject *)&PySSLContext_Type) != 0)
5225 return NULL;
5226 if (PyDict_SetItemString(d, "_SSLSocket",
5227 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005228 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005229 if (PyDict_SetItemString(d, "MemoryBIO",
5230 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5231 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005232 if (PyDict_SetItemString(d, "SSLSession",
5233 (PyObject *)&PySSLSession_Type) != 0)
5234 return NULL;
5235
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005236 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5237 PY_SSL_ERROR_ZERO_RETURN);
5238 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5239 PY_SSL_ERROR_WANT_READ);
5240 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5241 PY_SSL_ERROR_WANT_WRITE);
5242 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5243 PY_SSL_ERROR_WANT_X509_LOOKUP);
5244 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5245 PY_SSL_ERROR_SYSCALL);
5246 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5247 PY_SSL_ERROR_SSL);
5248 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5249 PY_SSL_ERROR_WANT_CONNECT);
5250 /* non ssl.h errorcodes */
5251 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5252 PY_SSL_ERROR_EOF);
5253 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5254 PY_SSL_ERROR_INVALID_ERROR_CODE);
5255 /* cert requirements */
5256 PyModule_AddIntConstant(m, "CERT_NONE",
5257 PY_SSL_CERT_NONE);
5258 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5259 PY_SSL_CERT_OPTIONAL);
5260 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5261 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005262 /* CRL verification for verification_flags */
5263 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5264 0);
5265 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5266 X509_V_FLAG_CRL_CHECK);
5267 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5268 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5269 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5270 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005271#ifdef X509_V_FLAG_TRUSTED_FIRST
5272 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5273 X509_V_FLAG_TRUSTED_FIRST);
5274#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005275
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005276 /* Alert Descriptions from ssl.h */
5277 /* note RESERVED constants no longer intended for use have been removed */
5278 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5279
5280#define ADD_AD_CONSTANT(s) \
5281 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5282 SSL_AD_##s)
5283
5284 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5285 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5286 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5287 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5288 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5289 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5290 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5291 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5292 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5293 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5294 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5295 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5296 ADD_AD_CONSTANT(UNKNOWN_CA);
5297 ADD_AD_CONSTANT(ACCESS_DENIED);
5298 ADD_AD_CONSTANT(DECODE_ERROR);
5299 ADD_AD_CONSTANT(DECRYPT_ERROR);
5300 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5301 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5302 ADD_AD_CONSTANT(INTERNAL_ERROR);
5303 ADD_AD_CONSTANT(USER_CANCELLED);
5304 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005305 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005306#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5307 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5308#endif
5309#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5310 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5311#endif
5312#ifdef SSL_AD_UNRECOGNIZED_NAME
5313 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5314#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005315#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5316 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5317#endif
5318#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5319 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5320#endif
5321#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5322 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5323#endif
5324
5325#undef ADD_AD_CONSTANT
5326
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005327 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005328#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005329 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5330 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005331#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005332#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005333 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5334 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005335#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005336 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005337 PY_SSL_VERSION_TLS);
5338 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5339 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005340 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5341 PY_SSL_VERSION_TLS_CLIENT);
5342 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5343 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005344 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5345 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005346#if HAVE_TLSv1_2
5347 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5348 PY_SSL_VERSION_TLS1_1);
5349 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5350 PY_SSL_VERSION_TLS1_2);
5351#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005352
Antoine Pitroub5218772010-05-21 09:56:06 +00005353 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005354 PyModule_AddIntConstant(m, "OP_ALL",
5355 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005356 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5357 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5358 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005359#if HAVE_TLSv1_2
5360 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5361 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5362#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005363 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5364 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005365 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005366 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005367#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005368 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005369#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005370#ifdef SSL_OP_NO_COMPRESSION
5371 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5372 SSL_OP_NO_COMPRESSION);
5373#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005374
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005375#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005376 r = Py_True;
5377#else
5378 r = Py_False;
5379#endif
5380 Py_INCREF(r);
5381 PyModule_AddObject(m, "HAS_SNI", r);
5382
Antoine Pitroud6494802011-07-21 01:11:30 +02005383 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005384 Py_INCREF(r);
5385 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5386
Antoine Pitrou501da612011-12-21 09:27:41 +01005387#ifdef OPENSSL_NO_ECDH
5388 r = Py_False;
5389#else
5390 r = Py_True;
5391#endif
5392 Py_INCREF(r);
5393 PyModule_AddObject(m, "HAS_ECDH", r);
5394
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005395#ifdef OPENSSL_NPN_NEGOTIATED
5396 r = Py_True;
5397#else
5398 r = Py_False;
5399#endif
5400 Py_INCREF(r);
5401 PyModule_AddObject(m, "HAS_NPN", r);
5402
Benjamin Petersoncca27322015-01-23 16:35:37 -05005403#ifdef HAVE_ALPN
5404 r = Py_True;
5405#else
5406 r = Py_False;
5407#endif
5408 Py_INCREF(r);
5409 PyModule_AddObject(m, "HAS_ALPN", r);
5410
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005411 /* Mappings for error codes */
5412 err_codes_to_names = PyDict_New();
5413 err_names_to_codes = PyDict_New();
5414 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5415 return NULL;
5416 errcode = error_codes;
5417 while (errcode->mnemonic != NULL) {
5418 PyObject *mnemo, *key;
5419 mnemo = PyUnicode_FromString(errcode->mnemonic);
5420 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5421 if (mnemo == NULL || key == NULL)
5422 return NULL;
5423 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5424 return NULL;
5425 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5426 return NULL;
5427 Py_DECREF(key);
5428 Py_DECREF(mnemo);
5429 errcode++;
5430 }
5431 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5432 return NULL;
5433 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5434 return NULL;
5435
5436 lib_codes_to_names = PyDict_New();
5437 if (lib_codes_to_names == NULL)
5438 return NULL;
5439 libcode = library_codes;
5440 while (libcode->library != NULL) {
5441 PyObject *mnemo, *key;
5442 key = PyLong_FromLong(libcode->code);
5443 mnemo = PyUnicode_FromString(libcode->library);
5444 if (key == NULL || mnemo == NULL)
5445 return NULL;
5446 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5447 return NULL;
5448 Py_DECREF(key);
5449 Py_DECREF(mnemo);
5450 libcode++;
5451 }
5452 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5453 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005454
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005455 /* OpenSSL version */
5456 /* SSLeay() gives us the version of the library linked against,
5457 which could be different from the headers version.
5458 */
5459 libver = SSLeay();
5460 r = PyLong_FromUnsignedLong(libver);
5461 if (r == NULL)
5462 return NULL;
5463 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5464 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005465 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005466 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5467 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5468 return NULL;
5469 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5470 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5471 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005472
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005473 libver = OPENSSL_VERSION_NUMBER;
5474 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5475 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5476 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5477 return NULL;
5478
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005479 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005480}