blob: 4d8e7e7a39d1ba2b56a24e121b6bc29e12530f42 [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
143
144static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
145{
146 return ne->set;
147}
148
149#ifndef OPENSSL_NO_COMP
150static int COMP_get_type(const COMP_METHOD *meth)
151{
152 return meth->type;
153}
Christian Heimes598894f2016-09-05 23:19:05 +0200154#endif
155
156static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
157{
158 return ctx->default_passwd_callback;
159}
160
161static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
162{
163 return ctx->default_passwd_callback_userdata;
164}
165
166static int X509_OBJECT_get_type(X509_OBJECT *x)
167{
168 return x->type;
169}
170
171static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
172{
173 return x->data.x509;
174}
175
176static int BIO_up_ref(BIO *b)
177{
178 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
179 return 1;
180}
181
182static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
183 return store->objs;
184}
185
186static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
187{
188 return store->param;
189}
Christian Heimes99a65702016-09-10 23:44:53 +0200190
191static int
192SSL_SESSION_has_ticket(const SSL_SESSION *s)
193{
194 return (s->tlsext_ticklen > 0) ? 1 : 0;
195}
196
197static unsigned long
198SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
199{
200 return s->tlsext_tick_lifetime_hint;
201}
202
Christian Heimes598894f2016-09-05 23:19:05 +0200203#endif /* OpenSSL < 1.1.0 or LibreSSL */
204
205
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000206enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000207 /* these mirror ssl.h */
208 PY_SSL_ERROR_NONE,
209 PY_SSL_ERROR_SSL,
210 PY_SSL_ERROR_WANT_READ,
211 PY_SSL_ERROR_WANT_WRITE,
212 PY_SSL_ERROR_WANT_X509_LOOKUP,
213 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
214 PY_SSL_ERROR_ZERO_RETURN,
215 PY_SSL_ERROR_WANT_CONNECT,
216 /* start of non ssl.h errorcodes */
217 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
218 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
219 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000220};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000221
Thomas Woutersed03b412007-08-28 21:37:11 +0000222enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000223 PY_SSL_CLIENT,
224 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000225};
226
227enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000228 PY_SSL_CERT_NONE,
229 PY_SSL_CERT_OPTIONAL,
230 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000231};
232
233enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000234 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200235 PY_SSL_VERSION_SSL3=1,
Christian Heimes598894f2016-09-05 23:19:05 +0200236 PY_SSL_VERSION_TLS,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100237#if HAVE_TLSv1_2
238 PY_SSL_VERSION_TLS1,
239 PY_SSL_VERSION_TLS1_1,
240 PY_SSL_VERSION_TLS1_2
241#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000242 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000243#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100244};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200245
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000246#ifdef WITH_THREAD
247
248/* serves as a flag to see whether we've initialized the SSL thread support. */
249/* 0 means no, greater than 0 means yes */
250
251static unsigned int _ssl_locks_count = 0;
252
253#endif /* def WITH_THREAD */
254
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000255/* SSL socket object */
256
257#define X509_NAME_MAXLEN 256
258
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000259/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
260 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
261 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
262#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000263# define HAVE_SSL_CTX_CLEAR_OPTIONS
264#else
265# undef HAVE_SSL_CTX_CLEAR_OPTIONS
266#endif
267
Antoine Pitroud6494802011-07-21 01:11:30 +0200268/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
269 * older SSL, but let's be safe */
270#define PySSL_CB_MAXLEN 128
271
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100272
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000273typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000274 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000275 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100276#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -0500277 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100278 int npn_protocols_len;
279#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500280#ifdef HAVE_ALPN
281 unsigned char *alpn_protocols;
282 int alpn_protocols_len;
283#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100284#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200285 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100286#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100287 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000288} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000289
Antoine Pitrou152efa22010-05-16 18:19:27 +0000290typedef struct {
291 PyObject_HEAD
292 PyObject *Socket; /* weakref to socket on which we're layered */
293 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100294 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000295 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200296 char shutdown_seen_zero;
297 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200298 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200299 PyObject *owner; /* Python level "owner" passed to servername callback */
300 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000301} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000302
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200303typedef struct {
304 PyObject_HEAD
305 BIO *bio;
306 int eof_written;
307} PySSLMemoryBIO;
308
Christian Heimes99a65702016-09-10 23:44:53 +0200309typedef struct {
310 PyObject_HEAD
311 SSL_SESSION *session;
312 PySSLContext *ctx;
313} PySSLSession;
314
Antoine Pitrou152efa22010-05-16 18:19:27 +0000315static PyTypeObject PySSLContext_Type;
316static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200317static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200318static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000319
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300320/*[clinic input]
321module _ssl
322class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
323class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
324class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200325class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300326[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200327/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300328
329#include "clinic/_ssl.c.h"
330
Victor Stinner14690702015-04-06 22:46:13 +0200331static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000332
Christian Heimes99a65702016-09-10 23:44:53 +0200333
Antoine Pitrou152efa22010-05-16 18:19:27 +0000334#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
335#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200336#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200337#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000338
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000339typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000340 SOCKET_IS_NONBLOCKING,
341 SOCKET_IS_BLOCKING,
342 SOCKET_HAS_TIMED_OUT,
343 SOCKET_HAS_BEEN_CLOSED,
344 SOCKET_TOO_LARGE_FOR_SELECT,
345 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000346} timeout_state;
347
Thomas Woutersed03b412007-08-28 21:37:11 +0000348/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000349#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200350#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000351
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200352/* Get the socket from a PySSLSocket, if it has one */
353#define GET_SOCKET(obj) ((obj)->Socket ? \
354 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200355
Victor Stinner14690702015-04-06 22:46:13 +0200356/* If sock is NULL, use a timeout of 0 second */
357#define GET_SOCKET_TIMEOUT(sock) \
358 ((sock != NULL) ? (sock)->sock_timeout : 0)
359
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200360/*
361 * SSL errors.
362 */
363
364PyDoc_STRVAR(SSLError_doc,
365"An error occurred in the SSL implementation.");
366
367PyDoc_STRVAR(SSLZeroReturnError_doc,
368"SSL/TLS session closed cleanly.");
369
370PyDoc_STRVAR(SSLWantReadError_doc,
371"Non-blocking SSL socket needs to read more data\n"
372"before the requested operation can be completed.");
373
374PyDoc_STRVAR(SSLWantWriteError_doc,
375"Non-blocking SSL socket needs to write more data\n"
376"before the requested operation can be completed.");
377
378PyDoc_STRVAR(SSLSyscallError_doc,
379"System error when attempting SSL operation.");
380
381PyDoc_STRVAR(SSLEOFError_doc,
382"SSL/TLS connection terminated abruptly.");
383
384static PyObject *
385SSLError_str(PyOSErrorObject *self)
386{
387 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
388 Py_INCREF(self->strerror);
389 return self->strerror;
390 }
391 else
392 return PyObject_Str(self->args);
393}
394
395static PyType_Slot sslerror_type_slots[] = {
396 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
397 {Py_tp_doc, SSLError_doc},
398 {Py_tp_str, SSLError_str},
399 {0, 0},
400};
401
402static PyType_Spec sslerror_type_spec = {
403 "ssl.SSLError",
404 sizeof(PyOSErrorObject),
405 0,
406 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
407 sslerror_type_slots
408};
409
410static void
411fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
412 int lineno, unsigned long errcode)
413{
414 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
415 PyObject *init_value, *msg, *key;
416 _Py_IDENTIFIER(reason);
417 _Py_IDENTIFIER(library);
418
419 if (errcode != 0) {
420 int lib, reason;
421
422 lib = ERR_GET_LIB(errcode);
423 reason = ERR_GET_REASON(errcode);
424 key = Py_BuildValue("ii", lib, reason);
425 if (key == NULL)
426 goto fail;
427 reason_obj = PyDict_GetItem(err_codes_to_names, key);
428 Py_DECREF(key);
429 if (reason_obj == NULL) {
430 /* XXX if reason < 100, it might reflect a library number (!!) */
431 PyErr_Clear();
432 }
433 key = PyLong_FromLong(lib);
434 if (key == NULL)
435 goto fail;
436 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
437 Py_DECREF(key);
438 if (lib_obj == NULL) {
439 PyErr_Clear();
440 }
441 if (errstr == NULL)
442 errstr = ERR_reason_error_string(errcode);
443 }
444 if (errstr == NULL)
445 errstr = "unknown error";
446
447 if (reason_obj && lib_obj)
448 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
449 lib_obj, reason_obj, errstr, lineno);
450 else if (lib_obj)
451 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
452 lib_obj, errstr, lineno);
453 else
454 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200455 if (msg == NULL)
456 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100457
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200458 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100459 if (init_value == NULL)
460 goto fail;
461
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200462 err_value = PyObject_CallObject(type, init_value);
463 Py_DECREF(init_value);
464 if (err_value == NULL)
465 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100466
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200467 if (reason_obj == NULL)
468 reason_obj = Py_None;
469 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
470 goto fail;
471 if (lib_obj == NULL)
472 lib_obj = Py_None;
473 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
474 goto fail;
475 PyErr_SetObject(type, err_value);
476fail:
477 Py_XDECREF(err_value);
478}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000479
480static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200481PySSL_SetError(PySSLSocket *obj, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000482{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200483 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200484 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000485 int err;
486 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200487 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000488
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000489 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200490 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000491
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000492 if (obj->ssl != NULL) {
493 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000494
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000495 switch (err) {
496 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200497 errstr = "TLS/SSL connection has been closed (EOF)";
498 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000499 p = PY_SSL_ERROR_ZERO_RETURN;
500 break;
501 case SSL_ERROR_WANT_READ:
502 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200503 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000504 p = PY_SSL_ERROR_WANT_READ;
505 break;
506 case SSL_ERROR_WANT_WRITE:
507 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200508 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000509 errstr = "The operation did not complete (write)";
510 break;
511 case SSL_ERROR_WANT_X509_LOOKUP:
512 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000513 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000514 break;
515 case SSL_ERROR_WANT_CONNECT:
516 p = PY_SSL_ERROR_WANT_CONNECT;
517 errstr = "The operation did not complete (connect)";
518 break;
519 case SSL_ERROR_SYSCALL:
520 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000521 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200522 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000523 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000524 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200525 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000526 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200527 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000528 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000529 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000530 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200531 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000532 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200533 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000534 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000535 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200536 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000537 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000538 }
539 } else {
540 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000541 }
542 break;
543 }
544 case SSL_ERROR_SSL:
545 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000546 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200547 if (e == 0)
548 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000549 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000550 break;
551 }
552 default:
553 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
554 errstr = "Invalid error code";
555 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000556 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200557 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000558 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000559 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000560}
561
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000562static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200563_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000564
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200565 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000566 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200567 else
568 errcode = 0;
569 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000570 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000571 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000572}
573
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200574/*
575 * SSL objects
576 */
577
Antoine Pitrou152efa22010-05-16 18:19:27 +0000578static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100579newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000580 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200581 char *server_hostname,
582 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000583{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000584 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100585 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200586 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000587
Antoine Pitrou152efa22010-05-16 18:19:27 +0000588 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000589 if (self == NULL)
590 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000591
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000592 self->peer_cert = NULL;
593 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000594 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100595 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200596 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200597 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200598 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700599 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200600 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700601 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
602 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200603 if (hostname == NULL) {
604 Py_DECREF(self);
605 return NULL;
606 }
607 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700608 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200609
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100610 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000611
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000612 /* Make sure the SSL error state is initialized */
613 (void) ERR_get_state();
614 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000615
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000616 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000617 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000618 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200619 SSL_set_app_data(self->ssl, self);
620 if (sock) {
621 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
622 } else {
623 /* BIOs are reference counted and SSL_set_bio borrows our reference.
624 * To prevent a double free in memory_bio_dealloc() we need to take an
625 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200626 BIO_up_ref(inbio->bio);
627 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200628 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
629 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200630 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000631#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200632 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000633#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200634 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000635
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100636#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000637 if (server_hostname != NULL)
638 SSL_set_tlsext_host_name(self->ssl, server_hostname);
639#endif
640
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000641 /* If the socket is in non-blocking mode or timeout mode, set the BIO
642 * to non-blocking mode (blocking is the default)
643 */
Victor Stinnere2452312015-03-28 03:00:46 +0100644 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000645 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
646 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
647 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000648
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000649 PySSL_BEGIN_ALLOW_THREADS
650 if (socket_type == PY_SSL_CLIENT)
651 SSL_set_connect_state(self->ssl);
652 else
653 SSL_set_accept_state(self->ssl);
654 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000655
Antoine Pitroud6494802011-07-21 01:11:30 +0200656 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200657 if (sock != NULL) {
658 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
659 if (self->Socket == NULL) {
660 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200661 return NULL;
662 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100663 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000664 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000665}
666
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000667/* SSL object methods */
668
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300669/*[clinic input]
670_ssl._SSLSocket.do_handshake
671[clinic start generated code]*/
672
673static PyObject *
674_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
675/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000676{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000677 int ret;
678 int err;
679 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200680 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200681 _PyTime_t timeout, deadline = 0;
682 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000683
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200684 if (sock) {
685 if (((PyObject*)sock) == Py_None) {
686 _setSSLError("Underlying socket connection gone",
687 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
688 return NULL;
689 }
690 Py_INCREF(sock);
691
692 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100693 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200694 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
695 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000696 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000697
Victor Stinner14690702015-04-06 22:46:13 +0200698 timeout = GET_SOCKET_TIMEOUT(sock);
699 has_timeout = (timeout > 0);
700 if (has_timeout)
701 deadline = _PyTime_GetMonotonicClock() + timeout;
702
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000703 /* Actually negotiate SSL connection */
704 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000705 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000706 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 ret = SSL_do_handshake(self->ssl);
708 err = SSL_get_error(self->ssl, ret);
709 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200710
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000711 if (PyErr_CheckSignals())
712 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200713
Victor Stinner14690702015-04-06 22:46:13 +0200714 if (has_timeout)
715 timeout = deadline - _PyTime_GetMonotonicClock();
716
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000717 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200718 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000719 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200720 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000721 } else {
722 sockstate = SOCKET_OPERATION_OK;
723 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200724
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000725 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000726 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000727 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000728 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000729 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
730 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000731 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000732 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000733 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
734 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000735 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000736 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000737 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
738 break;
739 }
740 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200741 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000742 if (ret < 1)
743 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000744
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 if (self->peer_cert)
746 X509_free (self->peer_cert);
747 PySSL_BEGIN_ALLOW_THREADS
748 self->peer_cert = SSL_get_peer_certificate(self->ssl);
749 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200750 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000751
752 Py_INCREF(Py_None);
753 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000754
755error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200756 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000757 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000758}
759
Thomas Woutersed03b412007-08-28 21:37:11 +0000760static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000761_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000762
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000763 char namebuf[X509_NAME_MAXLEN];
764 int buflen;
765 PyObject *name_obj;
766 PyObject *value_obj;
767 PyObject *attr;
768 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000769
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
771 if (buflen < 0) {
772 _setSSLError(NULL, 0, __FILE__, __LINE__);
773 goto fail;
774 }
775 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
776 if (name_obj == NULL)
777 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000778
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
780 if (buflen < 0) {
781 _setSSLError(NULL, 0, __FILE__, __LINE__);
782 Py_DECREF(name_obj);
783 goto fail;
784 }
785 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000786 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000787 OPENSSL_free(valuebuf);
788 if (value_obj == NULL) {
789 Py_DECREF(name_obj);
790 goto fail;
791 }
792 attr = PyTuple_New(2);
793 if (attr == NULL) {
794 Py_DECREF(name_obj);
795 Py_DECREF(value_obj);
796 goto fail;
797 }
798 PyTuple_SET_ITEM(attr, 0, name_obj);
799 PyTuple_SET_ITEM(attr, 1, value_obj);
800 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000801
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000804}
805
806static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000808{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000809 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
810 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
811 PyObject *rdnt;
812 PyObject *attr = NULL; /* tuple to hold an attribute */
813 int entry_count = X509_NAME_entry_count(xname);
814 X509_NAME_ENTRY *entry;
815 ASN1_OBJECT *name;
816 ASN1_STRING *value;
817 int index_counter;
818 int rdn_level = -1;
819 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000820
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000821 dn = PyList_New(0);
822 if (dn == NULL)
823 return NULL;
824 /* now create another tuple to hold the top-level RDN */
825 rdn = PyList_New(0);
826 if (rdn == NULL)
827 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000829 for (index_counter = 0;
830 index_counter < entry_count;
831 index_counter++)
832 {
833 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000834
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000835 /* check to see if we've gotten to a new RDN */
836 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200837 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 /* yes, new RDN */
839 /* add old RDN to DN */
840 rdnt = PyList_AsTuple(rdn);
841 Py_DECREF(rdn);
842 if (rdnt == NULL)
843 goto fail0;
844 retcode = PyList_Append(dn, rdnt);
845 Py_DECREF(rdnt);
846 if (retcode < 0)
847 goto fail0;
848 /* create new RDN */
849 rdn = PyList_New(0);
850 if (rdn == NULL)
851 goto fail0;
852 }
853 }
Christian Heimes598894f2016-09-05 23:19:05 +0200854 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000855
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000856 /* now add this attribute to the current RDN */
857 name = X509_NAME_ENTRY_get_object(entry);
858 value = X509_NAME_ENTRY_get_data(entry);
859 attr = _create_tuple_for_attribute(name, value);
860 /*
861 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
862 entry->set,
863 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
864 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
865 */
866 if (attr == NULL)
867 goto fail1;
868 retcode = PyList_Append(rdn, attr);
869 Py_DECREF(attr);
870 if (retcode < 0)
871 goto fail1;
872 }
873 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100874 if (rdn != NULL) {
875 if (PyList_GET_SIZE(rdn) > 0) {
876 rdnt = PyList_AsTuple(rdn);
877 Py_DECREF(rdn);
878 if (rdnt == NULL)
879 goto fail0;
880 retcode = PyList_Append(dn, rdnt);
881 Py_DECREF(rdnt);
882 if (retcode < 0)
883 goto fail0;
884 }
885 else {
886 Py_DECREF(rdn);
887 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000888 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000889
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000890 /* convert list to tuple */
891 rdnt = PyList_AsTuple(dn);
892 Py_DECREF(dn);
893 if (rdnt == NULL)
894 return NULL;
895 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000896
897 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000898 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000899
900 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000901 Py_XDECREF(dn);
902 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000903}
904
905static PyObject *
906_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000907
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000908 /* this code follows the procedure outlined in
909 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
910 function to extract the STACK_OF(GENERAL_NAME),
911 then iterates through the stack to add the
912 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000913
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000914 int i, j;
915 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200916 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000917 X509_EXTENSION *ext = NULL;
918 GENERAL_NAMES *names = NULL;
919 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000920 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000921 BIO *biobuf = NULL;
922 char buf[2048];
923 char *vptr;
924 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000925 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000926
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000927 if (certificate == NULL)
928 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000929
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 /* get a memory buffer */
931 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000932
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200933 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 while ((i = X509_get_ext_by_NID(
935 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000936
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000937 if (peer_alt_names == Py_None) {
938 peer_alt_names = PyList_New(0);
939 if (peer_alt_names == NULL)
940 goto fail;
941 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000942
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 /* now decode the altName */
944 ext = X509_get_ext(certificate, i);
945 if(!(method = X509V3_EXT_get(ext))) {
946 PyErr_SetString
947 (PySSLErrorObject,
948 ERRSTR("No method for internalizing subjectAltName!"));
949 goto fail;
950 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000951
Christian Heimes598894f2016-09-05 23:19:05 +0200952 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000953 if (method->it)
954 names = (GENERAL_NAMES*)
955 (ASN1_item_d2i(NULL,
956 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200957 X509_EXTENSION_get_data(ext)->length,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000958 ASN1_ITEM_ptr(method->it)));
959 else
960 names = (GENERAL_NAMES*)
961 (method->d2i(NULL,
962 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200963 X509_EXTENSION_get_data(ext)->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000964
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000965 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200967 int gntype;
968 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000969
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200971 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200972 switch (gntype) {
973 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 /* we special-case DirName as a tuple of
975 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000976
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000977 t = PyTuple_New(2);
978 if (t == NULL) {
979 goto fail;
980 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000981
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000982 v = PyUnicode_FromString("DirName");
983 if (v == NULL) {
984 Py_DECREF(t);
985 goto fail;
986 }
987 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000988
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000989 v = _create_tuple_for_X509_NAME (name->d.dirn);
990 if (v == NULL) {
991 Py_DECREF(t);
992 goto fail;
993 }
994 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200995 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000996
Christian Heimes824f7f32013-08-17 00:54:47 +0200997 case GEN_EMAIL:
998 case GEN_DNS:
999 case GEN_URI:
1000 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1001 correctly, CVE-2013-4238 */
1002 t = PyTuple_New(2);
1003 if (t == NULL)
1004 goto fail;
1005 switch (gntype) {
1006 case GEN_EMAIL:
1007 v = PyUnicode_FromString("email");
1008 as = name->d.rfc822Name;
1009 break;
1010 case GEN_DNS:
1011 v = PyUnicode_FromString("DNS");
1012 as = name->d.dNSName;
1013 break;
1014 case GEN_URI:
1015 v = PyUnicode_FromString("URI");
1016 as = name->d.uniformResourceIdentifier;
1017 break;
1018 }
1019 if (v == NULL) {
1020 Py_DECREF(t);
1021 goto fail;
1022 }
1023 PyTuple_SET_ITEM(t, 0, v);
1024 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1025 ASN1_STRING_length(as));
1026 if (v == NULL) {
1027 Py_DECREF(t);
1028 goto fail;
1029 }
1030 PyTuple_SET_ITEM(t, 1, v);
1031 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001032
Christian Heimes1c03abd2016-09-06 23:25:35 +02001033 case GEN_RID:
1034 t = PyTuple_New(2);
1035 if (t == NULL)
1036 goto fail;
1037
1038 v = PyUnicode_FromString("Registered ID");
1039 if (v == NULL) {
1040 Py_DECREF(t);
1041 goto fail;
1042 }
1043 PyTuple_SET_ITEM(t, 0, v);
1044
1045 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1046 if (len < 0) {
1047 Py_DECREF(t);
1048 _setSSLError(NULL, 0, __FILE__, __LINE__);
1049 goto fail;
1050 } else if (len >= (int)sizeof(buf)) {
1051 v = PyUnicode_FromString("<INVALID>");
1052 } else {
1053 v = PyUnicode_FromStringAndSize(buf, len);
1054 }
1055 if (v == NULL) {
1056 Py_DECREF(t);
1057 goto fail;
1058 }
1059 PyTuple_SET_ITEM(t, 1, v);
1060 break;
1061
Christian Heimes824f7f32013-08-17 00:54:47 +02001062 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001063 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001064 switch (gntype) {
1065 /* check for new general name type */
1066 case GEN_OTHERNAME:
1067 case GEN_X400:
1068 case GEN_EDIPARTY:
1069 case GEN_IPADD:
1070 case GEN_RID:
1071 break;
1072 default:
1073 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1074 "Unknown general name type %d",
1075 gntype) == -1) {
1076 goto fail;
1077 }
1078 break;
1079 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001080 (void) BIO_reset(biobuf);
1081 GENERAL_NAME_print(biobuf, name);
1082 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1083 if (len < 0) {
1084 _setSSLError(NULL, 0, __FILE__, __LINE__);
1085 goto fail;
1086 }
1087 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001088 if (vptr == NULL) {
1089 PyErr_Format(PyExc_ValueError,
1090 "Invalid value %.200s",
1091 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001092 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001093 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001094 t = PyTuple_New(2);
1095 if (t == NULL)
1096 goto fail;
1097 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1098 if (v == NULL) {
1099 Py_DECREF(t);
1100 goto fail;
1101 }
1102 PyTuple_SET_ITEM(t, 0, v);
1103 v = PyUnicode_FromStringAndSize((vptr + 1),
1104 (len - (vptr - buf + 1)));
1105 if (v == NULL) {
1106 Py_DECREF(t);
1107 goto fail;
1108 }
1109 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001110 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001112
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001113 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001114
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001115 if (PyList_Append(peer_alt_names, t) < 0) {
1116 Py_DECREF(t);
1117 goto fail;
1118 }
1119 Py_DECREF(t);
1120 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001121 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001122 }
1123 BIO_free(biobuf);
1124 if (peer_alt_names != Py_None) {
1125 v = PyList_AsTuple(peer_alt_names);
1126 Py_DECREF(peer_alt_names);
1127 return v;
1128 } else {
1129 return peer_alt_names;
1130 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001131
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001132
1133 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001134 if (biobuf != NULL)
1135 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 if (peer_alt_names != Py_None) {
1138 Py_XDECREF(peer_alt_names);
1139 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001140
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001141 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001142}
1143
1144static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001145_get_aia_uri(X509 *certificate, int nid) {
1146 PyObject *lst = NULL, *ostr = NULL;
1147 int i, result;
1148 AUTHORITY_INFO_ACCESS *info;
1149
1150 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001151 if (info == NULL)
1152 return Py_None;
1153 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1154 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001155 return Py_None;
1156 }
1157
1158 if ((lst = PyList_New(0)) == NULL) {
1159 goto fail;
1160 }
1161
1162 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1163 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1164 ASN1_IA5STRING *uri;
1165
1166 if ((OBJ_obj2nid(ad->method) != nid) ||
1167 (ad->location->type != GEN_URI)) {
1168 continue;
1169 }
1170 uri = ad->location->d.uniformResourceIdentifier;
1171 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1172 uri->length);
1173 if (ostr == NULL) {
1174 goto fail;
1175 }
1176 result = PyList_Append(lst, ostr);
1177 Py_DECREF(ostr);
1178 if (result < 0) {
1179 goto fail;
1180 }
1181 }
1182 AUTHORITY_INFO_ACCESS_free(info);
1183
1184 /* convert to tuple or None */
1185 if (PyList_Size(lst) == 0) {
1186 Py_DECREF(lst);
1187 return Py_None;
1188 } else {
1189 PyObject *tup;
1190 tup = PyList_AsTuple(lst);
1191 Py_DECREF(lst);
1192 return tup;
1193 }
1194
1195 fail:
1196 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001197 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001198 return NULL;
1199}
1200
1201static PyObject *
1202_get_crl_dp(X509 *certificate) {
1203 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001204 int i, j;
1205 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001206
Christian Heimes598894f2016-09-05 23:19:05 +02001207#if OPENSSL_VERSION_NUMBER >= 0x10001000L
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001208 /* Calls x509v3_cache_extensions and sets up crldp */
1209 X509_check_ca(certificate);
Christian Heimes949ec142013-11-21 16:26:51 +01001210#endif
Christian Heimes598894f2016-09-05 23:19:05 +02001211 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001212
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001213 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001214 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001215
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001216 lst = PyList_New(0);
1217 if (lst == NULL)
1218 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001219
1220 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1221 DIST_POINT *dp;
1222 STACK_OF(GENERAL_NAME) *gns;
1223
1224 dp = sk_DIST_POINT_value(dps, i);
1225 gns = dp->distpoint->name.fullname;
1226
1227 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1228 GENERAL_NAME *gn;
1229 ASN1_IA5STRING *uri;
1230 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001231 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001232
1233 gn = sk_GENERAL_NAME_value(gns, j);
1234 if (gn->type != GEN_URI) {
1235 continue;
1236 }
1237 uri = gn->d.uniformResourceIdentifier;
1238 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1239 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001240 if (ouri == NULL)
1241 goto done;
1242
1243 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001244 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001245 if (err < 0)
1246 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001247 }
1248 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001249
1250 /* Convert to tuple. */
1251 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1252
1253 done:
1254 Py_XDECREF(lst);
1255#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Peterson806fb252015-11-14 00:09:22 -08001256 sk_DIST_POINT_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001257#endif
1258 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001259}
1260
1261static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001262_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001263
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001264 PyObject *retval = NULL;
1265 BIO *biobuf = NULL;
1266 PyObject *peer;
1267 PyObject *peer_alt_names = NULL;
1268 PyObject *issuer;
1269 PyObject *version;
1270 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001271 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001272 ASN1_INTEGER *serialNumber;
1273 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001274 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001275 ASN1_TIME *notBefore, *notAfter;
1276 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 retval = PyDict_New();
1279 if (retval == NULL)
1280 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001281
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001282 peer = _create_tuple_for_X509_NAME(
1283 X509_get_subject_name(certificate));
1284 if (peer == NULL)
1285 goto fail0;
1286 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1287 Py_DECREF(peer);
1288 goto fail0;
1289 }
1290 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001291
Antoine Pitroufb046912010-11-09 20:21:19 +00001292 issuer = _create_tuple_for_X509_NAME(
1293 X509_get_issuer_name(certificate));
1294 if (issuer == NULL)
1295 goto fail0;
1296 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001297 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001298 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001299 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001300 Py_DECREF(issuer);
1301
1302 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001303 if (version == NULL)
1304 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001305 if (PyDict_SetItemString(retval, "version", version) < 0) {
1306 Py_DECREF(version);
1307 goto fail0;
1308 }
1309 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001310
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001311 /* get a memory buffer */
1312 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001313
Antoine Pitroufb046912010-11-09 20:21:19 +00001314 (void) BIO_reset(biobuf);
1315 serialNumber = X509_get_serialNumber(certificate);
1316 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1317 i2a_ASN1_INTEGER(biobuf, serialNumber);
1318 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1319 if (len < 0) {
1320 _setSSLError(NULL, 0, __FILE__, __LINE__);
1321 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001322 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001323 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1324 if (sn_obj == NULL)
1325 goto fail1;
1326 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1327 Py_DECREF(sn_obj);
1328 goto fail1;
1329 }
1330 Py_DECREF(sn_obj);
1331
1332 (void) BIO_reset(biobuf);
1333 notBefore = X509_get_notBefore(certificate);
1334 ASN1_TIME_print(biobuf, notBefore);
1335 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1336 if (len < 0) {
1337 _setSSLError(NULL, 0, __FILE__, __LINE__);
1338 goto fail1;
1339 }
1340 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1341 if (pnotBefore == NULL)
1342 goto fail1;
1343 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1344 Py_DECREF(pnotBefore);
1345 goto fail1;
1346 }
1347 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001348
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001349 (void) BIO_reset(biobuf);
1350 notAfter = X509_get_notAfter(certificate);
1351 ASN1_TIME_print(biobuf, notAfter);
1352 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1353 if (len < 0) {
1354 _setSSLError(NULL, 0, __FILE__, __LINE__);
1355 goto fail1;
1356 }
1357 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1358 if (pnotAfter == NULL)
1359 goto fail1;
1360 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1361 Py_DECREF(pnotAfter);
1362 goto fail1;
1363 }
1364 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001365
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001367
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 peer_alt_names = _get_peer_alt_names(certificate);
1369 if (peer_alt_names == NULL)
1370 goto fail1;
1371 else if (peer_alt_names != Py_None) {
1372 if (PyDict_SetItemString(retval, "subjectAltName",
1373 peer_alt_names) < 0) {
1374 Py_DECREF(peer_alt_names);
1375 goto fail1;
1376 }
1377 Py_DECREF(peer_alt_names);
1378 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001379
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001380 /* Authority Information Access: OCSP URIs */
1381 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1382 if (obj == NULL) {
1383 goto fail1;
1384 } else if (obj != Py_None) {
1385 result = PyDict_SetItemString(retval, "OCSP", obj);
1386 Py_DECREF(obj);
1387 if (result < 0) {
1388 goto fail1;
1389 }
1390 }
1391
1392 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1393 if (obj == NULL) {
1394 goto fail1;
1395 } else if (obj != Py_None) {
1396 result = PyDict_SetItemString(retval, "caIssuers", obj);
1397 Py_DECREF(obj);
1398 if (result < 0) {
1399 goto fail1;
1400 }
1401 }
1402
1403 /* CDP (CRL distribution points) */
1404 obj = _get_crl_dp(certificate);
1405 if (obj == NULL) {
1406 goto fail1;
1407 } else if (obj != Py_None) {
1408 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1409 Py_DECREF(obj);
1410 if (result < 0) {
1411 goto fail1;
1412 }
1413 }
1414
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001415 BIO_free(biobuf);
1416 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001417
1418 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001419 if (biobuf != NULL)
1420 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001421 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001422 Py_XDECREF(retval);
1423 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001424}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001425
Christian Heimes9a5395a2013-06-17 15:44:12 +02001426static PyObject *
1427_certificate_to_der(X509 *certificate)
1428{
1429 unsigned char *bytes_buf = NULL;
1430 int len;
1431 PyObject *retval;
1432
1433 bytes_buf = NULL;
1434 len = i2d_X509(certificate, &bytes_buf);
1435 if (len < 0) {
1436 _setSSLError(NULL, 0, __FILE__, __LINE__);
1437 return NULL;
1438 }
1439 /* this is actually an immutable bytes sequence */
1440 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1441 OPENSSL_free(bytes_buf);
1442 return retval;
1443}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001444
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001445/*[clinic input]
1446_ssl._test_decode_cert
1447 path: object(converter="PyUnicode_FSConverter")
1448 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001449
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001450[clinic start generated code]*/
1451
1452static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001453_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1454/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001455{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001456 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001457 X509 *x=NULL;
1458 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001459
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001460 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1461 PyErr_SetString(PySSLErrorObject,
1462 "Can't malloc memory to read file");
1463 goto fail0;
1464 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001465
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001466 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001467 PyErr_SetString(PySSLErrorObject,
1468 "Can't open file");
1469 goto fail0;
1470 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001471
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001472 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1473 if (x == NULL) {
1474 PyErr_SetString(PySSLErrorObject,
1475 "Error decoding PEM-encoded file");
1476 goto fail0;
1477 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001478
Antoine Pitroufb046912010-11-09 20:21:19 +00001479 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001480 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001481
1482 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001483 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001484 if (cert != NULL) BIO_free(cert);
1485 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001486}
1487
1488
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001489/*[clinic input]
1490_ssl._SSLSocket.peer_certificate
1491 der as binary_mode: bool = False
1492 /
1493
1494Returns the certificate for the peer.
1495
1496If no certificate was provided, returns None. If a certificate was
1497provided, but not validated, returns an empty dictionary. Otherwise
1498returns a dict containing information about the peer certificate.
1499
1500If the optional argument is True, returns a DER-encoded copy of the
1501peer certificate, or None if no certificate was provided. This will
1502return the certificate even if it wasn't validated.
1503[clinic start generated code]*/
1504
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001505static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001506_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1507/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001508{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001509 int verification;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001510
Antoine Pitrou20b85552013-09-29 19:50:53 +02001511 if (!self->handshake_done) {
1512 PyErr_SetString(PyExc_ValueError,
1513 "handshake not done yet");
1514 return NULL;
1515 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001516 if (!self->peer_cert)
1517 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001518
Antoine Pitrou721738f2012-08-15 23:20:39 +02001519 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001520 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001521 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001523 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 if ((verification & SSL_VERIFY_PEER) == 0)
1525 return PyDict_New();
1526 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001527 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001529}
1530
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001531static PyObject *
1532cipher_to_tuple(const SSL_CIPHER *cipher)
1533{
1534 const char *cipher_name, *cipher_protocol;
1535 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001536 if (retval == NULL)
1537 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001538
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001539 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001540 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001541 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001542 PyTuple_SET_ITEM(retval, 0, Py_None);
1543 } else {
1544 v = PyUnicode_FromString(cipher_name);
1545 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001546 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001547 PyTuple_SET_ITEM(retval, 0, v);
1548 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001549
1550 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001551 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001552 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001553 PyTuple_SET_ITEM(retval, 1, Py_None);
1554 } else {
1555 v = PyUnicode_FromString(cipher_protocol);
1556 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001557 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558 PyTuple_SET_ITEM(retval, 1, v);
1559 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001560
1561 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001562 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001563 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001564 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001565
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001566 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001567
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001568 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001569 Py_DECREF(retval);
1570 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001571}
1572
Christian Heimes25bfcd52016-09-06 00:04:45 +02001573#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1574static PyObject *
1575cipher_to_dict(const SSL_CIPHER *cipher)
1576{
1577 const char *cipher_name, *cipher_protocol;
1578
1579 unsigned long cipher_id;
1580 int alg_bits, strength_bits, len;
1581 char buf[512] = {0};
1582#if OPENSSL_VERSION_1_1
1583 int aead, nid;
1584 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1585#endif
1586 PyObject *retval;
1587
1588 retval = PyDict_New();
1589 if (retval == NULL) {
1590 goto error;
1591 }
1592
1593 /* can be NULL */
1594 cipher_name = SSL_CIPHER_get_name(cipher);
1595 cipher_protocol = SSL_CIPHER_get_version(cipher);
1596 cipher_id = SSL_CIPHER_get_id(cipher);
1597 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1598 len = strlen(buf);
1599 if (len > 1 && buf[len-1] == '\n')
1600 buf[len-1] = '\0';
1601 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1602
1603#if OPENSSL_VERSION_1_1
1604 aead = SSL_CIPHER_is_aead(cipher);
1605 nid = SSL_CIPHER_get_cipher_nid(cipher);
1606 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1607 nid = SSL_CIPHER_get_digest_nid(cipher);
1608 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1609 nid = SSL_CIPHER_get_kx_nid(cipher);
1610 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1611 nid = SSL_CIPHER_get_auth_nid(cipher);
1612 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1613#endif
1614
1615 retval = Py_BuildValue(
1616 "{sksssssssisi"
1617#if OPENSSL_VERSION_1_1
1618 "sOssssssss"
1619#endif
1620 "}",
1621 "id", cipher_id,
1622 "name", cipher_name,
1623 "protocol", cipher_protocol,
1624 "description", buf,
1625 "strength_bits", strength_bits,
1626 "alg_bits", alg_bits
1627#if OPENSSL_VERSION_1_1
1628 ,"aead", aead ? Py_True : Py_False,
1629 "symmetric", skcipher,
1630 "digest", digest,
1631 "kea", kx,
1632 "auth", auth
1633#endif
1634 );
1635 return retval;
1636
1637 error:
1638 Py_XDECREF(retval);
1639 return NULL;
1640}
1641#endif
1642
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001643/*[clinic input]
1644_ssl._SSLSocket.shared_ciphers
1645[clinic start generated code]*/
1646
1647static PyObject *
1648_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1649/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001650{
1651 STACK_OF(SSL_CIPHER) *ciphers;
1652 int i;
1653 PyObject *res;
1654
Christian Heimes598894f2016-09-05 23:19:05 +02001655 ciphers = SSL_get_ciphers(self->ssl);
1656 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001657 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001658 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1659 if (!res)
1660 return NULL;
1661 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1662 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1663 if (!tup) {
1664 Py_DECREF(res);
1665 return NULL;
1666 }
1667 PyList_SET_ITEM(res, i, tup);
1668 }
1669 return res;
1670}
1671
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001672/*[clinic input]
1673_ssl._SSLSocket.cipher
1674[clinic start generated code]*/
1675
1676static PyObject *
1677_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1678/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001679{
1680 const SSL_CIPHER *current;
1681
1682 if (self->ssl == NULL)
1683 Py_RETURN_NONE;
1684 current = SSL_get_current_cipher(self->ssl);
1685 if (current == NULL)
1686 Py_RETURN_NONE;
1687 return cipher_to_tuple(current);
1688}
1689
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001690/*[clinic input]
1691_ssl._SSLSocket.version
1692[clinic start generated code]*/
1693
1694static PyObject *
1695_ssl__SSLSocket_version_impl(PySSLSocket *self)
1696/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001697{
1698 const char *version;
1699
1700 if (self->ssl == NULL)
1701 Py_RETURN_NONE;
1702 version = SSL_get_version(self->ssl);
1703 if (!strcmp(version, "unknown"))
1704 Py_RETURN_NONE;
1705 return PyUnicode_FromString(version);
1706}
1707
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001708#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001709/*[clinic input]
1710_ssl._SSLSocket.selected_npn_protocol
1711[clinic start generated code]*/
1712
1713static PyObject *
1714_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1715/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1716{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001717 const unsigned char *out;
1718 unsigned int outlen;
1719
Victor Stinner4569cd52013-06-23 14:58:43 +02001720 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001721 &out, &outlen);
1722
1723 if (out == NULL)
1724 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001725 return PyUnicode_FromStringAndSize((char *)out, outlen);
1726}
1727#endif
1728
1729#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001730/*[clinic input]
1731_ssl._SSLSocket.selected_alpn_protocol
1732[clinic start generated code]*/
1733
1734static PyObject *
1735_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1736/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1737{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001738 const unsigned char *out;
1739 unsigned int outlen;
1740
1741 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1742
1743 if (out == NULL)
1744 Py_RETURN_NONE;
1745 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001746}
1747#endif
1748
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001749/*[clinic input]
1750_ssl._SSLSocket.compression
1751[clinic start generated code]*/
1752
1753static PyObject *
1754_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1755/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1756{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001757#ifdef OPENSSL_NO_COMP
1758 Py_RETURN_NONE;
1759#else
1760 const COMP_METHOD *comp_method;
1761 const char *short_name;
1762
1763 if (self->ssl == NULL)
1764 Py_RETURN_NONE;
1765 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001766 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001767 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001768 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001769 if (short_name == NULL)
1770 Py_RETURN_NONE;
1771 return PyUnicode_DecodeFSDefault(short_name);
1772#endif
1773}
1774
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001775static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1776 Py_INCREF(self->ctx);
1777 return self->ctx;
1778}
1779
1780static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1781 void *closure) {
1782
1783 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001784#if !HAVE_SNI
1785 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1786 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001787 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001788#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001789 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001790 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001791 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001792#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001793 } else {
1794 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1795 return -1;
1796 }
1797
1798 return 0;
1799}
1800
1801PyDoc_STRVAR(PySSL_set_context_doc,
1802"_setter_context(ctx)\n\
1803\
1804This changes the context associated with the SSLSocket. This is typically\n\
1805used from within a callback function set by the set_servername_callback\n\
1806on the SSLContext to change the certificate information associated with the\n\
1807SSLSocket before the cryptographic exchange handshake messages\n");
1808
1809
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001810static PyObject *
1811PySSL_get_server_side(PySSLSocket *self, void *c)
1812{
1813 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1814}
1815
1816PyDoc_STRVAR(PySSL_get_server_side_doc,
1817"Whether this is a server-side socket.");
1818
1819static PyObject *
1820PySSL_get_server_hostname(PySSLSocket *self, void *c)
1821{
1822 if (self->server_hostname == NULL)
1823 Py_RETURN_NONE;
1824 Py_INCREF(self->server_hostname);
1825 return self->server_hostname;
1826}
1827
1828PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1829"The currently set server hostname (for SNI).");
1830
1831static PyObject *
1832PySSL_get_owner(PySSLSocket *self, void *c)
1833{
1834 PyObject *owner;
1835
1836 if (self->owner == NULL)
1837 Py_RETURN_NONE;
1838
1839 owner = PyWeakref_GetObject(self->owner);
1840 Py_INCREF(owner);
1841 return owner;
1842}
1843
1844static int
1845PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1846{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001847 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001848 if (self->owner == NULL)
1849 return -1;
1850 return 0;
1851}
1852
1853PyDoc_STRVAR(PySSL_get_owner_doc,
1854"The Python-level owner of this object.\
1855Passed as \"self\" in servername callback.");
1856
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001857
Antoine Pitrou152efa22010-05-16 18:19:27 +00001858static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001859{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001860 if (self->peer_cert) /* Possible not to have one? */
1861 X509_free (self->peer_cert);
1862 if (self->ssl)
1863 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001864 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001865 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001866 Py_XDECREF(self->server_hostname);
1867 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001868 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001869}
1870
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001871/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001872 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001873 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001874 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001875
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001876static int
Victor Stinner14690702015-04-06 22:46:13 +02001877PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001878{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001879 int rc;
1880#ifdef HAVE_POLL
1881 struct pollfd pollfd;
1882 _PyTime_t ms;
1883#else
1884 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001885 fd_set fds;
1886 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001887#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001888
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001889 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001890 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001891 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001892 else if (timeout < 0) {
1893 if (s->sock_timeout > 0)
1894 return SOCKET_HAS_TIMED_OUT;
1895 else
1896 return SOCKET_IS_BLOCKING;
1897 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001898
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001899 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001900 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001901 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001902
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001903 /* Prefer poll, if available, since you can poll() any fd
1904 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001905#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001906 pollfd.fd = s->sock_fd;
1907 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001908
Victor Stinner14690702015-04-06 22:46:13 +02001909 /* timeout is in seconds, poll() uses milliseconds */
1910 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001911 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001912
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001913 PySSL_BEGIN_ALLOW_THREADS
1914 rc = poll(&pollfd, 1, (int)ms);
1915 PySSL_END_ALLOW_THREADS
1916#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001917 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001918 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001919 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001920
Victor Stinner14690702015-04-06 22:46:13 +02001921 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001922
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001923 FD_ZERO(&fds);
1924 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001925
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001926 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001927 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001928 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001929 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001930 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001931 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001932 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001933 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001934#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001935
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001936 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1937 (when we are able to write or when there's something to read) */
1938 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001939}
1940
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001941/*[clinic input]
1942_ssl._SSLSocket.write
1943 b: Py_buffer
1944 /
1945
1946Writes the bytes-like object b into the SSL object.
1947
1948Returns the number of bytes written.
1949[clinic start generated code]*/
1950
1951static PyObject *
1952_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1953/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001954{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001955 int len;
1956 int sockstate;
1957 int err;
1958 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001959 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001960 _PyTime_t timeout, deadline = 0;
1961 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001962
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001963 if (sock != NULL) {
1964 if (((PyObject*)sock) == Py_None) {
1965 _setSSLError("Underlying socket connection gone",
1966 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1967 return NULL;
1968 }
1969 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001970 }
1971
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001972 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001973 PyErr_Format(PyExc_OverflowError,
1974 "string longer than %d bytes", INT_MAX);
1975 goto error;
1976 }
1977
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001978 if (sock != NULL) {
1979 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001980 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001981 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1982 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1983 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001984
Victor Stinner14690702015-04-06 22:46:13 +02001985 timeout = GET_SOCKET_TIMEOUT(sock);
1986 has_timeout = (timeout > 0);
1987 if (has_timeout)
1988 deadline = _PyTime_GetMonotonicClock() + timeout;
1989
1990 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001991 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001992 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001993 "The write operation timed out");
1994 goto error;
1995 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1996 PyErr_SetString(PySSLErrorObject,
1997 "Underlying socket has been closed.");
1998 goto error;
1999 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2000 PyErr_SetString(PySSLErrorObject,
2001 "Underlying socket too large for select().");
2002 goto error;
2003 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002004
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002005 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002006 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002007 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002008 err = SSL_get_error(self->ssl, len);
2009 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002010
2011 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002012 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002013
Victor Stinner14690702015-04-06 22:46:13 +02002014 if (has_timeout)
2015 timeout = deadline - _PyTime_GetMonotonicClock();
2016
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002017 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002018 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002019 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002020 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002021 } else {
2022 sockstate = SOCKET_OPERATION_OK;
2023 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002024
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002025 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002026 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002027 "The write operation timed out");
2028 goto error;
2029 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2030 PyErr_SetString(PySSLErrorObject,
2031 "Underlying socket has been closed.");
2032 goto error;
2033 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2034 break;
2035 }
2036 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002037
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002038 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002039 if (len > 0)
2040 return PyLong_FromLong(len);
2041 else
2042 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002043
2044error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002045 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002046 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002047}
2048
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002049/*[clinic input]
2050_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002051
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002052Returns the number of already decrypted bytes available for read, pending on the connection.
2053[clinic start generated code]*/
2054
2055static PyObject *
2056_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2057/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002058{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002059 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002060
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002061 PySSL_BEGIN_ALLOW_THREADS
2062 count = SSL_pending(self->ssl);
2063 PySSL_END_ALLOW_THREADS
2064 if (count < 0)
2065 return PySSL_SetError(self, count, __FILE__, __LINE__);
2066 else
2067 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002068}
2069
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002070/*[clinic input]
2071_ssl._SSLSocket.read
2072 size as len: int
2073 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002074 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002075 ]
2076 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002077
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002078Read up to size bytes from the SSL socket.
2079[clinic start generated code]*/
2080
2081static PyObject *
2082_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2083 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002084/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002085{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002086 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002087 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002088 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002089 int sockstate;
2090 int err;
2091 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002092 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002093 _PyTime_t timeout, deadline = 0;
2094 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002095
Martin Panter5503d472016-03-27 05:35:19 +00002096 if (!group_right_1 && len < 0) {
2097 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2098 return NULL;
2099 }
2100
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002101 if (sock != NULL) {
2102 if (((PyObject*)sock) == Py_None) {
2103 _setSSLError("Underlying socket connection gone",
2104 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2105 return NULL;
2106 }
2107 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002108 }
2109
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002110 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002111 dest = PyBytes_FromStringAndSize(NULL, len);
2112 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002113 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002114 if (len == 0) {
2115 Py_XDECREF(sock);
2116 return dest;
2117 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002118 mem = PyBytes_AS_STRING(dest);
2119 }
2120 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002121 mem = buffer->buf;
2122 if (len <= 0 || len > buffer->len) {
2123 len = (int) buffer->len;
2124 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002125 PyErr_SetString(PyExc_OverflowError,
2126 "maximum length can't fit in a C 'int'");
2127 goto error;
2128 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002129 if (len == 0) {
2130 count = 0;
2131 goto done;
2132 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002133 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002134 }
2135
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002136 if (sock != NULL) {
2137 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002138 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002139 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2140 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2141 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002142
Victor Stinner14690702015-04-06 22:46:13 +02002143 timeout = GET_SOCKET_TIMEOUT(sock);
2144 has_timeout = (timeout > 0);
2145 if (has_timeout)
2146 deadline = _PyTime_GetMonotonicClock() + timeout;
2147
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002148 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002149 PySSL_BEGIN_ALLOW_THREADS
2150 count = SSL_read(self->ssl, mem, len);
2151 err = SSL_get_error(self->ssl, count);
2152 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002153
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002154 if (PyErr_CheckSignals())
2155 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002156
Victor Stinner14690702015-04-06 22:46:13 +02002157 if (has_timeout)
2158 timeout = deadline - _PyTime_GetMonotonicClock();
2159
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002160 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002161 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002162 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002163 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002164 } else if (err == SSL_ERROR_ZERO_RETURN &&
2165 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002166 {
2167 count = 0;
2168 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002169 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002170 else
2171 sockstate = SOCKET_OPERATION_OK;
2172
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002173 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002174 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002175 "The read operation timed out");
2176 goto error;
2177 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2178 break;
2179 }
2180 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002181
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002182 if (count <= 0) {
2183 PySSL_SetError(self, count, __FILE__, __LINE__);
2184 goto error;
2185 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002186
2187done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002188 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002189 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002190 _PyBytes_Resize(&dest, count);
2191 return dest;
2192 }
2193 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002194 return PyLong_FromLong(count);
2195 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002196
2197error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002198 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002199 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002200 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002201 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002202}
2203
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002204/*[clinic input]
2205_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002206
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002207Does the SSL shutdown handshake with the remote end.
2208
2209Returns the underlying socket object.
2210[clinic start generated code]*/
2211
2212static PyObject *
2213_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2214/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002215{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002216 int err, ssl_err, sockstate, nonblocking;
2217 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002218 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002219 _PyTime_t timeout, deadline = 0;
2220 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002221
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002222 if (sock != NULL) {
2223 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002224 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002225 _setSSLError("Underlying socket connection gone",
2226 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2227 return NULL;
2228 }
2229 Py_INCREF(sock);
2230
2231 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002232 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002233 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2234 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002235 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002236
Victor Stinner14690702015-04-06 22:46:13 +02002237 timeout = GET_SOCKET_TIMEOUT(sock);
2238 has_timeout = (timeout > 0);
2239 if (has_timeout)
2240 deadline = _PyTime_GetMonotonicClock() + timeout;
2241
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002242 while (1) {
2243 PySSL_BEGIN_ALLOW_THREADS
2244 /* Disable read-ahead so that unwrap can work correctly.
2245 * Otherwise OpenSSL might read in too much data,
2246 * eating clear text data that happens to be
2247 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002248 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002249 * function is used and the shutdown_seen_zero != 0
2250 * condition is met.
2251 */
2252 if (self->shutdown_seen_zero)
2253 SSL_set_read_ahead(self->ssl, 0);
2254 err = SSL_shutdown(self->ssl);
2255 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002256
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002257 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2258 if (err > 0)
2259 break;
2260 if (err == 0) {
2261 /* Don't loop endlessly; instead preserve legacy
2262 behaviour of trying SSL_shutdown() only twice.
2263 This looks necessary for OpenSSL < 0.9.8m */
2264 if (++zeros > 1)
2265 break;
2266 /* Shutdown was sent, now try receiving */
2267 self->shutdown_seen_zero = 1;
2268 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002269 }
2270
Victor Stinner14690702015-04-06 22:46:13 +02002271 if (has_timeout)
2272 timeout = deadline - _PyTime_GetMonotonicClock();
2273
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002274 /* Possibly retry shutdown until timeout or failure */
2275 ssl_err = SSL_get_error(self->ssl, err);
2276 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002277 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002278 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002279 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002280 else
2281 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002282
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002283 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2284 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002285 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002286 "The read operation timed out");
2287 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002288 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002289 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002290 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002291 }
2292 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2293 PyErr_SetString(PySSLErrorObject,
2294 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002295 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002296 }
2297 else if (sockstate != SOCKET_OPERATION_OK)
2298 /* Retain the SSL error code */
2299 break;
2300 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002301
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002302 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002303 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002304 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002305 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002306 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002307 /* It's already INCREF'ed */
2308 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002309 else
2310 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002311
2312error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002313 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002314 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002315}
2316
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002317/*[clinic input]
2318_ssl._SSLSocket.tls_unique_cb
2319
2320Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2321
2322If the TLS handshake is not yet complete, None is returned.
2323[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002324
Antoine Pitroud6494802011-07-21 01:11:30 +02002325static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002326_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2327/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002328{
2329 PyObject *retval = NULL;
2330 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002331 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002332
2333 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2334 /* if session is resumed XOR we are the client */
2335 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2336 }
2337 else {
2338 /* if a new session XOR we are the server */
2339 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2340 }
2341
2342 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002343 if (len == 0)
2344 Py_RETURN_NONE;
2345
2346 retval = PyBytes_FromStringAndSize(buf, len);
2347
2348 return retval;
2349}
2350
Christian Heimes99a65702016-09-10 23:44:53 +02002351#ifdef OPENSSL_VERSION_1_1
2352
2353static SSL_SESSION*
2354_ssl_session_dup(SSL_SESSION *session) {
2355 SSL_SESSION *newsession = NULL;
2356 int slen;
2357 unsigned char *senc = NULL, *p;
2358 const unsigned char *const_p;
2359
2360 if (session == NULL) {
2361 PyErr_SetString(PyExc_ValueError, "Invalid session");
2362 goto error;
2363 }
2364
2365 /* get length */
2366 slen = i2d_SSL_SESSION(session, NULL);
2367 if (slen == 0 || slen > 0xFF00) {
2368 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2369 goto error;
2370 }
2371 if ((senc = PyMem_Malloc(slen)) == NULL) {
2372 PyErr_NoMemory();
2373 goto error;
2374 }
2375 p = senc;
2376 if (!i2d_SSL_SESSION(session, &p)) {
2377 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2378 goto error;
2379 }
2380 const_p = senc;
2381 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2382 if (session == NULL) {
2383 goto error;
2384 }
2385 PyMem_Free(senc);
2386 return newsession;
2387 error:
2388 if (senc != NULL) {
2389 PyMem_Free(senc);
2390 }
2391 return NULL;
2392}
2393#endif
2394
2395static PyObject *
2396PySSL_get_session(PySSLSocket *self, void *closure) {
2397 /* get_session can return sessions from a server-side connection,
2398 * it does not check for handshake done or client socket. */
2399 PySSLSession *pysess;
2400 SSL_SESSION *session;
2401
2402#ifdef OPENSSL_VERSION_1_1
2403 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2404 * https://github.com/openssl/openssl/issues/1550 */
2405 session = SSL_get0_session(self->ssl); /* borrowed reference */
2406 if (session == NULL) {
2407 Py_RETURN_NONE;
2408 }
2409 if ((session = _ssl_session_dup(session)) == NULL) {
2410 return NULL;
2411 }
2412#else
2413 session = SSL_get1_session(self->ssl);
2414 if (session == NULL) {
2415 Py_RETURN_NONE;
2416 }
2417#endif
2418
2419 pysess = PyObject_New(PySSLSession, &PySSLSession_Type);
2420 if (pysess == NULL) {
2421 SSL_SESSION_free(session);
2422 return NULL;
2423 }
2424
2425 assert(self->ctx);
2426 pysess->ctx = self->ctx;
2427 Py_INCREF(pysess->ctx);
2428 pysess->session = session;
2429 return (PyObject *)pysess;
2430}
2431
2432static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2433 void *closure)
2434 {
2435 PySSLSession *pysess;
2436#ifdef OPENSSL_VERSION_1_1
2437 SSL_SESSION *session;
2438#endif
2439 int result;
2440
2441 if (!PySSLSession_Check(value)) {
2442 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2443 return -1;
2444 }
2445 pysess = (PySSLSession *)value;
2446
2447 if (self->ctx->ctx != pysess->ctx->ctx) {
2448 PyErr_SetString(PyExc_ValueError,
2449 "Session refers to a different SSLContext.");
2450 return -1;
2451 }
2452 if (self->socket_type != PY_SSL_CLIENT) {
2453 PyErr_SetString(PyExc_ValueError,
2454 "Cannot set session for server-side SSLSocket.");
2455 return -1;
2456 }
2457 if (self->handshake_done) {
2458 PyErr_SetString(PyExc_ValueError,
2459 "Cannot set session after handshake.");
2460 return -1;
2461 }
2462#ifdef OPENSSL_VERSION_1_1
2463 /* duplicate session */
2464 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2465 return -1;
2466 }
2467 result = SSL_set_session(self->ssl, session);
2468 /* free duplicate, SSL_set_session() bumps ref count */
2469 SSL_SESSION_free(session);
2470#else
2471 result = SSL_set_session(self->ssl, pysess->session);
2472#endif
2473 if (result == 0) {
2474 _setSSLError(NULL, 0, __FILE__, __LINE__);
2475 return -1;
2476 }
2477 return 0;
2478}
2479
2480PyDoc_STRVAR(PySSL_set_session_doc,
2481"_setter_session(session)\n\
2482\
2483Get / set SSLSession.");
2484
2485static PyObject *
2486PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2487 if (SSL_session_reused(self->ssl)) {
2488 Py_RETURN_TRUE;
2489 } else {
2490 Py_RETURN_FALSE;
2491 }
2492}
2493
2494PyDoc_STRVAR(PySSL_get_session_reused_doc,
2495"Was the client session reused during handshake?");
2496
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002497static PyGetSetDef ssl_getsetlist[] = {
2498 {"context", (getter) PySSL_get_context,
2499 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002500 {"server_side", (getter) PySSL_get_server_side, NULL,
2501 PySSL_get_server_side_doc},
2502 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2503 PySSL_get_server_hostname_doc},
2504 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2505 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002506 {"session", (getter) PySSL_get_session,
2507 (setter) PySSL_set_session, PySSL_set_session_doc},
2508 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2509 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002510 {NULL}, /* sentinel */
2511};
2512
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002513static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002514 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2515 _SSL__SSLSOCKET_WRITE_METHODDEF
2516 _SSL__SSLSOCKET_READ_METHODDEF
2517 _SSL__SSLSOCKET_PENDING_METHODDEF
2518 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2519 _SSL__SSLSOCKET_CIPHER_METHODDEF
2520 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2521 _SSL__SSLSOCKET_VERSION_METHODDEF
2522 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2523 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2524 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2525 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2526 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002527 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002528};
2529
Antoine Pitrou152efa22010-05-16 18:19:27 +00002530static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002531 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002532 "_ssl._SSLSocket", /*tp_name*/
2533 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002534 0, /*tp_itemsize*/
2535 /* methods */
2536 (destructor)PySSL_dealloc, /*tp_dealloc*/
2537 0, /*tp_print*/
2538 0, /*tp_getattr*/
2539 0, /*tp_setattr*/
2540 0, /*tp_reserved*/
2541 0, /*tp_repr*/
2542 0, /*tp_as_number*/
2543 0, /*tp_as_sequence*/
2544 0, /*tp_as_mapping*/
2545 0, /*tp_hash*/
2546 0, /*tp_call*/
2547 0, /*tp_str*/
2548 0, /*tp_getattro*/
2549 0, /*tp_setattro*/
2550 0, /*tp_as_buffer*/
2551 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2552 0, /*tp_doc*/
2553 0, /*tp_traverse*/
2554 0, /*tp_clear*/
2555 0, /*tp_richcompare*/
2556 0, /*tp_weaklistoffset*/
2557 0, /*tp_iter*/
2558 0, /*tp_iternext*/
2559 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002560 0, /*tp_members*/
2561 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002562};
2563
Antoine Pitrou152efa22010-05-16 18:19:27 +00002564
2565/*
2566 * _SSLContext objects
2567 */
2568
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002569/*[clinic input]
2570@classmethod
2571_ssl._SSLContext.__new__
2572 protocol as proto_version: int
2573 /
2574[clinic start generated code]*/
2575
Antoine Pitrou152efa22010-05-16 18:19:27 +00002576static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002577_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2578/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002579{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002580 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002581 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002582 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002583 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002584#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002585 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002586#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002587
Antoine Pitrou152efa22010-05-16 18:19:27 +00002588 PySSL_BEGIN_ALLOW_THREADS
2589 if (proto_version == PY_SSL_VERSION_TLS1)
2590 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002591#if HAVE_TLSv1_2
2592 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2593 ctx = SSL_CTX_new(TLSv1_1_method());
2594 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2595 ctx = SSL_CTX_new(TLSv1_2_method());
2596#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002597#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002598 else if (proto_version == PY_SSL_VERSION_SSL3)
2599 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002600#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002601#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002602 else if (proto_version == PY_SSL_VERSION_SSL2)
2603 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002604#endif
Christian Heimes598894f2016-09-05 23:19:05 +02002605 else if (proto_version == PY_SSL_VERSION_TLS)
2606 ctx = SSL_CTX_new(TLS_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002607 else
2608 proto_version = -1;
2609 PySSL_END_ALLOW_THREADS
2610
2611 if (proto_version == -1) {
2612 PyErr_SetString(PyExc_ValueError,
2613 "invalid protocol version");
2614 return NULL;
2615 }
2616 if (ctx == NULL) {
2617 PyErr_SetString(PySSLErrorObject,
2618 "failed to allocate SSL context");
2619 return NULL;
2620 }
2621
2622 assert(type != NULL && type->tp_alloc != NULL);
2623 self = (PySSLContext *) type->tp_alloc(type, 0);
2624 if (self == NULL) {
2625 SSL_CTX_free(ctx);
2626 return NULL;
2627 }
2628 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002629#ifdef OPENSSL_NPN_NEGOTIATED
2630 self->npn_protocols = NULL;
2631#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002632#ifdef HAVE_ALPN
2633 self->alpn_protocols = NULL;
2634#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002635#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002636 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002637#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002638 /* Don't check host name by default */
2639 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002640 /* Defaults */
2641 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002642 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2643 if (proto_version != PY_SSL_VERSION_SSL2)
2644 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002645 if (proto_version != PY_SSL_VERSION_SSL3)
2646 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002647 /* Minimal security flags for server and client side context.
2648 * Client sockets ignore server-side parameters. */
2649#ifdef SSL_OP_NO_COMPRESSION
2650 options |= SSL_OP_NO_COMPRESSION;
2651#endif
2652#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2653 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2654#endif
2655#ifdef SSL_OP_SINGLE_DH_USE
2656 options |= SSL_OP_SINGLE_DH_USE;
2657#endif
2658#ifdef SSL_OP_SINGLE_ECDH_USE
2659 options |= SSL_OP_SINGLE_ECDH_USE;
2660#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002661 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002662
Christian Heimes358cfd42016-09-10 22:43:48 +02002663 /* A bare minimum cipher list without completly broken cipher suites.
2664 * It's far from perfect but gives users a better head start. */
2665 if (proto_version != PY_SSL_VERSION_SSL2) {
2666 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2667 } else {
2668 /* SSLv2 needs MD5 */
2669 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2670 }
2671 if (result == 0) {
2672 Py_DECREF(self);
2673 ERR_clear_error();
2674 PyErr_SetString(PySSLErrorObject,
2675 "No cipher can be selected.");
2676 return NULL;
2677 }
2678
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002679#if defined(SSL_MODE_RELEASE_BUFFERS)
2680 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2681 usage for no cost at all. However, don't do this for OpenSSL versions
2682 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2683 2014-0198. I can't find exactly which beta fixed this CVE, so be
2684 conservative and assume it wasn't fixed until release. We do this check
2685 at runtime to avoid problems from the dynamic linker.
2686 See #25672 for more on this. */
2687 libver = SSLeay();
2688 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2689 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2690 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2691 }
2692#endif
2693
2694
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002695#ifndef OPENSSL_NO_ECDH
2696 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2697 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002698 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2699 */
2700#if defined(SSL_CTX_set_ecdh_auto) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002701 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2702#else
2703 {
2704 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2705 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2706 EC_KEY_free(key);
2707 }
2708#endif
2709#endif
2710
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002711#define SID_CTX "Python"
2712 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2713 sizeof(SID_CTX));
2714#undef SID_CTX
2715
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002716#ifdef X509_V_FLAG_TRUSTED_FIRST
2717 {
2718 /* Improve trust chain building when cross-signed intermediate
2719 certificates are present. See https://bugs.python.org/issue23476. */
2720 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2721 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2722 }
2723#endif
2724
Antoine Pitrou152efa22010-05-16 18:19:27 +00002725 return (PyObject *)self;
2726}
2727
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002728static int
2729context_traverse(PySSLContext *self, visitproc visit, void *arg)
2730{
2731#ifndef OPENSSL_NO_TLSEXT
2732 Py_VISIT(self->set_hostname);
2733#endif
2734 return 0;
2735}
2736
2737static int
2738context_clear(PySSLContext *self)
2739{
2740#ifndef OPENSSL_NO_TLSEXT
2741 Py_CLEAR(self->set_hostname);
2742#endif
2743 return 0;
2744}
2745
Antoine Pitrou152efa22010-05-16 18:19:27 +00002746static void
2747context_dealloc(PySSLContext *self)
2748{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002749 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002750 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002751#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002752 PyMem_FREE(self->npn_protocols);
2753#endif
2754#ifdef HAVE_ALPN
2755 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002756#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002757 Py_TYPE(self)->tp_free(self);
2758}
2759
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002760/*[clinic input]
2761_ssl._SSLContext.set_ciphers
2762 cipherlist: str
2763 /
2764[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002765
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002766static PyObject *
2767_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2768/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2769{
2770 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002771 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002772 /* Clearing the error queue is necessary on some OpenSSL versions,
2773 otherwise the error will be reported again when another SSL call
2774 is done. */
2775 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002776 PyErr_SetString(PySSLErrorObject,
2777 "No cipher can be selected.");
2778 return NULL;
2779 }
2780 Py_RETURN_NONE;
2781}
2782
Christian Heimes25bfcd52016-09-06 00:04:45 +02002783#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2784/*[clinic input]
2785_ssl._SSLContext.get_ciphers
2786[clinic start generated code]*/
2787
2788static PyObject *
2789_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2790/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2791{
2792 SSL *ssl = NULL;
2793 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002794 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002795 int i=0;
2796 PyObject *result = NULL, *dct;
2797
2798 ssl = SSL_new(self->ctx);
2799 if (ssl == NULL) {
2800 _setSSLError(NULL, 0, __FILE__, __LINE__);
2801 goto exit;
2802 }
2803 sk = SSL_get_ciphers(ssl);
2804
2805 result = PyList_New(sk_SSL_CIPHER_num(sk));
2806 if (result == NULL) {
2807 goto exit;
2808 }
2809
2810 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2811 cipher = sk_SSL_CIPHER_value(sk, i);
2812 dct = cipher_to_dict(cipher);
2813 if (dct == NULL) {
2814 Py_CLEAR(result);
2815 goto exit;
2816 }
2817 PyList_SET_ITEM(result, i, dct);
2818 }
2819
2820 exit:
2821 if (ssl != NULL)
2822 SSL_free(ssl);
2823 return result;
2824
2825}
2826#endif
2827
2828
Benjamin Petersonc54de472015-01-28 12:06:39 -05002829#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002830static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002831do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2832 const unsigned char *server_protocols, unsigned int server_protocols_len,
2833 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002834{
Benjamin Peterson88615022015-01-23 17:30:26 -05002835 int ret;
2836 if (client_protocols == NULL) {
2837 client_protocols = (unsigned char *)"";
2838 client_protocols_len = 0;
2839 }
2840 if (server_protocols == NULL) {
2841 server_protocols = (unsigned char *)"";
2842 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002843 }
2844
Benjamin Peterson88615022015-01-23 17:30:26 -05002845 ret = SSL_select_next_proto(out, outlen,
2846 server_protocols, server_protocols_len,
2847 client_protocols, client_protocols_len);
2848 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2849 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002850
2851 return SSL_TLSEXT_ERR_OK;
2852}
2853
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002854/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2855static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002856_advertiseNPN_cb(SSL *s,
2857 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002858 void *args)
2859{
2860 PySSLContext *ssl_ctx = (PySSLContext *) args;
2861
2862 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002863 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002864 *len = 0;
2865 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002866 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002867 *len = ssl_ctx->npn_protocols_len;
2868 }
2869
2870 return SSL_TLSEXT_ERR_OK;
2871}
2872/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2873static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002874_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002875 unsigned char **out, unsigned char *outlen,
2876 const unsigned char *server, unsigned int server_len,
2877 void *args)
2878{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002879 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002880 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002881 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002882}
2883#endif
2884
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002885/*[clinic input]
2886_ssl._SSLContext._set_npn_protocols
2887 protos: Py_buffer
2888 /
2889[clinic start generated code]*/
2890
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002891static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002892_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2893 Py_buffer *protos)
2894/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002895{
2896#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002897 PyMem_Free(self->npn_protocols);
2898 self->npn_protocols = PyMem_Malloc(protos->len);
2899 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002900 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002901 memcpy(self->npn_protocols, protos->buf, protos->len);
2902 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002903
2904 /* set both server and client callbacks, because the context can
2905 * be used to create both types of sockets */
2906 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2907 _advertiseNPN_cb,
2908 self);
2909 SSL_CTX_set_next_proto_select_cb(self->ctx,
2910 _selectNPN_cb,
2911 self);
2912
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002913 Py_RETURN_NONE;
2914#else
2915 PyErr_SetString(PyExc_NotImplementedError,
2916 "The NPN extension requires OpenSSL 1.0.1 or later.");
2917 return NULL;
2918#endif
2919}
2920
Benjamin Petersoncca27322015-01-23 16:35:37 -05002921#ifdef HAVE_ALPN
2922static int
2923_selectALPN_cb(SSL *s,
2924 const unsigned char **out, unsigned char *outlen,
2925 const unsigned char *client_protocols, unsigned int client_protocols_len,
2926 void *args)
2927{
2928 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002929 return do_protocol_selection(1, (unsigned char **)out, outlen,
2930 ctx->alpn_protocols, ctx->alpn_protocols_len,
2931 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002932}
2933#endif
2934
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002935/*[clinic input]
2936_ssl._SSLContext._set_alpn_protocols
2937 protos: Py_buffer
2938 /
2939[clinic start generated code]*/
2940
Benjamin Petersoncca27322015-01-23 16:35:37 -05002941static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002942_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2943 Py_buffer *protos)
2944/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002945{
2946#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002947 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002948 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002949 if (!self->alpn_protocols)
2950 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002951 memcpy(self->alpn_protocols, protos->buf, protos->len);
2952 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002953
2954 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2955 return PyErr_NoMemory();
2956 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2957
Benjamin Petersoncca27322015-01-23 16:35:37 -05002958 Py_RETURN_NONE;
2959#else
2960 PyErr_SetString(PyExc_NotImplementedError,
2961 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2962 return NULL;
2963#endif
2964}
2965
Antoine Pitrou152efa22010-05-16 18:19:27 +00002966static PyObject *
2967get_verify_mode(PySSLContext *self, void *c)
2968{
2969 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2970 case SSL_VERIFY_NONE:
2971 return PyLong_FromLong(PY_SSL_CERT_NONE);
2972 case SSL_VERIFY_PEER:
2973 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2974 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2975 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2976 }
2977 PyErr_SetString(PySSLErrorObject,
2978 "invalid return value from SSL_CTX_get_verify_mode");
2979 return NULL;
2980}
2981
2982static int
2983set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2984{
2985 int n, mode;
2986 if (!PyArg_Parse(arg, "i", &n))
2987 return -1;
2988 if (n == PY_SSL_CERT_NONE)
2989 mode = SSL_VERIFY_NONE;
2990 else if (n == PY_SSL_CERT_OPTIONAL)
2991 mode = SSL_VERIFY_PEER;
2992 else if (n == PY_SSL_CERT_REQUIRED)
2993 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2994 else {
2995 PyErr_SetString(PyExc_ValueError,
2996 "invalid value for verify_mode");
2997 return -1;
2998 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002999 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
3000 PyErr_SetString(PyExc_ValueError,
3001 "Cannot set verify_mode to CERT_NONE when "
3002 "check_hostname is enabled.");
3003 return -1;
3004 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003005 SSL_CTX_set_verify(self->ctx, mode, NULL);
3006 return 0;
3007}
3008
3009static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003010get_verify_flags(PySSLContext *self, void *c)
3011{
3012 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003013 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003014 unsigned long flags;
3015
3016 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003017 param = X509_STORE_get0_param(store);
3018 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003019 return PyLong_FromUnsignedLong(flags);
3020}
3021
3022static int
3023set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3024{
3025 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003026 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003027 unsigned long new_flags, flags, set, clear;
3028
3029 if (!PyArg_Parse(arg, "k", &new_flags))
3030 return -1;
3031 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003032 param = X509_STORE_get0_param(store);
3033 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003034 clear = flags & ~new_flags;
3035 set = ~flags & new_flags;
3036 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003037 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003038 _setSSLError(NULL, 0, __FILE__, __LINE__);
3039 return -1;
3040 }
3041 }
3042 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003043 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003044 _setSSLError(NULL, 0, __FILE__, __LINE__);
3045 return -1;
3046 }
3047 }
3048 return 0;
3049}
3050
3051static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003052get_options(PySSLContext *self, void *c)
3053{
3054 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3055}
3056
3057static int
3058set_options(PySSLContext *self, PyObject *arg, void *c)
3059{
3060 long new_opts, opts, set, clear;
3061 if (!PyArg_Parse(arg, "l", &new_opts))
3062 return -1;
3063 opts = SSL_CTX_get_options(self->ctx);
3064 clear = opts & ~new_opts;
3065 set = ~opts & new_opts;
3066 if (clear) {
3067#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3068 SSL_CTX_clear_options(self->ctx, clear);
3069#else
3070 PyErr_SetString(PyExc_ValueError,
3071 "can't clear options before OpenSSL 0.9.8m");
3072 return -1;
3073#endif
3074 }
3075 if (set)
3076 SSL_CTX_set_options(self->ctx, set);
3077 return 0;
3078}
3079
Christian Heimes1aa9a752013-12-02 02:41:19 +01003080static PyObject *
3081get_check_hostname(PySSLContext *self, void *c)
3082{
3083 return PyBool_FromLong(self->check_hostname);
3084}
3085
3086static int
3087set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3088{
3089 int check_hostname;
3090 if (!PyArg_Parse(arg, "p", &check_hostname))
3091 return -1;
3092 if (check_hostname &&
3093 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3094 PyErr_SetString(PyExc_ValueError,
3095 "check_hostname needs a SSL context with either "
3096 "CERT_OPTIONAL or CERT_REQUIRED");
3097 return -1;
3098 }
3099 self->check_hostname = check_hostname;
3100 return 0;
3101}
3102
3103
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003104typedef struct {
3105 PyThreadState *thread_state;
3106 PyObject *callable;
3107 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003108 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003109 int error;
3110} _PySSLPasswordInfo;
3111
3112static int
3113_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3114 const char *bad_type_error)
3115{
3116 /* Set the password and size fields of a _PySSLPasswordInfo struct
3117 from a unicode, bytes, or byte array object.
3118 The password field will be dynamically allocated and must be freed
3119 by the caller */
3120 PyObject *password_bytes = NULL;
3121 const char *data = NULL;
3122 Py_ssize_t size;
3123
3124 if (PyUnicode_Check(password)) {
3125 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3126 if (!password_bytes) {
3127 goto error;
3128 }
3129 data = PyBytes_AS_STRING(password_bytes);
3130 size = PyBytes_GET_SIZE(password_bytes);
3131 } else if (PyBytes_Check(password)) {
3132 data = PyBytes_AS_STRING(password);
3133 size = PyBytes_GET_SIZE(password);
3134 } else if (PyByteArray_Check(password)) {
3135 data = PyByteArray_AS_STRING(password);
3136 size = PyByteArray_GET_SIZE(password);
3137 } else {
3138 PyErr_SetString(PyExc_TypeError, bad_type_error);
3139 goto error;
3140 }
3141
Victor Stinner9ee02032013-06-23 15:08:23 +02003142 if (size > (Py_ssize_t)INT_MAX) {
3143 PyErr_Format(PyExc_ValueError,
3144 "password cannot be longer than %d bytes", INT_MAX);
3145 goto error;
3146 }
3147
Victor Stinner11ebff22013-07-07 17:07:52 +02003148 PyMem_Free(pw_info->password);
3149 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003150 if (!pw_info->password) {
3151 PyErr_SetString(PyExc_MemoryError,
3152 "unable to allocate password buffer");
3153 goto error;
3154 }
3155 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003156 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003157
3158 Py_XDECREF(password_bytes);
3159 return 1;
3160
3161error:
3162 Py_XDECREF(password_bytes);
3163 return 0;
3164}
3165
3166static int
3167_password_callback(char *buf, int size, int rwflag, void *userdata)
3168{
3169 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3170 PyObject *fn_ret = NULL;
3171
3172 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3173
3174 if (pw_info->callable) {
3175 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
3176 if (!fn_ret) {
3177 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3178 core python API, so we could use it to add a frame here */
3179 goto error;
3180 }
3181
3182 if (!_pwinfo_set(pw_info, fn_ret,
3183 "password callback must return a string")) {
3184 goto error;
3185 }
3186 Py_CLEAR(fn_ret);
3187 }
3188
3189 if (pw_info->size > size) {
3190 PyErr_Format(PyExc_ValueError,
3191 "password cannot be longer than %d bytes", size);
3192 goto error;
3193 }
3194
3195 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3196 memcpy(buf, pw_info->password, pw_info->size);
3197 return pw_info->size;
3198
3199error:
3200 Py_XDECREF(fn_ret);
3201 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3202 pw_info->error = 1;
3203 return -1;
3204}
3205
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003206/*[clinic input]
3207_ssl._SSLContext.load_cert_chain
3208 certfile: object
3209 keyfile: object = NULL
3210 password: object = NULL
3211
3212[clinic start generated code]*/
3213
Antoine Pitroub5218772010-05-21 09:56:06 +00003214static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003215_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3216 PyObject *keyfile, PyObject *password)
3217/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003218{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003219 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003220 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3221 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003222 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003223 int r;
3224
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003225 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003226 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003227 if (keyfile == Py_None)
3228 keyfile = NULL;
3229 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3230 PyErr_SetString(PyExc_TypeError,
3231 "certfile should be a valid filesystem path");
3232 return NULL;
3233 }
3234 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3235 PyErr_SetString(PyExc_TypeError,
3236 "keyfile should be a valid filesystem path");
3237 goto error;
3238 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003239 if (password && password != Py_None) {
3240 if (PyCallable_Check(password)) {
3241 pw_info.callable = password;
3242 } else if (!_pwinfo_set(&pw_info, password,
3243 "password should be a string or callable")) {
3244 goto error;
3245 }
3246 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3247 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3248 }
3249 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003250 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3251 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003252 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003253 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003254 if (pw_info.error) {
3255 ERR_clear_error();
3256 /* the password callback has already set the error information */
3257 }
3258 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003259 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003260 PyErr_SetFromErrno(PyExc_IOError);
3261 }
3262 else {
3263 _setSSLError(NULL, 0, __FILE__, __LINE__);
3264 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003265 goto error;
3266 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003267 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003268 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003269 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3270 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003271 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3272 Py_CLEAR(keyfile_bytes);
3273 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003274 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003275 if (pw_info.error) {
3276 ERR_clear_error();
3277 /* the password callback has already set the error information */
3278 }
3279 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003280 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003281 PyErr_SetFromErrno(PyExc_IOError);
3282 }
3283 else {
3284 _setSSLError(NULL, 0, __FILE__, __LINE__);
3285 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003286 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003287 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003288 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003289 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003290 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003291 if (r != 1) {
3292 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003293 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003294 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003295 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3296 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003297 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003298 Py_RETURN_NONE;
3299
3300error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003301 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3302 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003303 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003304 Py_XDECREF(keyfile_bytes);
3305 Py_XDECREF(certfile_bytes);
3306 return NULL;
3307}
3308
Christian Heimesefff7062013-11-21 03:35:02 +01003309/* internal helper function, returns -1 on error
3310 */
3311static int
3312_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3313 int filetype)
3314{
3315 BIO *biobuf = NULL;
3316 X509_STORE *store;
3317 int retval = 0, err, loaded = 0;
3318
3319 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3320
3321 if (len <= 0) {
3322 PyErr_SetString(PyExc_ValueError,
3323 "Empty certificate data");
3324 return -1;
3325 } else if (len > INT_MAX) {
3326 PyErr_SetString(PyExc_OverflowError,
3327 "Certificate data is too long.");
3328 return -1;
3329 }
3330
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003331 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003332 if (biobuf == NULL) {
3333 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3334 return -1;
3335 }
3336
3337 store = SSL_CTX_get_cert_store(self->ctx);
3338 assert(store != NULL);
3339
3340 while (1) {
3341 X509 *cert = NULL;
3342 int r;
3343
3344 if (filetype == SSL_FILETYPE_ASN1) {
3345 cert = d2i_X509_bio(biobuf, NULL);
3346 } else {
3347 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003348 SSL_CTX_get_default_passwd_cb(self->ctx),
3349 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3350 );
Christian Heimesefff7062013-11-21 03:35:02 +01003351 }
3352 if (cert == NULL) {
3353 break;
3354 }
3355 r = X509_STORE_add_cert(store, cert);
3356 X509_free(cert);
3357 if (!r) {
3358 err = ERR_peek_last_error();
3359 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3360 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3361 /* cert already in hash table, not an error */
3362 ERR_clear_error();
3363 } else {
3364 break;
3365 }
3366 }
3367 loaded++;
3368 }
3369
3370 err = ERR_peek_last_error();
3371 if ((filetype == SSL_FILETYPE_ASN1) &&
3372 (loaded > 0) &&
3373 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3374 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3375 /* EOF ASN1 file, not an error */
3376 ERR_clear_error();
3377 retval = 0;
3378 } else if ((filetype == SSL_FILETYPE_PEM) &&
3379 (loaded > 0) &&
3380 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3381 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3382 /* EOF PEM file, not an error */
3383 ERR_clear_error();
3384 retval = 0;
3385 } else {
3386 _setSSLError(NULL, 0, __FILE__, __LINE__);
3387 retval = -1;
3388 }
3389
3390 BIO_free(biobuf);
3391 return retval;
3392}
3393
3394
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003395/*[clinic input]
3396_ssl._SSLContext.load_verify_locations
3397 cafile: object = NULL
3398 capath: object = NULL
3399 cadata: object = NULL
3400
3401[clinic start generated code]*/
3402
Antoine Pitrou152efa22010-05-16 18:19:27 +00003403static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003404_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3405 PyObject *cafile,
3406 PyObject *capath,
3407 PyObject *cadata)
3408/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003409{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003410 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3411 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003412 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003413
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003414 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003415 if (cafile == Py_None)
3416 cafile = NULL;
3417 if (capath == Py_None)
3418 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003419 if (cadata == Py_None)
3420 cadata = NULL;
3421
3422 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003423 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003424 "cafile, capath and cadata cannot be all omitted");
3425 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003426 }
3427 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3428 PyErr_SetString(PyExc_TypeError,
3429 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003430 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003431 }
3432 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003433 PyErr_SetString(PyExc_TypeError,
3434 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003435 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003436 }
Christian Heimesefff7062013-11-21 03:35:02 +01003437
3438 /* validata cadata type and load cadata */
3439 if (cadata) {
3440 Py_buffer buf;
3441 PyObject *cadata_ascii = NULL;
3442
3443 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3444 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3445 PyBuffer_Release(&buf);
3446 PyErr_SetString(PyExc_TypeError,
3447 "cadata should be a contiguous buffer with "
3448 "a single dimension");
3449 goto error;
3450 }
3451 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3452 PyBuffer_Release(&buf);
3453 if (r == -1) {
3454 goto error;
3455 }
3456 } else {
3457 PyErr_Clear();
3458 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3459 if (cadata_ascii == NULL) {
3460 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003461 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003462 "bytes-like object");
3463 goto error;
3464 }
3465 r = _add_ca_certs(self,
3466 PyBytes_AS_STRING(cadata_ascii),
3467 PyBytes_GET_SIZE(cadata_ascii),
3468 SSL_FILETYPE_PEM);
3469 Py_DECREF(cadata_ascii);
3470 if (r == -1) {
3471 goto error;
3472 }
3473 }
3474 }
3475
3476 /* load cafile or capath */
3477 if (cafile || capath) {
3478 if (cafile)
3479 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3480 if (capath)
3481 capath_buf = PyBytes_AS_STRING(capath_bytes);
3482 PySSL_BEGIN_ALLOW_THREADS
3483 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3484 PySSL_END_ALLOW_THREADS
3485 if (r != 1) {
3486 ok = 0;
3487 if (errno != 0) {
3488 ERR_clear_error();
3489 PyErr_SetFromErrno(PyExc_IOError);
3490 }
3491 else {
3492 _setSSLError(NULL, 0, __FILE__, __LINE__);
3493 }
3494 goto error;
3495 }
3496 }
3497 goto end;
3498
3499 error:
3500 ok = 0;
3501 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003502 Py_XDECREF(cafile_bytes);
3503 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003504 if (ok) {
3505 Py_RETURN_NONE;
3506 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003507 return NULL;
3508 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003509}
3510
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003511/*[clinic input]
3512_ssl._SSLContext.load_dh_params
3513 path as filepath: object
3514 /
3515
3516[clinic start generated code]*/
3517
Antoine Pitrou152efa22010-05-16 18:19:27 +00003518static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003519_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3520/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003521{
3522 FILE *f;
3523 DH *dh;
3524
Victor Stinnerdaf45552013-08-28 00:53:59 +02003525 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003526 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003527 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003528
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003529 errno = 0;
3530 PySSL_BEGIN_ALLOW_THREADS
3531 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003532 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003533 PySSL_END_ALLOW_THREADS
3534 if (dh == NULL) {
3535 if (errno != 0) {
3536 ERR_clear_error();
3537 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3538 }
3539 else {
3540 _setSSLError(NULL, 0, __FILE__, __LINE__);
3541 }
3542 return NULL;
3543 }
3544 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3545 _setSSLError(NULL, 0, __FILE__, __LINE__);
3546 DH_free(dh);
3547 Py_RETURN_NONE;
3548}
3549
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003550/*[clinic input]
3551_ssl._SSLContext._wrap_socket
3552 sock: object(subclass_of="PySocketModule.Sock_Type")
3553 server_side: int
3554 server_hostname as hostname_obj: object = None
3555
3556[clinic start generated code]*/
3557
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003558static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003559_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3560 int server_side, PyObject *hostname_obj)
3561/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003562{
Antoine Pitroud5323212010-10-22 18:19:07 +00003563 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003564 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003565
Antoine Pitroud5323212010-10-22 18:19:07 +00003566 /* server_hostname is either None (or absent), or to be encoded
3567 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003568 if (hostname_obj != Py_None) {
3569 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003570 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003571 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003572
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003573 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3574 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003575 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003576 if (hostname != NULL)
3577 PyMem_Free(hostname);
3578 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003579}
3580
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003581/*[clinic input]
3582_ssl._SSLContext._wrap_bio
3583 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3584 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3585 server_side: int
3586 server_hostname as hostname_obj: object = None
3587
3588[clinic start generated code]*/
3589
Antoine Pitroub0182c82010-10-12 20:09:02 +00003590static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003591_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3592 PySSLMemoryBIO *outgoing, int server_side,
3593 PyObject *hostname_obj)
3594/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003595{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003596 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003597 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003598
3599 /* server_hostname is either None (or absent), or to be encoded
3600 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003601 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003602 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3603 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003604 }
3605
3606 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3607 incoming, outgoing);
3608
3609 PyMem_Free(hostname);
3610 return res;
3611}
3612
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003613/*[clinic input]
3614_ssl._SSLContext.session_stats
3615[clinic start generated code]*/
3616
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003617static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003618_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3619/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003620{
3621 int r;
3622 PyObject *value, *stats = PyDict_New();
3623 if (!stats)
3624 return NULL;
3625
3626#define ADD_STATS(SSL_NAME, KEY_NAME) \
3627 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3628 if (value == NULL) \
3629 goto error; \
3630 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3631 Py_DECREF(value); \
3632 if (r < 0) \
3633 goto error;
3634
3635 ADD_STATS(number, "number");
3636 ADD_STATS(connect, "connect");
3637 ADD_STATS(connect_good, "connect_good");
3638 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3639 ADD_STATS(accept, "accept");
3640 ADD_STATS(accept_good, "accept_good");
3641 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3642 ADD_STATS(accept, "accept");
3643 ADD_STATS(hits, "hits");
3644 ADD_STATS(misses, "misses");
3645 ADD_STATS(timeouts, "timeouts");
3646 ADD_STATS(cache_full, "cache_full");
3647
3648#undef ADD_STATS
3649
3650 return stats;
3651
3652error:
3653 Py_DECREF(stats);
3654 return NULL;
3655}
3656
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003657/*[clinic input]
3658_ssl._SSLContext.set_default_verify_paths
3659[clinic start generated code]*/
3660
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003661static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003662_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3663/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003664{
3665 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3666 _setSSLError(NULL, 0, __FILE__, __LINE__);
3667 return NULL;
3668 }
3669 Py_RETURN_NONE;
3670}
3671
Antoine Pitrou501da612011-12-21 09:27:41 +01003672#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003673/*[clinic input]
3674_ssl._SSLContext.set_ecdh_curve
3675 name: object
3676 /
3677
3678[clinic start generated code]*/
3679
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003680static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003681_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3682/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003683{
3684 PyObject *name_bytes;
3685 int nid;
3686 EC_KEY *key;
3687
3688 if (!PyUnicode_FSConverter(name, &name_bytes))
3689 return NULL;
3690 assert(PyBytes_Check(name_bytes));
3691 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3692 Py_DECREF(name_bytes);
3693 if (nid == 0) {
3694 PyErr_Format(PyExc_ValueError,
3695 "unknown elliptic curve name %R", name);
3696 return NULL;
3697 }
3698 key = EC_KEY_new_by_curve_name(nid);
3699 if (key == NULL) {
3700 _setSSLError(NULL, 0, __FILE__, __LINE__);
3701 return NULL;
3702 }
3703 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3704 EC_KEY_free(key);
3705 Py_RETURN_NONE;
3706}
Antoine Pitrou501da612011-12-21 09:27:41 +01003707#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003708
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003709#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003710static int
3711_servername_callback(SSL *s, int *al, void *args)
3712{
3713 int ret;
3714 PySSLContext *ssl_ctx = (PySSLContext *) args;
3715 PySSLSocket *ssl;
3716 PyObject *servername_o;
3717 PyObject *servername_idna;
3718 PyObject *result;
3719 /* The high-level ssl.SSLSocket object */
3720 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003721 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003722#ifdef WITH_THREAD
3723 PyGILState_STATE gstate = PyGILState_Ensure();
3724#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003725
3726 if (ssl_ctx->set_hostname == NULL) {
3727 /* remove race condition in this the call back while if removing the
3728 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003729#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003730 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003731#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003732 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003733 }
3734
3735 ssl = SSL_get_app_data(s);
3736 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003737
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003738 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003739 * SSL connection and that has a .context attribute that can be changed to
3740 * identify the requested hostname. Since the official API is the Python
3741 * level API we want to pass the callback a Python level object rather than
3742 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3743 * SSLObject) that will be passed. Otherwise if there's a socket then that
3744 * will be passed. If both do not exist only then the C-level object is
3745 * passed. */
3746 if (ssl->owner)
3747 ssl_socket = PyWeakref_GetObject(ssl->owner);
3748 else if (ssl->Socket)
3749 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3750 else
3751 ssl_socket = (PyObject *) ssl;
3752
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003753 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003754 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003755 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003756
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003757 if (servername == NULL) {
3758 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3759 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003760 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003761 else {
3762 servername_o = PyBytes_FromString(servername);
3763 if (servername_o == NULL) {
3764 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3765 goto error;
3766 }
3767 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3768 if (servername_idna == NULL) {
3769 PyErr_WriteUnraisable(servername_o);
3770 Py_DECREF(servername_o);
3771 goto error;
3772 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003773 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003774 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3775 servername_idna, ssl_ctx, NULL);
3776 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003777 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003778 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003779
3780 if (result == NULL) {
3781 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3782 *al = SSL_AD_HANDSHAKE_FAILURE;
3783 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3784 }
3785 else {
3786 if (result != Py_None) {
3787 *al = (int) PyLong_AsLong(result);
3788 if (PyErr_Occurred()) {
3789 PyErr_WriteUnraisable(result);
3790 *al = SSL_AD_INTERNAL_ERROR;
3791 }
3792 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3793 }
3794 else {
3795 ret = SSL_TLSEXT_ERR_OK;
3796 }
3797 Py_DECREF(result);
3798 }
3799
Stefan Krah20d60802013-01-17 17:07:17 +01003800#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003801 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003802#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003803 return ret;
3804
3805error:
3806 Py_DECREF(ssl_socket);
3807 *al = SSL_AD_INTERNAL_ERROR;
3808 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003809#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003810 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003811#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003812 return ret;
3813}
Antoine Pitroua5963382013-03-30 16:39:00 +01003814#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003815
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003816/*[clinic input]
3817_ssl._SSLContext.set_servername_callback
3818 method as cb: object
3819 /
3820
3821Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3822
3823If the argument is None then the callback is disabled. The method is called
3824with the SSLSocket, the server name as a string, and the SSLContext object.
3825See RFC 6066 for details of the SNI extension.
3826[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003827
3828static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003829_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3830/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003831{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003832#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003833 Py_CLEAR(self->set_hostname);
3834 if (cb == Py_None) {
3835 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3836 }
3837 else {
3838 if (!PyCallable_Check(cb)) {
3839 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3840 PyErr_SetString(PyExc_TypeError,
3841 "not a callable object");
3842 return NULL;
3843 }
3844 Py_INCREF(cb);
3845 self->set_hostname = cb;
3846 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3847 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3848 }
3849 Py_RETURN_NONE;
3850#else
3851 PyErr_SetString(PyExc_NotImplementedError,
3852 "The TLS extension servername callback, "
3853 "SSL_CTX_set_tlsext_servername_callback, "
3854 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003855 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003856#endif
3857}
3858
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003859/*[clinic input]
3860_ssl._SSLContext.cert_store_stats
3861
3862Returns quantities of loaded X.509 certificates.
3863
3864X.509 certificates with a CA extension and certificate revocation lists
3865inside the context's cert store.
3866
3867NOTE: Certificates in a capath directory aren't loaded unless they have
3868been used at least once.
3869[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003870
3871static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003872_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3873/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003874{
3875 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003876 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003877 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003878 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003879
3880 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003881 objs = X509_STORE_get0_objects(store);
3882 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3883 obj = sk_X509_OBJECT_value(objs, i);
3884 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003885 case X509_LU_X509:
3886 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003887 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003888 ca++;
3889 }
3890 break;
3891 case X509_LU_CRL:
3892 crl++;
3893 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003894 default:
3895 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3896 * As far as I can tell they are internal states and never
3897 * stored in a cert store */
3898 break;
3899 }
3900 }
3901 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3902 "x509_ca", ca);
3903}
3904
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003905/*[clinic input]
3906_ssl._SSLContext.get_ca_certs
3907 binary_form: bool = False
3908
3909Returns a list of dicts with information of loaded CA certs.
3910
3911If the optional argument is True, returns a DER-encoded copy of the CA
3912certificate.
3913
3914NOTE: Certificates in a capath directory aren't loaded unless they have
3915been used at least once.
3916[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003917
3918static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003919_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3920/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003921{
3922 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003923 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003924 PyObject *ci = NULL, *rlist = NULL;
3925 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003926
3927 if ((rlist = PyList_New(0)) == NULL) {
3928 return NULL;
3929 }
3930
3931 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003932 objs = X509_STORE_get0_objects(store);
3933 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003934 X509_OBJECT *obj;
3935 X509 *cert;
3936
Christian Heimes598894f2016-09-05 23:19:05 +02003937 obj = sk_X509_OBJECT_value(objs, i);
3938 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003939 /* not a x509 cert */
3940 continue;
3941 }
3942 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003943 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003944 if (!X509_check_ca(cert)) {
3945 continue;
3946 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003947 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003948 ci = _certificate_to_der(cert);
3949 } else {
3950 ci = _decode_certificate(cert);
3951 }
3952 if (ci == NULL) {
3953 goto error;
3954 }
3955 if (PyList_Append(rlist, ci) == -1) {
3956 goto error;
3957 }
3958 Py_CLEAR(ci);
3959 }
3960 return rlist;
3961
3962 error:
3963 Py_XDECREF(ci);
3964 Py_XDECREF(rlist);
3965 return NULL;
3966}
3967
3968
Antoine Pitrou152efa22010-05-16 18:19:27 +00003969static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003970 {"check_hostname", (getter) get_check_hostname,
3971 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003972 {"options", (getter) get_options,
3973 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003974 {"verify_flags", (getter) get_verify_flags,
3975 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003976 {"verify_mode", (getter) get_verify_mode,
3977 (setter) set_verify_mode, NULL},
3978 {NULL}, /* sentinel */
3979};
3980
3981static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003982 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
3983 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
3984 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
3985 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
3986 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
3987 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
3988 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
3989 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
3990 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
3991 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
3992 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
3993 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
3994 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
3995 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02003996 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00003997 {NULL, NULL} /* sentinel */
3998};
3999
4000static PyTypeObject PySSLContext_Type = {
4001 PyVarObject_HEAD_INIT(NULL, 0)
4002 "_ssl._SSLContext", /*tp_name*/
4003 sizeof(PySSLContext), /*tp_basicsize*/
4004 0, /*tp_itemsize*/
4005 (destructor)context_dealloc, /*tp_dealloc*/
4006 0, /*tp_print*/
4007 0, /*tp_getattr*/
4008 0, /*tp_setattr*/
4009 0, /*tp_reserved*/
4010 0, /*tp_repr*/
4011 0, /*tp_as_number*/
4012 0, /*tp_as_sequence*/
4013 0, /*tp_as_mapping*/
4014 0, /*tp_hash*/
4015 0, /*tp_call*/
4016 0, /*tp_str*/
4017 0, /*tp_getattro*/
4018 0, /*tp_setattro*/
4019 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004020 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004021 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004022 (traverseproc) context_traverse, /*tp_traverse*/
4023 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004024 0, /*tp_richcompare*/
4025 0, /*tp_weaklistoffset*/
4026 0, /*tp_iter*/
4027 0, /*tp_iternext*/
4028 context_methods, /*tp_methods*/
4029 0, /*tp_members*/
4030 context_getsetlist, /*tp_getset*/
4031 0, /*tp_base*/
4032 0, /*tp_dict*/
4033 0, /*tp_descr_get*/
4034 0, /*tp_descr_set*/
4035 0, /*tp_dictoffset*/
4036 0, /*tp_init*/
4037 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004038 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004039};
4040
4041
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004042/*
4043 * MemoryBIO objects
4044 */
4045
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004046/*[clinic input]
4047@classmethod
4048_ssl.MemoryBIO.__new__
4049
4050[clinic start generated code]*/
4051
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004052static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004053_ssl_MemoryBIO_impl(PyTypeObject *type)
4054/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004055{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004056 BIO *bio;
4057 PySSLMemoryBIO *self;
4058
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004059 bio = BIO_new(BIO_s_mem());
4060 if (bio == NULL) {
4061 PyErr_SetString(PySSLErrorObject,
4062 "failed to allocate BIO");
4063 return NULL;
4064 }
4065 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4066 * just that no data is currently available. The SSL routines should retry
4067 * the read, which we can achieve by calling BIO_set_retry_read(). */
4068 BIO_set_retry_read(bio);
4069 BIO_set_mem_eof_return(bio, -1);
4070
4071 assert(type != NULL && type->tp_alloc != NULL);
4072 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4073 if (self == NULL) {
4074 BIO_free(bio);
4075 return NULL;
4076 }
4077 self->bio = bio;
4078 self->eof_written = 0;
4079
4080 return (PyObject *) self;
4081}
4082
4083static void
4084memory_bio_dealloc(PySSLMemoryBIO *self)
4085{
4086 BIO_free(self->bio);
4087 Py_TYPE(self)->tp_free(self);
4088}
4089
4090static PyObject *
4091memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4092{
4093 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
4094}
4095
4096PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4097"The number of bytes pending in the memory BIO.");
4098
4099static PyObject *
4100memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4101{
4102 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4103 && self->eof_written);
4104}
4105
4106PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4107"Whether the memory BIO is at EOF.");
4108
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004109/*[clinic input]
4110_ssl.MemoryBIO.read
4111 size as len: int = -1
4112 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004113
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004114Read up to size bytes from the memory BIO.
4115
4116If size is not specified, read the entire buffer.
4117If the return value is an empty bytes instance, this means either
4118EOF or that no data is available. Use the "eof" property to
4119distinguish between the two.
4120[clinic start generated code]*/
4121
4122static PyObject *
4123_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4124/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4125{
4126 int avail, nbytes;
4127 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004128
4129 avail = BIO_ctrl_pending(self->bio);
4130 if ((len < 0) || (len > avail))
4131 len = avail;
4132
4133 result = PyBytes_FromStringAndSize(NULL, len);
4134 if ((result == NULL) || (len == 0))
4135 return result;
4136
4137 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4138 /* There should never be any short reads but check anyway. */
4139 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4140 Py_DECREF(result);
4141 return NULL;
4142 }
4143
4144 return result;
4145}
4146
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004147/*[clinic input]
4148_ssl.MemoryBIO.write
4149 b: Py_buffer
4150 /
4151
4152Writes the bytes b into the memory BIO.
4153
4154Returns the number of bytes written.
4155[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004156
4157static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004158_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4159/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004160{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004161 int nbytes;
4162
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004163 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004164 PyErr_Format(PyExc_OverflowError,
4165 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004166 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004167 }
4168
4169 if (self->eof_written) {
4170 PyErr_SetString(PySSLErrorObject,
4171 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004172 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004173 }
4174
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004175 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004176 if (nbytes < 0) {
4177 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004178 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004179 }
4180
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004181 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004182}
4183
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004184/*[clinic input]
4185_ssl.MemoryBIO.write_eof
4186
4187Write an EOF marker to the memory BIO.
4188
4189When all data has been read, the "eof" property will be True.
4190[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004191
4192static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004193_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4194/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004195{
4196 self->eof_written = 1;
4197 /* After an EOF is written, a zero return from read() should be a real EOF
4198 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4199 BIO_clear_retry_flags(self->bio);
4200 BIO_set_mem_eof_return(self->bio, 0);
4201
4202 Py_RETURN_NONE;
4203}
4204
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004205static PyGetSetDef memory_bio_getsetlist[] = {
4206 {"pending", (getter) memory_bio_get_pending, NULL,
4207 PySSL_memory_bio_pending_doc},
4208 {"eof", (getter) memory_bio_get_eof, NULL,
4209 PySSL_memory_bio_eof_doc},
4210 {NULL}, /* sentinel */
4211};
4212
4213static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004214 _SSL_MEMORYBIO_READ_METHODDEF
4215 _SSL_MEMORYBIO_WRITE_METHODDEF
4216 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004217 {NULL, NULL} /* sentinel */
4218};
4219
4220static PyTypeObject PySSLMemoryBIO_Type = {
4221 PyVarObject_HEAD_INIT(NULL, 0)
4222 "_ssl.MemoryBIO", /*tp_name*/
4223 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4224 0, /*tp_itemsize*/
4225 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4226 0, /*tp_print*/
4227 0, /*tp_getattr*/
4228 0, /*tp_setattr*/
4229 0, /*tp_reserved*/
4230 0, /*tp_repr*/
4231 0, /*tp_as_number*/
4232 0, /*tp_as_sequence*/
4233 0, /*tp_as_mapping*/
4234 0, /*tp_hash*/
4235 0, /*tp_call*/
4236 0, /*tp_str*/
4237 0, /*tp_getattro*/
4238 0, /*tp_setattro*/
4239 0, /*tp_as_buffer*/
4240 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4241 0, /*tp_doc*/
4242 0, /*tp_traverse*/
4243 0, /*tp_clear*/
4244 0, /*tp_richcompare*/
4245 0, /*tp_weaklistoffset*/
4246 0, /*tp_iter*/
4247 0, /*tp_iternext*/
4248 memory_bio_methods, /*tp_methods*/
4249 0, /*tp_members*/
4250 memory_bio_getsetlist, /*tp_getset*/
4251 0, /*tp_base*/
4252 0, /*tp_dict*/
4253 0, /*tp_descr_get*/
4254 0, /*tp_descr_set*/
4255 0, /*tp_dictoffset*/
4256 0, /*tp_init*/
4257 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004258 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004259};
4260
Antoine Pitrou152efa22010-05-16 18:19:27 +00004261
Christian Heimes99a65702016-09-10 23:44:53 +02004262/*
4263 * SSL Session object
4264 */
4265
4266static void
4267PySSLSession_dealloc(PySSLSession *self)
4268{
4269 Py_XDECREF(self->ctx);
4270 if (self->session != NULL) {
4271 SSL_SESSION_free(self->session);
4272 }
4273 PyObject_Del(self);
4274}
4275
4276static PyObject *
4277PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4278{
4279 int result;
4280
4281 if (left == NULL || right == NULL) {
4282 PyErr_BadInternalCall();
4283 return NULL;
4284 }
4285
4286 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4287 Py_RETURN_NOTIMPLEMENTED;
4288 }
4289
4290 if (left == right) {
4291 result = 0;
4292 } else {
4293 const unsigned char *left_id, *right_id;
4294 unsigned int left_len, right_len;
4295 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4296 &left_len);
4297 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4298 &right_len);
4299 if (left_len == right_len) {
4300 result = memcmp(left_id, right_id, left_len);
4301 } else {
4302 result = 1;
4303 }
4304 }
4305
4306 switch (op) {
4307 case Py_EQ:
4308 if (result == 0) {
4309 Py_RETURN_TRUE;
4310 } else {
4311 Py_RETURN_FALSE;
4312 }
4313 break;
4314 case Py_NE:
4315 if (result != 0) {
4316 Py_RETURN_TRUE;
4317 } else {
4318 Py_RETURN_FALSE;
4319 }
4320 break;
4321 case Py_LT:
4322 case Py_LE:
4323 case Py_GT:
4324 case Py_GE:
4325 Py_RETURN_NOTIMPLEMENTED;
4326 break;
4327 default:
4328 PyErr_BadArgument();
4329 return NULL;
4330 }
4331}
4332
4333static int
4334PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4335{
4336 Py_VISIT(self->ctx);
4337 return 0;
4338}
4339
4340static int
4341PySSLSession_clear(PySSLSession *self)
4342{
4343 Py_CLEAR(self->ctx);
4344 return 0;
4345}
4346
4347
4348static PyObject *
4349PySSLSession_get_time(PySSLSession *self, void *closure) {
4350 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4351}
4352
4353PyDoc_STRVAR(PySSLSession_get_time_doc,
4354"Session creation time (seconds since epoch).");
4355
4356
4357static PyObject *
4358PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4359 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4360}
4361
4362PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4363"Session timeout (delta in seconds).");
4364
4365
4366static PyObject *
4367PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4368 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4369 return PyLong_FromUnsignedLong(hint);
4370}
4371
4372PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4373"Ticket life time hint.");
4374
4375
4376static PyObject *
4377PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4378 const unsigned char *id;
4379 unsigned int len;
4380 id = SSL_SESSION_get_id(self->session, &len);
4381 return PyBytes_FromStringAndSize((const char *)id, len);
4382}
4383
4384PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4385"Session id");
4386
4387
4388static PyObject *
4389PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4390 if (SSL_SESSION_has_ticket(self->session)) {
4391 Py_RETURN_TRUE;
4392 } else {
4393 Py_RETURN_FALSE;
4394 }
4395}
4396
4397PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4398"Does the session contain a ticket?");
4399
4400
4401static PyGetSetDef PySSLSession_getsetlist[] = {
4402 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4403 PySSLSession_get_has_ticket_doc},
4404 {"id", (getter) PySSLSession_get_session_id, NULL,
4405 PySSLSession_get_session_id_doc},
4406 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4407 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4408 {"time", (getter) PySSLSession_get_time, NULL,
4409 PySSLSession_get_time_doc},
4410 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4411 PySSLSession_get_timeout_doc},
4412 {NULL}, /* sentinel */
4413};
4414
4415static PyTypeObject PySSLSession_Type = {
4416 PyVarObject_HEAD_INIT(NULL, 0)
4417 "_ssl.Session", /*tp_name*/
4418 sizeof(PySSLSession), /*tp_basicsize*/
4419 0, /*tp_itemsize*/
4420 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4421 0, /*tp_print*/
4422 0, /*tp_getattr*/
4423 0, /*tp_setattr*/
4424 0, /*tp_reserved*/
4425 0, /*tp_repr*/
4426 0, /*tp_as_number*/
4427 0, /*tp_as_sequence*/
4428 0, /*tp_as_mapping*/
4429 0, /*tp_hash*/
4430 0, /*tp_call*/
4431 0, /*tp_str*/
4432 0, /*tp_getattro*/
4433 0, /*tp_setattro*/
4434 0, /*tp_as_buffer*/
4435 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4436 0, /*tp_doc*/
4437 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4438 (inquiry)PySSLSession_clear, /*tp_clear*/
4439 PySSLSession_richcompare, /*tp_richcompare*/
4440 0, /*tp_weaklistoffset*/
4441 0, /*tp_iter*/
4442 0, /*tp_iternext*/
4443 0, /*tp_methods*/
4444 0, /*tp_members*/
4445 PySSLSession_getsetlist, /*tp_getset*/
4446};
4447
4448
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004449/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004450/*[clinic input]
4451_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004452 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004453 entropy: double
4454 /
4455
4456Mix string into the OpenSSL PRNG state.
4457
4458entropy (a float) is a lower bound on the entropy contained in
4459string. See RFC 1750.
4460[clinic start generated code]*/
4461
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004462static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004463_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
4464/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004465{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004466 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004467 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004468
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004469 buf = (const char *)view->buf;
4470 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004471 do {
4472 written = Py_MIN(len, INT_MAX);
4473 RAND_add(buf, (int)written, entropy);
4474 buf += written;
4475 len -= written;
4476 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004477 Py_INCREF(Py_None);
4478 return Py_None;
4479}
4480
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004481static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004482PySSL_RAND(int len, int pseudo)
4483{
4484 int ok;
4485 PyObject *bytes;
4486 unsigned long err;
4487 const char *errstr;
4488 PyObject *v;
4489
Victor Stinner1e81a392013-12-19 16:47:04 +01004490 if (len < 0) {
4491 PyErr_SetString(PyExc_ValueError, "num must be positive");
4492 return NULL;
4493 }
4494
Victor Stinner99c8b162011-05-24 12:05:19 +02004495 bytes = PyBytes_FromStringAndSize(NULL, len);
4496 if (bytes == NULL)
4497 return NULL;
4498 if (pseudo) {
4499 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4500 if (ok == 0 || ok == 1)
4501 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4502 }
4503 else {
4504 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4505 if (ok == 1)
4506 return bytes;
4507 }
4508 Py_DECREF(bytes);
4509
4510 err = ERR_get_error();
4511 errstr = ERR_reason_error_string(err);
4512 v = Py_BuildValue("(ks)", err, errstr);
4513 if (v != NULL) {
4514 PyErr_SetObject(PySSLErrorObject, v);
4515 Py_DECREF(v);
4516 }
4517 return NULL;
4518}
4519
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004520/*[clinic input]
4521_ssl.RAND_bytes
4522 n: int
4523 /
4524
4525Generate n cryptographically strong pseudo-random bytes.
4526[clinic start generated code]*/
4527
Victor Stinner99c8b162011-05-24 12:05:19 +02004528static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004529_ssl_RAND_bytes_impl(PyObject *module, int n)
4530/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004531{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004532 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004533}
4534
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004535/*[clinic input]
4536_ssl.RAND_pseudo_bytes
4537 n: int
4538 /
4539
4540Generate n pseudo-random bytes.
4541
4542Return a pair (bytes, is_cryptographic). is_cryptographic is True
4543if the bytes generated are cryptographically strong.
4544[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004545
4546static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004547_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4548/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004549{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004550 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004551}
4552
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004553/*[clinic input]
4554_ssl.RAND_status
4555
4556Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4557
4558It is necessary to seed the PRNG with RAND_add() on some platforms before
4559using the ssl() function.
4560[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004561
4562static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004563_ssl_RAND_status_impl(PyObject *module)
4564/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004565{
Christian Heimes217cfd12007-12-02 14:31:20 +00004566 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004567}
4568
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004569#ifndef OPENSSL_NO_EGD
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004570/*[clinic input]
4571_ssl.RAND_egd
4572 path: object(converter="PyUnicode_FSConverter")
4573 /
4574
4575Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4576
4577Returns number of bytes read. Raises SSLError if connection to EGD
4578fails or if it does not provide enough data to seed PRNG.
4579[clinic start generated code]*/
4580
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004581static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004582_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4583/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004584{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004585 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004586 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004587 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004588 PyErr_SetString(PySSLErrorObject,
4589 "EGD connection failed or EGD did not return "
4590 "enough data to seed the PRNG");
4591 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004592 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004593 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004594}
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004595#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004596
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004597
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004598
4599/*[clinic input]
4600_ssl.get_default_verify_paths
4601
4602Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4603
4604The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4605[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004606
4607static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004608_ssl_get_default_verify_paths_impl(PyObject *module)
4609/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004610{
4611 PyObject *ofile_env = NULL;
4612 PyObject *ofile = NULL;
4613 PyObject *odir_env = NULL;
4614 PyObject *odir = NULL;
4615
Benjamin Petersond113c962015-07-18 10:59:13 -07004616#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004617 const char *tmp = (info); \
4618 target = NULL; \
4619 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4620 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4621 target = PyBytes_FromString(tmp); } \
4622 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004623 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004624
Benjamin Petersond113c962015-07-18 10:59:13 -07004625 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4626 CONVERT(X509_get_default_cert_file(), ofile);
4627 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4628 CONVERT(X509_get_default_cert_dir(), odir);
4629#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004630
Christian Heimes200bb1b2013-06-14 15:14:29 +02004631 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004632
4633 error:
4634 Py_XDECREF(ofile_env);
4635 Py_XDECREF(ofile);
4636 Py_XDECREF(odir_env);
4637 Py_XDECREF(odir);
4638 return NULL;
4639}
4640
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004641static PyObject*
4642asn1obj2py(ASN1_OBJECT *obj)
4643{
4644 int nid;
4645 const char *ln, *sn;
4646 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004647 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004648
4649 nid = OBJ_obj2nid(obj);
4650 if (nid == NID_undef) {
4651 PyErr_Format(PyExc_ValueError, "Unknown object");
4652 return NULL;
4653 }
4654 sn = OBJ_nid2sn(nid);
4655 ln = OBJ_nid2ln(nid);
4656 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4657 if (buflen < 0) {
4658 _setSSLError(NULL, 0, __FILE__, __LINE__);
4659 return NULL;
4660 }
4661 if (buflen) {
4662 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4663 } else {
4664 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4665 }
4666}
4667
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004668/*[clinic input]
4669_ssl.txt2obj
4670 txt: str
4671 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004672
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004673Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4674
4675By default objects are looked up by OID. With name=True short and
4676long name are also matched.
4677[clinic start generated code]*/
4678
4679static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004680_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4681/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004682{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004683 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004684 ASN1_OBJECT *obj;
4685
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004686 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4687 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004688 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004689 return NULL;
4690 }
4691 result = asn1obj2py(obj);
4692 ASN1_OBJECT_free(obj);
4693 return result;
4694}
4695
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004696/*[clinic input]
4697_ssl.nid2obj
4698 nid: int
4699 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004700
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004701Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4702[clinic start generated code]*/
4703
4704static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004705_ssl_nid2obj_impl(PyObject *module, int nid)
4706/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004707{
4708 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004709 ASN1_OBJECT *obj;
4710
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004711 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004712 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004713 return NULL;
4714 }
4715 obj = OBJ_nid2obj(nid);
4716 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004717 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004718 return NULL;
4719 }
4720 result = asn1obj2py(obj);
4721 ASN1_OBJECT_free(obj);
4722 return result;
4723}
4724
Christian Heimes46bebee2013-06-09 19:03:31 +02004725#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004726
4727static PyObject*
4728certEncodingType(DWORD encodingType)
4729{
4730 static PyObject *x509_asn = NULL;
4731 static PyObject *pkcs_7_asn = NULL;
4732
4733 if (x509_asn == NULL) {
4734 x509_asn = PyUnicode_InternFromString("x509_asn");
4735 if (x509_asn == NULL)
4736 return NULL;
4737 }
4738 if (pkcs_7_asn == NULL) {
4739 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4740 if (pkcs_7_asn == NULL)
4741 return NULL;
4742 }
4743 switch(encodingType) {
4744 case X509_ASN_ENCODING:
4745 Py_INCREF(x509_asn);
4746 return x509_asn;
4747 case PKCS_7_ASN_ENCODING:
4748 Py_INCREF(pkcs_7_asn);
4749 return pkcs_7_asn;
4750 default:
4751 return PyLong_FromLong(encodingType);
4752 }
4753}
4754
4755static PyObject*
4756parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4757{
4758 CERT_ENHKEY_USAGE *usage;
4759 DWORD size, error, i;
4760 PyObject *retval;
4761
4762 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4763 error = GetLastError();
4764 if (error == CRYPT_E_NOT_FOUND) {
4765 Py_RETURN_TRUE;
4766 }
4767 return PyErr_SetFromWindowsErr(error);
4768 }
4769
4770 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4771 if (usage == NULL) {
4772 return PyErr_NoMemory();
4773 }
4774
4775 /* Now get the actual enhanced usage property */
4776 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4777 PyMem_Free(usage);
4778 error = GetLastError();
4779 if (error == CRYPT_E_NOT_FOUND) {
4780 Py_RETURN_TRUE;
4781 }
4782 return PyErr_SetFromWindowsErr(error);
4783 }
4784 retval = PySet_New(NULL);
4785 if (retval == NULL) {
4786 goto error;
4787 }
4788 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4789 if (usage->rgpszUsageIdentifier[i]) {
4790 PyObject *oid;
4791 int err;
4792 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4793 if (oid == NULL) {
4794 Py_CLEAR(retval);
4795 goto error;
4796 }
4797 err = PySet_Add(retval, oid);
4798 Py_DECREF(oid);
4799 if (err == -1) {
4800 Py_CLEAR(retval);
4801 goto error;
4802 }
4803 }
4804 }
4805 error:
4806 PyMem_Free(usage);
4807 return retval;
4808}
4809
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004810/*[clinic input]
4811_ssl.enum_certificates
4812 store_name: str
4813
4814Retrieve certificates from Windows' cert store.
4815
4816store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4817more cert storages, too. The function returns a list of (bytes,
4818encoding_type, trust) tuples. The encoding_type flag can be interpreted
4819with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4820a set of OIDs or the boolean True.
4821[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004822
Christian Heimes46bebee2013-06-09 19:03:31 +02004823static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004824_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4825/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004826{
Christian Heimes46bebee2013-06-09 19:03:31 +02004827 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004828 PCCERT_CONTEXT pCertCtx = NULL;
4829 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004830 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004831
Christian Heimes44109d72013-11-22 01:51:30 +01004832 result = PyList_New(0);
4833 if (result == NULL) {
4834 return NULL;
4835 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004836 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4837 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4838 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004839 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004840 Py_DECREF(result);
4841 return PyErr_SetFromWindowsErr(GetLastError());
4842 }
4843
Christian Heimes44109d72013-11-22 01:51:30 +01004844 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4845 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4846 pCertCtx->cbCertEncoded);
4847 if (!cert) {
4848 Py_CLEAR(result);
4849 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004850 }
Christian Heimes44109d72013-11-22 01:51:30 +01004851 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4852 Py_CLEAR(result);
4853 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004854 }
Christian Heimes44109d72013-11-22 01:51:30 +01004855 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4856 if (keyusage == Py_True) {
4857 Py_DECREF(keyusage);
4858 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004859 }
Christian Heimes44109d72013-11-22 01:51:30 +01004860 if (keyusage == NULL) {
4861 Py_CLEAR(result);
4862 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004863 }
Christian Heimes44109d72013-11-22 01:51:30 +01004864 if ((tup = PyTuple_New(3)) == NULL) {
4865 Py_CLEAR(result);
4866 break;
4867 }
4868 PyTuple_SET_ITEM(tup, 0, cert);
4869 cert = NULL;
4870 PyTuple_SET_ITEM(tup, 1, enc);
4871 enc = NULL;
4872 PyTuple_SET_ITEM(tup, 2, keyusage);
4873 keyusage = NULL;
4874 if (PyList_Append(result, tup) < 0) {
4875 Py_CLEAR(result);
4876 break;
4877 }
4878 Py_CLEAR(tup);
4879 }
4880 if (pCertCtx) {
4881 /* loop ended with an error, need to clean up context manually */
4882 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004883 }
4884
4885 /* In error cases cert, enc and tup may not be NULL */
4886 Py_XDECREF(cert);
4887 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004888 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004889 Py_XDECREF(tup);
4890
4891 if (!CertCloseStore(hStore, 0)) {
4892 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004893 Py_XDECREF(result);
4894 return PyErr_SetFromWindowsErr(GetLastError());
4895 }
4896 return result;
4897}
4898
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004899/*[clinic input]
4900_ssl.enum_crls
4901 store_name: str
4902
4903Retrieve CRLs from Windows' cert store.
4904
4905store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4906more cert storages, too. The function returns a list of (bytes,
4907encoding_type) tuples. The encoding_type flag can be interpreted with
4908X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4909[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004910
4911static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004912_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4913/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004914{
Christian Heimes44109d72013-11-22 01:51:30 +01004915 HCERTSTORE hStore = NULL;
4916 PCCRL_CONTEXT pCrlCtx = NULL;
4917 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4918 PyObject *result = NULL;
4919
Christian Heimes44109d72013-11-22 01:51:30 +01004920 result = PyList_New(0);
4921 if (result == NULL) {
4922 return NULL;
4923 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004924 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4925 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4926 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004927 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004928 Py_DECREF(result);
4929 return PyErr_SetFromWindowsErr(GetLastError());
4930 }
Christian Heimes44109d72013-11-22 01:51:30 +01004931
4932 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4933 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4934 pCrlCtx->cbCrlEncoded);
4935 if (!crl) {
4936 Py_CLEAR(result);
4937 break;
4938 }
4939 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4940 Py_CLEAR(result);
4941 break;
4942 }
4943 if ((tup = PyTuple_New(2)) == NULL) {
4944 Py_CLEAR(result);
4945 break;
4946 }
4947 PyTuple_SET_ITEM(tup, 0, crl);
4948 crl = NULL;
4949 PyTuple_SET_ITEM(tup, 1, enc);
4950 enc = NULL;
4951
4952 if (PyList_Append(result, tup) < 0) {
4953 Py_CLEAR(result);
4954 break;
4955 }
4956 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004957 }
Christian Heimes44109d72013-11-22 01:51:30 +01004958 if (pCrlCtx) {
4959 /* loop ended with an error, need to clean up context manually */
4960 CertFreeCRLContext(pCrlCtx);
4961 }
4962
4963 /* In error cases cert, enc and tup may not be NULL */
4964 Py_XDECREF(crl);
4965 Py_XDECREF(enc);
4966 Py_XDECREF(tup);
4967
4968 if (!CertCloseStore(hStore, 0)) {
4969 /* This error case might shadow another exception.*/
4970 Py_XDECREF(result);
4971 return PyErr_SetFromWindowsErr(GetLastError());
4972 }
4973 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004974}
Christian Heimes44109d72013-11-22 01:51:30 +01004975
4976#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004977
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004978/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004979static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004980 _SSL__TEST_DECODE_CERT_METHODDEF
4981 _SSL_RAND_ADD_METHODDEF
4982 _SSL_RAND_BYTES_METHODDEF
4983 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4984 _SSL_RAND_EGD_METHODDEF
4985 _SSL_RAND_STATUS_METHODDEF
4986 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
4987 _SSL_ENUM_CERTIFICATES_METHODDEF
4988 _SSL_ENUM_CRLS_METHODDEF
4989 _SSL_TXT2OBJ_METHODDEF
4990 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004991 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004992};
4993
4994
Christian Heimes598894f2016-09-05 23:19:05 +02004995#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004996
4997/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02004998 * of the Python C thread library
4999 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5000 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005001
5002static PyThread_type_lock *_ssl_locks = NULL;
5003
Christian Heimes4d98ca92013-08-19 17:36:29 +02005004#if OPENSSL_VERSION_NUMBER >= 0x10000000
5005/* use new CRYPTO_THREADID API. */
5006static void
5007_ssl_threadid_callback(CRYPTO_THREADID *id)
5008{
5009 CRYPTO_THREADID_set_numeric(id,
5010 (unsigned long)PyThread_get_thread_ident());
5011}
5012#else
5013/* deprecated CRYPTO_set_id_callback() API. */
5014static unsigned long
5015_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005016 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005017}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005018#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005019
Bill Janssen6e027db2007-11-15 22:23:56 +00005020static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005021 (int mode, int n, const char *file, int line) {
5022 /* this function is needed to perform locking on shared data
5023 structures. (Note that OpenSSL uses a number of global data
5024 structures that will be implicitly shared whenever multiple
5025 threads use OpenSSL.) Multi-threaded applications will
5026 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005027
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005028 locking_function() must be able to handle up to
5029 CRYPTO_num_locks() different mutex locks. It sets the n-th
5030 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005031
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005032 file and line are the file number of the function setting the
5033 lock. They can be useful for debugging.
5034 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005035
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005036 if ((_ssl_locks == NULL) ||
5037 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5038 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005039
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005040 if (mode & CRYPTO_LOCK) {
5041 PyThread_acquire_lock(_ssl_locks[n], 1);
5042 } else {
5043 PyThread_release_lock(_ssl_locks[n]);
5044 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005045}
5046
5047static int _setup_ssl_threads(void) {
5048
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005049 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005050
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005051 if (_ssl_locks == NULL) {
5052 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005053 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
5054 if (_ssl_locks == NULL) {
5055 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005056 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005057 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005058 memset(_ssl_locks, 0,
5059 sizeof(PyThread_type_lock) * _ssl_locks_count);
5060 for (i = 0; i < _ssl_locks_count; i++) {
5061 _ssl_locks[i] = PyThread_allocate_lock();
5062 if (_ssl_locks[i] == NULL) {
5063 unsigned int j;
5064 for (j = 0; j < i; j++) {
5065 PyThread_free_lock(_ssl_locks[j]);
5066 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005067 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005068 return 0;
5069 }
5070 }
5071 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005072#if OPENSSL_VERSION_NUMBER >= 0x10000000
5073 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5074#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005075 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005076#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005077 }
5078 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005079}
5080
Christian Heimes598894f2016-09-05 23:19:05 +02005081#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005082
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005083PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005084"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005085for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005086
Martin v. Löwis1a214512008-06-11 05:26:20 +00005087
5088static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005089 PyModuleDef_HEAD_INIT,
5090 "_ssl",
5091 module_doc,
5092 -1,
5093 PySSL_methods,
5094 NULL,
5095 NULL,
5096 NULL,
5097 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005098};
5099
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005100
5101static void
5102parse_openssl_version(unsigned long libver,
5103 unsigned int *major, unsigned int *minor,
5104 unsigned int *fix, unsigned int *patch,
5105 unsigned int *status)
5106{
5107 *status = libver & 0xF;
5108 libver >>= 4;
5109 *patch = libver & 0xFF;
5110 libver >>= 8;
5111 *fix = libver & 0xFF;
5112 libver >>= 8;
5113 *minor = libver & 0xFF;
5114 libver >>= 8;
5115 *major = libver & 0xFF;
5116}
5117
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005118PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005119PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005120{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005121 PyObject *m, *d, *r;
5122 unsigned long libver;
5123 unsigned int major, minor, fix, patch, status;
5124 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005125 struct py_ssl_error_code *errcode;
5126 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005127
Antoine Pitrou152efa22010-05-16 18:19:27 +00005128 if (PyType_Ready(&PySSLContext_Type) < 0)
5129 return NULL;
5130 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005131 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005132 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5133 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005134 if (PyType_Ready(&PySSLSession_Type) < 0)
5135 return NULL;
5136
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005137
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005138 m = PyModule_Create(&_sslmodule);
5139 if (m == NULL)
5140 return NULL;
5141 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005142
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005143 /* Load _socket module and its C API */
5144 socket_api = PySocketModule_ImportModuleAndAPI();
5145 if (!socket_api)
5146 return NULL;
5147 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005148
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005149 /* Init OpenSSL */
5150 SSL_load_error_strings();
5151 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005152#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02005153#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005154 /* note that this will start threading if not already started */
5155 if (!_setup_ssl_threads()) {
5156 return NULL;
5157 }
Christian Heimes598894f2016-09-05 23:19:05 +02005158#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5159 /* OpenSSL 1.1.0 builtin thread support is enabled */
5160 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005161#endif
Christian Heimes598894f2016-09-05 23:19:05 +02005162#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005163 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005164
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005165 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005166 sslerror_type_slots[0].pfunc = PyExc_OSError;
5167 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005168 if (PySSLErrorObject == NULL)
5169 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005170
Antoine Pitrou41032a62011-10-27 23:56:55 +02005171 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5172 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5173 PySSLErrorObject, NULL);
5174 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5175 "ssl.SSLWantReadError", SSLWantReadError_doc,
5176 PySSLErrorObject, NULL);
5177 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5178 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5179 PySSLErrorObject, NULL);
5180 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5181 "ssl.SSLSyscallError", SSLSyscallError_doc,
5182 PySSLErrorObject, NULL);
5183 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5184 "ssl.SSLEOFError", SSLEOFError_doc,
5185 PySSLErrorObject, NULL);
5186 if (PySSLZeroReturnErrorObject == NULL
5187 || PySSLWantReadErrorObject == NULL
5188 || PySSLWantWriteErrorObject == NULL
5189 || PySSLSyscallErrorObject == NULL
5190 || PySSLEOFErrorObject == NULL)
5191 return NULL;
5192 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5193 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5194 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5195 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5196 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5197 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005198 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005199 if (PyDict_SetItemString(d, "_SSLContext",
5200 (PyObject *)&PySSLContext_Type) != 0)
5201 return NULL;
5202 if (PyDict_SetItemString(d, "_SSLSocket",
5203 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005204 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005205 if (PyDict_SetItemString(d, "MemoryBIO",
5206 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5207 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005208 if (PyDict_SetItemString(d, "SSLSession",
5209 (PyObject *)&PySSLSession_Type) != 0)
5210 return NULL;
5211
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005212 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5213 PY_SSL_ERROR_ZERO_RETURN);
5214 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5215 PY_SSL_ERROR_WANT_READ);
5216 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5217 PY_SSL_ERROR_WANT_WRITE);
5218 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5219 PY_SSL_ERROR_WANT_X509_LOOKUP);
5220 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5221 PY_SSL_ERROR_SYSCALL);
5222 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5223 PY_SSL_ERROR_SSL);
5224 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5225 PY_SSL_ERROR_WANT_CONNECT);
5226 /* non ssl.h errorcodes */
5227 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5228 PY_SSL_ERROR_EOF);
5229 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5230 PY_SSL_ERROR_INVALID_ERROR_CODE);
5231 /* cert requirements */
5232 PyModule_AddIntConstant(m, "CERT_NONE",
5233 PY_SSL_CERT_NONE);
5234 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5235 PY_SSL_CERT_OPTIONAL);
5236 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5237 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005238 /* CRL verification for verification_flags */
5239 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5240 0);
5241 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5242 X509_V_FLAG_CRL_CHECK);
5243 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5244 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5245 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5246 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005247#ifdef X509_V_FLAG_TRUSTED_FIRST
5248 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5249 X509_V_FLAG_TRUSTED_FIRST);
5250#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005251
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005252 /* Alert Descriptions from ssl.h */
5253 /* note RESERVED constants no longer intended for use have been removed */
5254 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5255
5256#define ADD_AD_CONSTANT(s) \
5257 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5258 SSL_AD_##s)
5259
5260 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5261 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5262 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5263 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5264 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5265 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5266 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5267 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5268 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5269 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5270 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5271 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5272 ADD_AD_CONSTANT(UNKNOWN_CA);
5273 ADD_AD_CONSTANT(ACCESS_DENIED);
5274 ADD_AD_CONSTANT(DECODE_ERROR);
5275 ADD_AD_CONSTANT(DECRYPT_ERROR);
5276 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5277 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5278 ADD_AD_CONSTANT(INTERNAL_ERROR);
5279 ADD_AD_CONSTANT(USER_CANCELLED);
5280 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005281 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005282#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5283 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5284#endif
5285#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5286 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5287#endif
5288#ifdef SSL_AD_UNRECOGNIZED_NAME
5289 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5290#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005291#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5292 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5293#endif
5294#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5295 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5296#endif
5297#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5298 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5299#endif
5300
5301#undef ADD_AD_CONSTANT
5302
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005303 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005304#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005305 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5306 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005307#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005308#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005309 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5310 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005311#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005312 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005313 PY_SSL_VERSION_TLS);
5314 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5315 PY_SSL_VERSION_TLS);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005316 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5317 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005318#if HAVE_TLSv1_2
5319 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5320 PY_SSL_VERSION_TLS1_1);
5321 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5322 PY_SSL_VERSION_TLS1_2);
5323#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005324
Antoine Pitroub5218772010-05-21 09:56:06 +00005325 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005326 PyModule_AddIntConstant(m, "OP_ALL",
5327 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005328 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5329 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5330 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005331#if HAVE_TLSv1_2
5332 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5333 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5334#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005335 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5336 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005337 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005338 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005339#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005340 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005341#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005342#ifdef SSL_OP_NO_COMPRESSION
5343 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5344 SSL_OP_NO_COMPRESSION);
5345#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005346
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005347#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005348 r = Py_True;
5349#else
5350 r = Py_False;
5351#endif
5352 Py_INCREF(r);
5353 PyModule_AddObject(m, "HAS_SNI", r);
5354
Antoine Pitroud6494802011-07-21 01:11:30 +02005355 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005356 Py_INCREF(r);
5357 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5358
Antoine Pitrou501da612011-12-21 09:27:41 +01005359#ifdef OPENSSL_NO_ECDH
5360 r = Py_False;
5361#else
5362 r = Py_True;
5363#endif
5364 Py_INCREF(r);
5365 PyModule_AddObject(m, "HAS_ECDH", r);
5366
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005367#ifdef OPENSSL_NPN_NEGOTIATED
5368 r = Py_True;
5369#else
5370 r = Py_False;
5371#endif
5372 Py_INCREF(r);
5373 PyModule_AddObject(m, "HAS_NPN", r);
5374
Benjamin Petersoncca27322015-01-23 16:35:37 -05005375#ifdef HAVE_ALPN
5376 r = Py_True;
5377#else
5378 r = Py_False;
5379#endif
5380 Py_INCREF(r);
5381 PyModule_AddObject(m, "HAS_ALPN", r);
5382
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005383 /* Mappings for error codes */
5384 err_codes_to_names = PyDict_New();
5385 err_names_to_codes = PyDict_New();
5386 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5387 return NULL;
5388 errcode = error_codes;
5389 while (errcode->mnemonic != NULL) {
5390 PyObject *mnemo, *key;
5391 mnemo = PyUnicode_FromString(errcode->mnemonic);
5392 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5393 if (mnemo == NULL || key == NULL)
5394 return NULL;
5395 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5396 return NULL;
5397 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5398 return NULL;
5399 Py_DECREF(key);
5400 Py_DECREF(mnemo);
5401 errcode++;
5402 }
5403 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5404 return NULL;
5405 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5406 return NULL;
5407
5408 lib_codes_to_names = PyDict_New();
5409 if (lib_codes_to_names == NULL)
5410 return NULL;
5411 libcode = library_codes;
5412 while (libcode->library != NULL) {
5413 PyObject *mnemo, *key;
5414 key = PyLong_FromLong(libcode->code);
5415 mnemo = PyUnicode_FromString(libcode->library);
5416 if (key == NULL || mnemo == NULL)
5417 return NULL;
5418 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5419 return NULL;
5420 Py_DECREF(key);
5421 Py_DECREF(mnemo);
5422 libcode++;
5423 }
5424 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5425 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005426
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005427 /* OpenSSL version */
5428 /* SSLeay() gives us the version of the library linked against,
5429 which could be different from the headers version.
5430 */
5431 libver = SSLeay();
5432 r = PyLong_FromUnsignedLong(libver);
5433 if (r == NULL)
5434 return NULL;
5435 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5436 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005437 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005438 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5439 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5440 return NULL;
5441 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5442 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5443 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005444
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005445 libver = OPENSSL_VERSION_NUMBER;
5446 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5447 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5448 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5449 return NULL;
5450
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005451 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005452}