blob: fe19195366af91268d317dcaa916268fbc1c80bf [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}
154
155static const char *COMP_get_name(const COMP_METHOD *meth)
156{
157 return meth->name;
158}
159#endif
160
161static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
162{
163 return ctx->default_passwd_callback;
164}
165
166static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
167{
168 return ctx->default_passwd_callback_userdata;
169}
170
171static int X509_OBJECT_get_type(X509_OBJECT *x)
172{
173 return x->type;
174}
175
176static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
177{
178 return x->data.x509;
179}
180
181static int BIO_up_ref(BIO *b)
182{
183 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
184 return 1;
185}
186
187static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
188 return store->objs;
189}
190
191static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
192{
193 return store->param;
194}
195#endif /* OpenSSL < 1.1.0 or LibreSSL */
196
197
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000198enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000199 /* these mirror ssl.h */
200 PY_SSL_ERROR_NONE,
201 PY_SSL_ERROR_SSL,
202 PY_SSL_ERROR_WANT_READ,
203 PY_SSL_ERROR_WANT_WRITE,
204 PY_SSL_ERROR_WANT_X509_LOOKUP,
205 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
206 PY_SSL_ERROR_ZERO_RETURN,
207 PY_SSL_ERROR_WANT_CONNECT,
208 /* start of non ssl.h errorcodes */
209 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
210 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
211 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000212};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000213
Thomas Woutersed03b412007-08-28 21:37:11 +0000214enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000215 PY_SSL_CLIENT,
216 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000217};
218
219enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000220 PY_SSL_CERT_NONE,
221 PY_SSL_CERT_OPTIONAL,
222 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000223};
224
225enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000226 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200227 PY_SSL_VERSION_SSL3=1,
Christian Heimes598894f2016-09-05 23:19:05 +0200228 PY_SSL_VERSION_TLS,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100229#if HAVE_TLSv1_2
230 PY_SSL_VERSION_TLS1,
231 PY_SSL_VERSION_TLS1_1,
232 PY_SSL_VERSION_TLS1_2
233#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000234 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000235#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100236};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200237
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000238#ifdef WITH_THREAD
239
240/* serves as a flag to see whether we've initialized the SSL thread support. */
241/* 0 means no, greater than 0 means yes */
242
243static unsigned int _ssl_locks_count = 0;
244
245#endif /* def WITH_THREAD */
246
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000247/* SSL socket object */
248
249#define X509_NAME_MAXLEN 256
250
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000251/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
252 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
253 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
254#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000255# define HAVE_SSL_CTX_CLEAR_OPTIONS
256#else
257# undef HAVE_SSL_CTX_CLEAR_OPTIONS
258#endif
259
Antoine Pitroud6494802011-07-21 01:11:30 +0200260/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
261 * older SSL, but let's be safe */
262#define PySSL_CB_MAXLEN 128
263
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100264
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000265typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000266 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000267 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100268#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -0500269 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100270 int npn_protocols_len;
271#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500272#ifdef HAVE_ALPN
273 unsigned char *alpn_protocols;
274 int alpn_protocols_len;
275#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100276#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200277 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100278#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100279 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000280} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000281
Antoine Pitrou152efa22010-05-16 18:19:27 +0000282typedef struct {
283 PyObject_HEAD
284 PyObject *Socket; /* weakref to socket on which we're layered */
285 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100286 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000287 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200288 char shutdown_seen_zero;
289 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200290 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200291 PyObject *owner; /* Python level "owner" passed to servername callback */
292 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000293} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000294
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200295typedef struct {
296 PyObject_HEAD
297 BIO *bio;
298 int eof_written;
299} PySSLMemoryBIO;
300
Antoine Pitrou152efa22010-05-16 18:19:27 +0000301static PyTypeObject PySSLContext_Type;
302static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200303static PyTypeObject PySSLMemoryBIO_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000304
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300305/*[clinic input]
306module _ssl
307class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
308class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
309class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
310[clinic start generated code]*/
311/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7bf7cb832638e2e1]*/
312
313#include "clinic/_ssl.c.h"
314
Victor Stinner14690702015-04-06 22:46:13 +0200315static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000316
Antoine Pitrou152efa22010-05-16 18:19:27 +0000317#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
318#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200319#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000320
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000321typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000322 SOCKET_IS_NONBLOCKING,
323 SOCKET_IS_BLOCKING,
324 SOCKET_HAS_TIMED_OUT,
325 SOCKET_HAS_BEEN_CLOSED,
326 SOCKET_TOO_LARGE_FOR_SELECT,
327 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000328} timeout_state;
329
Thomas Woutersed03b412007-08-28 21:37:11 +0000330/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000331#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200332#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000333
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200334/* Get the socket from a PySSLSocket, if it has one */
335#define GET_SOCKET(obj) ((obj)->Socket ? \
336 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200337
Victor Stinner14690702015-04-06 22:46:13 +0200338/* If sock is NULL, use a timeout of 0 second */
339#define GET_SOCKET_TIMEOUT(sock) \
340 ((sock != NULL) ? (sock)->sock_timeout : 0)
341
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200342/*
343 * SSL errors.
344 */
345
346PyDoc_STRVAR(SSLError_doc,
347"An error occurred in the SSL implementation.");
348
349PyDoc_STRVAR(SSLZeroReturnError_doc,
350"SSL/TLS session closed cleanly.");
351
352PyDoc_STRVAR(SSLWantReadError_doc,
353"Non-blocking SSL socket needs to read more data\n"
354"before the requested operation can be completed.");
355
356PyDoc_STRVAR(SSLWantWriteError_doc,
357"Non-blocking SSL socket needs to write more data\n"
358"before the requested operation can be completed.");
359
360PyDoc_STRVAR(SSLSyscallError_doc,
361"System error when attempting SSL operation.");
362
363PyDoc_STRVAR(SSLEOFError_doc,
364"SSL/TLS connection terminated abruptly.");
365
366static PyObject *
367SSLError_str(PyOSErrorObject *self)
368{
369 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
370 Py_INCREF(self->strerror);
371 return self->strerror;
372 }
373 else
374 return PyObject_Str(self->args);
375}
376
377static PyType_Slot sslerror_type_slots[] = {
378 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
379 {Py_tp_doc, SSLError_doc},
380 {Py_tp_str, SSLError_str},
381 {0, 0},
382};
383
384static PyType_Spec sslerror_type_spec = {
385 "ssl.SSLError",
386 sizeof(PyOSErrorObject),
387 0,
388 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
389 sslerror_type_slots
390};
391
392static void
393fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
394 int lineno, unsigned long errcode)
395{
396 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
397 PyObject *init_value, *msg, *key;
398 _Py_IDENTIFIER(reason);
399 _Py_IDENTIFIER(library);
400
401 if (errcode != 0) {
402 int lib, reason;
403
404 lib = ERR_GET_LIB(errcode);
405 reason = ERR_GET_REASON(errcode);
406 key = Py_BuildValue("ii", lib, reason);
407 if (key == NULL)
408 goto fail;
409 reason_obj = PyDict_GetItem(err_codes_to_names, key);
410 Py_DECREF(key);
411 if (reason_obj == NULL) {
412 /* XXX if reason < 100, it might reflect a library number (!!) */
413 PyErr_Clear();
414 }
415 key = PyLong_FromLong(lib);
416 if (key == NULL)
417 goto fail;
418 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
419 Py_DECREF(key);
420 if (lib_obj == NULL) {
421 PyErr_Clear();
422 }
423 if (errstr == NULL)
424 errstr = ERR_reason_error_string(errcode);
425 }
426 if (errstr == NULL)
427 errstr = "unknown error";
428
429 if (reason_obj && lib_obj)
430 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
431 lib_obj, reason_obj, errstr, lineno);
432 else if (lib_obj)
433 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
434 lib_obj, errstr, lineno);
435 else
436 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200437 if (msg == NULL)
438 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100439
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200440 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100441 if (init_value == NULL)
442 goto fail;
443
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200444 err_value = PyObject_CallObject(type, init_value);
445 Py_DECREF(init_value);
446 if (err_value == NULL)
447 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100448
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200449 if (reason_obj == NULL)
450 reason_obj = Py_None;
451 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
452 goto fail;
453 if (lib_obj == NULL)
454 lib_obj = Py_None;
455 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
456 goto fail;
457 PyErr_SetObject(type, err_value);
458fail:
459 Py_XDECREF(err_value);
460}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000461
462static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200463PySSL_SetError(PySSLSocket *obj, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000464{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200465 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200466 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000467 int err;
468 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200469 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000470
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000471 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200472 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000473
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000474 if (obj->ssl != NULL) {
475 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000476
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000477 switch (err) {
478 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200479 errstr = "TLS/SSL connection has been closed (EOF)";
480 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000481 p = PY_SSL_ERROR_ZERO_RETURN;
482 break;
483 case SSL_ERROR_WANT_READ:
484 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200485 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000486 p = PY_SSL_ERROR_WANT_READ;
487 break;
488 case SSL_ERROR_WANT_WRITE:
489 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200490 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000491 errstr = "The operation did not complete (write)";
492 break;
493 case SSL_ERROR_WANT_X509_LOOKUP:
494 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000495 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000496 break;
497 case SSL_ERROR_WANT_CONNECT:
498 p = PY_SSL_ERROR_WANT_CONNECT;
499 errstr = "The operation did not complete (connect)";
500 break;
501 case SSL_ERROR_SYSCALL:
502 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000503 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200504 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000505 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000506 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200507 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000508 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200509 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000510 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000511 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000512 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200513 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000514 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200515 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000516 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000517 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200518 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000519 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000520 }
521 } else {
522 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000523 }
524 break;
525 }
526 case SSL_ERROR_SSL:
527 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000528 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200529 if (e == 0)
530 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000531 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000532 break;
533 }
534 default:
535 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
536 errstr = "Invalid error code";
537 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000538 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200539 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000540 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000541 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000542}
543
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000544static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200545_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000546
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200547 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000548 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200549 else
550 errcode = 0;
551 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000552 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000553 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000554}
555
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200556/*
557 * SSL objects
558 */
559
Antoine Pitrou152efa22010-05-16 18:19:27 +0000560static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100561newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000562 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200563 char *server_hostname,
564 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000565{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000566 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100567 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200568 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000569
Antoine Pitrou152efa22010-05-16 18:19:27 +0000570 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000571 if (self == NULL)
572 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000573
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000574 self->peer_cert = NULL;
575 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000576 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100577 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200578 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200579 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200580 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700581 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200582 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700583 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
584 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200585 if (hostname == NULL) {
586 Py_DECREF(self);
587 return NULL;
588 }
589 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700590 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200591
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100592 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000593
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000594 /* Make sure the SSL error state is initialized */
595 (void) ERR_get_state();
596 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000597
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000598 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000599 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000600 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200601 SSL_set_app_data(self->ssl, self);
602 if (sock) {
603 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
604 } else {
605 /* BIOs are reference counted and SSL_set_bio borrows our reference.
606 * To prevent a double free in memory_bio_dealloc() we need to take an
607 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200608 BIO_up_ref(inbio->bio);
609 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200610 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
611 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200612 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000613#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200614 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000615#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200616 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000617
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100618#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000619 if (server_hostname != NULL)
620 SSL_set_tlsext_host_name(self->ssl, server_hostname);
621#endif
622
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000623 /* If the socket is in non-blocking mode or timeout mode, set the BIO
624 * to non-blocking mode (blocking is the default)
625 */
Victor Stinnere2452312015-03-28 03:00:46 +0100626 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000627 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
628 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
629 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000630
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000631 PySSL_BEGIN_ALLOW_THREADS
632 if (socket_type == PY_SSL_CLIENT)
633 SSL_set_connect_state(self->ssl);
634 else
635 SSL_set_accept_state(self->ssl);
636 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000637
Antoine Pitroud6494802011-07-21 01:11:30 +0200638 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200639 if (sock != NULL) {
640 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
641 if (self->Socket == NULL) {
642 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200643 return NULL;
644 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100645 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000646 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000647}
648
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000649/* SSL object methods */
650
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300651/*[clinic input]
652_ssl._SSLSocket.do_handshake
653[clinic start generated code]*/
654
655static PyObject *
656_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
657/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000658{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000659 int ret;
660 int err;
661 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200662 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200663 _PyTime_t timeout, deadline = 0;
664 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000665
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200666 if (sock) {
667 if (((PyObject*)sock) == Py_None) {
668 _setSSLError("Underlying socket connection gone",
669 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
670 return NULL;
671 }
672 Py_INCREF(sock);
673
674 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100675 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200676 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
677 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000678 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000679
Victor Stinner14690702015-04-06 22:46:13 +0200680 timeout = GET_SOCKET_TIMEOUT(sock);
681 has_timeout = (timeout > 0);
682 if (has_timeout)
683 deadline = _PyTime_GetMonotonicClock() + timeout;
684
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000685 /* Actually negotiate SSL connection */
686 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000687 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000688 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000689 ret = SSL_do_handshake(self->ssl);
690 err = SSL_get_error(self->ssl, ret);
691 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200692
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000693 if (PyErr_CheckSignals())
694 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200695
Victor Stinner14690702015-04-06 22:46:13 +0200696 if (has_timeout)
697 timeout = deadline - _PyTime_GetMonotonicClock();
698
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000699 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200700 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000701 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200702 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000703 } else {
704 sockstate = SOCKET_OPERATION_OK;
705 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200706
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000708 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000709 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000710 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000711 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
712 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000713 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000714 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000715 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
716 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000717 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000718 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000719 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
720 break;
721 }
722 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200723 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000724 if (ret < 1)
725 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000726
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000727 if (self->peer_cert)
728 X509_free (self->peer_cert);
729 PySSL_BEGIN_ALLOW_THREADS
730 self->peer_cert = SSL_get_peer_certificate(self->ssl);
731 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200732 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000733
734 Py_INCREF(Py_None);
735 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000736
737error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200738 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000739 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000740}
741
Thomas Woutersed03b412007-08-28 21:37:11 +0000742static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000743_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000744
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 char namebuf[X509_NAME_MAXLEN];
746 int buflen;
747 PyObject *name_obj;
748 PyObject *value_obj;
749 PyObject *attr;
750 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000751
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000752 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
753 if (buflen < 0) {
754 _setSSLError(NULL, 0, __FILE__, __LINE__);
755 goto fail;
756 }
757 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
758 if (name_obj == NULL)
759 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000760
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000761 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
762 if (buflen < 0) {
763 _setSSLError(NULL, 0, __FILE__, __LINE__);
764 Py_DECREF(name_obj);
765 goto fail;
766 }
767 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000768 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 OPENSSL_free(valuebuf);
770 if (value_obj == NULL) {
771 Py_DECREF(name_obj);
772 goto fail;
773 }
774 attr = PyTuple_New(2);
775 if (attr == NULL) {
776 Py_DECREF(name_obj);
777 Py_DECREF(value_obj);
778 goto fail;
779 }
780 PyTuple_SET_ITEM(attr, 0, name_obj);
781 PyTuple_SET_ITEM(attr, 1, value_obj);
782 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000783
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000784 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000786}
787
788static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000789_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000790{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000791 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
792 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
793 PyObject *rdnt;
794 PyObject *attr = NULL; /* tuple to hold an attribute */
795 int entry_count = X509_NAME_entry_count(xname);
796 X509_NAME_ENTRY *entry;
797 ASN1_OBJECT *name;
798 ASN1_STRING *value;
799 int index_counter;
800 int rdn_level = -1;
801 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 dn = PyList_New(0);
804 if (dn == NULL)
805 return NULL;
806 /* now create another tuple to hold the top-level RDN */
807 rdn = PyList_New(0);
808 if (rdn == NULL)
809 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000811 for (index_counter = 0;
812 index_counter < entry_count;
813 index_counter++)
814 {
815 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000816
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000817 /* check to see if we've gotten to a new RDN */
818 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200819 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000820 /* yes, new RDN */
821 /* add old RDN to DN */
822 rdnt = PyList_AsTuple(rdn);
823 Py_DECREF(rdn);
824 if (rdnt == NULL)
825 goto fail0;
826 retcode = PyList_Append(dn, rdnt);
827 Py_DECREF(rdnt);
828 if (retcode < 0)
829 goto fail0;
830 /* create new RDN */
831 rdn = PyList_New(0);
832 if (rdn == NULL)
833 goto fail0;
834 }
835 }
Christian Heimes598894f2016-09-05 23:19:05 +0200836 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000837
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 /* now add this attribute to the current RDN */
839 name = X509_NAME_ENTRY_get_object(entry);
840 value = X509_NAME_ENTRY_get_data(entry);
841 attr = _create_tuple_for_attribute(name, value);
842 /*
843 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
844 entry->set,
845 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
846 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
847 */
848 if (attr == NULL)
849 goto fail1;
850 retcode = PyList_Append(rdn, attr);
851 Py_DECREF(attr);
852 if (retcode < 0)
853 goto fail1;
854 }
855 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100856 if (rdn != NULL) {
857 if (PyList_GET_SIZE(rdn) > 0) {
858 rdnt = PyList_AsTuple(rdn);
859 Py_DECREF(rdn);
860 if (rdnt == NULL)
861 goto fail0;
862 retcode = PyList_Append(dn, rdnt);
863 Py_DECREF(rdnt);
864 if (retcode < 0)
865 goto fail0;
866 }
867 else {
868 Py_DECREF(rdn);
869 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000870 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000871
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000872 /* convert list to tuple */
873 rdnt = PyList_AsTuple(dn);
874 Py_DECREF(dn);
875 if (rdnt == NULL)
876 return NULL;
877 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000878
879 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000880 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000881
882 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000883 Py_XDECREF(dn);
884 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000885}
886
887static PyObject *
888_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000889
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000890 /* this code follows the procedure outlined in
891 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
892 function to extract the STACK_OF(GENERAL_NAME),
893 then iterates through the stack to add the
894 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000895
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 int i, j;
897 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200898 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000899 X509_EXTENSION *ext = NULL;
900 GENERAL_NAMES *names = NULL;
901 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000902 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000903 BIO *biobuf = NULL;
904 char buf[2048];
905 char *vptr;
906 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000907 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000908
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000909 if (certificate == NULL)
910 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000912 /* get a memory buffer */
913 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000914
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200915 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000916 while ((i = X509_get_ext_by_NID(
917 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000918
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000919 if (peer_alt_names == Py_None) {
920 peer_alt_names = PyList_New(0);
921 if (peer_alt_names == NULL)
922 goto fail;
923 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000924
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000925 /* now decode the altName */
926 ext = X509_get_ext(certificate, i);
927 if(!(method = X509V3_EXT_get(ext))) {
928 PyErr_SetString
929 (PySSLErrorObject,
930 ERRSTR("No method for internalizing subjectAltName!"));
931 goto fail;
932 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000933
Christian Heimes598894f2016-09-05 23:19:05 +0200934 p = X509_EXTENSION_get_data(ext)->data;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 if (method->it)
936 names = (GENERAL_NAMES*)
937 (ASN1_item_d2i(NULL,
938 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200939 X509_EXTENSION_get_data(ext)->length,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 ASN1_ITEM_ptr(method->it)));
941 else
942 names = (GENERAL_NAMES*)
943 (method->d2i(NULL,
944 &p,
Christian Heimes598894f2016-09-05 23:19:05 +0200945 X509_EXTENSION_get_data(ext)->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000946
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000947 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200949 int gntype;
950 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000951
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000952 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200953 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200954 switch (gntype) {
955 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000956 /* we special-case DirName as a tuple of
957 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000958
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 t = PyTuple_New(2);
960 if (t == NULL) {
961 goto fail;
962 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000963
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000964 v = PyUnicode_FromString("DirName");
965 if (v == NULL) {
966 Py_DECREF(t);
967 goto fail;
968 }
969 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000970
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000971 v = _create_tuple_for_X509_NAME (name->d.dirn);
972 if (v == NULL) {
973 Py_DECREF(t);
974 goto fail;
975 }
976 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200977 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000978
Christian Heimes824f7f32013-08-17 00:54:47 +0200979 case GEN_EMAIL:
980 case GEN_DNS:
981 case GEN_URI:
982 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
983 correctly, CVE-2013-4238 */
984 t = PyTuple_New(2);
985 if (t == NULL)
986 goto fail;
987 switch (gntype) {
988 case GEN_EMAIL:
989 v = PyUnicode_FromString("email");
990 as = name->d.rfc822Name;
991 break;
992 case GEN_DNS:
993 v = PyUnicode_FromString("DNS");
994 as = name->d.dNSName;
995 break;
996 case GEN_URI:
997 v = PyUnicode_FromString("URI");
998 as = name->d.uniformResourceIdentifier;
999 break;
1000 }
1001 if (v == NULL) {
1002 Py_DECREF(t);
1003 goto fail;
1004 }
1005 PyTuple_SET_ITEM(t, 0, v);
1006 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1007 ASN1_STRING_length(as));
1008 if (v == NULL) {
1009 Py_DECREF(t);
1010 goto fail;
1011 }
1012 PyTuple_SET_ITEM(t, 1, v);
1013 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001014
Christian Heimes824f7f32013-08-17 00:54:47 +02001015 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001016 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001017 switch (gntype) {
1018 /* check for new general name type */
1019 case GEN_OTHERNAME:
1020 case GEN_X400:
1021 case GEN_EDIPARTY:
1022 case GEN_IPADD:
1023 case GEN_RID:
1024 break;
1025 default:
1026 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1027 "Unknown general name type %d",
1028 gntype) == -1) {
1029 goto fail;
1030 }
1031 break;
1032 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001033 (void) BIO_reset(biobuf);
1034 GENERAL_NAME_print(biobuf, name);
1035 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1036 if (len < 0) {
1037 _setSSLError(NULL, 0, __FILE__, __LINE__);
1038 goto fail;
1039 }
1040 vptr = strchr(buf, ':');
1041 if (vptr == NULL)
1042 goto fail;
1043 t = PyTuple_New(2);
1044 if (t == NULL)
1045 goto fail;
1046 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1047 if (v == NULL) {
1048 Py_DECREF(t);
1049 goto fail;
1050 }
1051 PyTuple_SET_ITEM(t, 0, v);
1052 v = PyUnicode_FromStringAndSize((vptr + 1),
1053 (len - (vptr - buf + 1)));
1054 if (v == NULL) {
1055 Py_DECREF(t);
1056 goto fail;
1057 }
1058 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001059 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001060 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001061
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001062 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001063
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001064 if (PyList_Append(peer_alt_names, t) < 0) {
1065 Py_DECREF(t);
1066 goto fail;
1067 }
1068 Py_DECREF(t);
1069 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001070 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001071 }
1072 BIO_free(biobuf);
1073 if (peer_alt_names != Py_None) {
1074 v = PyList_AsTuple(peer_alt_names);
1075 Py_DECREF(peer_alt_names);
1076 return v;
1077 } else {
1078 return peer_alt_names;
1079 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001080
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001081
1082 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001083 if (biobuf != NULL)
1084 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001085
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001086 if (peer_alt_names != Py_None) {
1087 Py_XDECREF(peer_alt_names);
1088 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001089
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001090 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001091}
1092
1093static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001094_get_aia_uri(X509 *certificate, int nid) {
1095 PyObject *lst = NULL, *ostr = NULL;
1096 int i, result;
1097 AUTHORITY_INFO_ACCESS *info;
1098
1099 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001100 if (info == NULL)
1101 return Py_None;
1102 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1103 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001104 return Py_None;
1105 }
1106
1107 if ((lst = PyList_New(0)) == NULL) {
1108 goto fail;
1109 }
1110
1111 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1112 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1113 ASN1_IA5STRING *uri;
1114
1115 if ((OBJ_obj2nid(ad->method) != nid) ||
1116 (ad->location->type != GEN_URI)) {
1117 continue;
1118 }
1119 uri = ad->location->d.uniformResourceIdentifier;
1120 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1121 uri->length);
1122 if (ostr == NULL) {
1123 goto fail;
1124 }
1125 result = PyList_Append(lst, ostr);
1126 Py_DECREF(ostr);
1127 if (result < 0) {
1128 goto fail;
1129 }
1130 }
1131 AUTHORITY_INFO_ACCESS_free(info);
1132
1133 /* convert to tuple or None */
1134 if (PyList_Size(lst) == 0) {
1135 Py_DECREF(lst);
1136 return Py_None;
1137 } else {
1138 PyObject *tup;
1139 tup = PyList_AsTuple(lst);
1140 Py_DECREF(lst);
1141 return tup;
1142 }
1143
1144 fail:
1145 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001146 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001147 return NULL;
1148}
1149
1150static PyObject *
1151_get_crl_dp(X509 *certificate) {
1152 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001153 int i, j;
1154 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001155
Christian Heimes598894f2016-09-05 23:19:05 +02001156#if OPENSSL_VERSION_NUMBER >= 0x10001000L
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001157 /* Calls x509v3_cache_extensions and sets up crldp */
1158 X509_check_ca(certificate);
Christian Heimes949ec142013-11-21 16:26:51 +01001159#endif
Christian Heimes598894f2016-09-05 23:19:05 +02001160 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001161
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001162 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001163 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001164
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001165 lst = PyList_New(0);
1166 if (lst == NULL)
1167 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001168
1169 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1170 DIST_POINT *dp;
1171 STACK_OF(GENERAL_NAME) *gns;
1172
1173 dp = sk_DIST_POINT_value(dps, i);
1174 gns = dp->distpoint->name.fullname;
1175
1176 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1177 GENERAL_NAME *gn;
1178 ASN1_IA5STRING *uri;
1179 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001180 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001181
1182 gn = sk_GENERAL_NAME_value(gns, j);
1183 if (gn->type != GEN_URI) {
1184 continue;
1185 }
1186 uri = gn->d.uniformResourceIdentifier;
1187 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1188 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001189 if (ouri == NULL)
1190 goto done;
1191
1192 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001193 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001194 if (err < 0)
1195 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001196 }
1197 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001198
1199 /* Convert to tuple. */
1200 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1201
1202 done:
1203 Py_XDECREF(lst);
1204#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Peterson806fb252015-11-14 00:09:22 -08001205 sk_DIST_POINT_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001206#endif
1207 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001208}
1209
1210static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001211_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001212
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001213 PyObject *retval = NULL;
1214 BIO *biobuf = NULL;
1215 PyObject *peer;
1216 PyObject *peer_alt_names = NULL;
1217 PyObject *issuer;
1218 PyObject *version;
1219 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001220 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001221 ASN1_INTEGER *serialNumber;
1222 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001223 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001224 ASN1_TIME *notBefore, *notAfter;
1225 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001226
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001227 retval = PyDict_New();
1228 if (retval == NULL)
1229 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001230
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001231 peer = _create_tuple_for_X509_NAME(
1232 X509_get_subject_name(certificate));
1233 if (peer == NULL)
1234 goto fail0;
1235 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1236 Py_DECREF(peer);
1237 goto fail0;
1238 }
1239 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001240
Antoine Pitroufb046912010-11-09 20:21:19 +00001241 issuer = _create_tuple_for_X509_NAME(
1242 X509_get_issuer_name(certificate));
1243 if (issuer == NULL)
1244 goto fail0;
1245 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001246 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001247 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001248 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001249 Py_DECREF(issuer);
1250
1251 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001252 if (version == NULL)
1253 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001254 if (PyDict_SetItemString(retval, "version", version) < 0) {
1255 Py_DECREF(version);
1256 goto fail0;
1257 }
1258 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001259
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001260 /* get a memory buffer */
1261 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001262
Antoine Pitroufb046912010-11-09 20:21:19 +00001263 (void) BIO_reset(biobuf);
1264 serialNumber = X509_get_serialNumber(certificate);
1265 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1266 i2a_ASN1_INTEGER(biobuf, serialNumber);
1267 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1268 if (len < 0) {
1269 _setSSLError(NULL, 0, __FILE__, __LINE__);
1270 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001271 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001272 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1273 if (sn_obj == NULL)
1274 goto fail1;
1275 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1276 Py_DECREF(sn_obj);
1277 goto fail1;
1278 }
1279 Py_DECREF(sn_obj);
1280
1281 (void) BIO_reset(biobuf);
1282 notBefore = X509_get_notBefore(certificate);
1283 ASN1_TIME_print(biobuf, notBefore);
1284 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1285 if (len < 0) {
1286 _setSSLError(NULL, 0, __FILE__, __LINE__);
1287 goto fail1;
1288 }
1289 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1290 if (pnotBefore == NULL)
1291 goto fail1;
1292 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1293 Py_DECREF(pnotBefore);
1294 goto fail1;
1295 }
1296 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001297
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001298 (void) BIO_reset(biobuf);
1299 notAfter = X509_get_notAfter(certificate);
1300 ASN1_TIME_print(biobuf, notAfter);
1301 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1302 if (len < 0) {
1303 _setSSLError(NULL, 0, __FILE__, __LINE__);
1304 goto fail1;
1305 }
1306 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1307 if (pnotAfter == NULL)
1308 goto fail1;
1309 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1310 Py_DECREF(pnotAfter);
1311 goto fail1;
1312 }
1313 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001314
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001315 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001316
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001317 peer_alt_names = _get_peer_alt_names(certificate);
1318 if (peer_alt_names == NULL)
1319 goto fail1;
1320 else if (peer_alt_names != Py_None) {
1321 if (PyDict_SetItemString(retval, "subjectAltName",
1322 peer_alt_names) < 0) {
1323 Py_DECREF(peer_alt_names);
1324 goto fail1;
1325 }
1326 Py_DECREF(peer_alt_names);
1327 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001328
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001329 /* Authority Information Access: OCSP URIs */
1330 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1331 if (obj == NULL) {
1332 goto fail1;
1333 } else if (obj != Py_None) {
1334 result = PyDict_SetItemString(retval, "OCSP", obj);
1335 Py_DECREF(obj);
1336 if (result < 0) {
1337 goto fail1;
1338 }
1339 }
1340
1341 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1342 if (obj == NULL) {
1343 goto fail1;
1344 } else if (obj != Py_None) {
1345 result = PyDict_SetItemString(retval, "caIssuers", obj);
1346 Py_DECREF(obj);
1347 if (result < 0) {
1348 goto fail1;
1349 }
1350 }
1351
1352 /* CDP (CRL distribution points) */
1353 obj = _get_crl_dp(certificate);
1354 if (obj == NULL) {
1355 goto fail1;
1356 } else if (obj != Py_None) {
1357 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1358 Py_DECREF(obj);
1359 if (result < 0) {
1360 goto fail1;
1361 }
1362 }
1363
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 BIO_free(biobuf);
1365 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001366
1367 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 if (biobuf != NULL)
1369 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001370 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001371 Py_XDECREF(retval);
1372 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001373}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001374
Christian Heimes9a5395a2013-06-17 15:44:12 +02001375static PyObject *
1376_certificate_to_der(X509 *certificate)
1377{
1378 unsigned char *bytes_buf = NULL;
1379 int len;
1380 PyObject *retval;
1381
1382 bytes_buf = NULL;
1383 len = i2d_X509(certificate, &bytes_buf);
1384 if (len < 0) {
1385 _setSSLError(NULL, 0, __FILE__, __LINE__);
1386 return NULL;
1387 }
1388 /* this is actually an immutable bytes sequence */
1389 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1390 OPENSSL_free(bytes_buf);
1391 return retval;
1392}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001393
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001394/*[clinic input]
1395_ssl._test_decode_cert
1396 path: object(converter="PyUnicode_FSConverter")
1397 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001398
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001399[clinic start generated code]*/
1400
1401static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001402_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1403/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001404{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001405 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001406 X509 *x=NULL;
1407 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001408
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001409 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1410 PyErr_SetString(PySSLErrorObject,
1411 "Can't malloc memory to read file");
1412 goto fail0;
1413 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001414
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001415 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001416 PyErr_SetString(PySSLErrorObject,
1417 "Can't open file");
1418 goto fail0;
1419 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001420
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001421 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1422 if (x == NULL) {
1423 PyErr_SetString(PySSLErrorObject,
1424 "Error decoding PEM-encoded file");
1425 goto fail0;
1426 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001427
Antoine Pitroufb046912010-11-09 20:21:19 +00001428 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001429 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001430
1431 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001432 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001433 if (cert != NULL) BIO_free(cert);
1434 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001435}
1436
1437
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001438/*[clinic input]
1439_ssl._SSLSocket.peer_certificate
1440 der as binary_mode: bool = False
1441 /
1442
1443Returns the certificate for the peer.
1444
1445If no certificate was provided, returns None. If a certificate was
1446provided, but not validated, returns an empty dictionary. Otherwise
1447returns a dict containing information about the peer certificate.
1448
1449If the optional argument is True, returns a DER-encoded copy of the
1450peer certificate, or None if no certificate was provided. This will
1451return the certificate even if it wasn't validated.
1452[clinic start generated code]*/
1453
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001454static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001455_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1456/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001457{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001458 int verification;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001459
Antoine Pitrou20b85552013-09-29 19:50:53 +02001460 if (!self->handshake_done) {
1461 PyErr_SetString(PyExc_ValueError,
1462 "handshake not done yet");
1463 return NULL;
1464 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001465 if (!self->peer_cert)
1466 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001467
Antoine Pitrou721738f2012-08-15 23:20:39 +02001468 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001469 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001470 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001471 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001472 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001473 if ((verification & SSL_VERIFY_PEER) == 0)
1474 return PyDict_New();
1475 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001476 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001477 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001478}
1479
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001480static PyObject *
1481cipher_to_tuple(const SSL_CIPHER *cipher)
1482{
1483 const char *cipher_name, *cipher_protocol;
1484 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001485 if (retval == NULL)
1486 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001487
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001488 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001489 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001490 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001491 PyTuple_SET_ITEM(retval, 0, Py_None);
1492 } else {
1493 v = PyUnicode_FromString(cipher_name);
1494 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001495 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001496 PyTuple_SET_ITEM(retval, 0, v);
1497 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001498
1499 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001500 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001501 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001502 PyTuple_SET_ITEM(retval, 1, Py_None);
1503 } else {
1504 v = PyUnicode_FromString(cipher_protocol);
1505 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001506 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001507 PyTuple_SET_ITEM(retval, 1, v);
1508 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001509
1510 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001511 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001512 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001513 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001514
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001515 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001516
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001517 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001518 Py_DECREF(retval);
1519 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001520}
1521
Christian Heimes25bfcd52016-09-06 00:04:45 +02001522#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1523static PyObject *
1524cipher_to_dict(const SSL_CIPHER *cipher)
1525{
1526 const char *cipher_name, *cipher_protocol;
1527
1528 unsigned long cipher_id;
1529 int alg_bits, strength_bits, len;
1530 char buf[512] = {0};
1531#if OPENSSL_VERSION_1_1
1532 int aead, nid;
1533 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1534#endif
1535 PyObject *retval;
1536
1537 retval = PyDict_New();
1538 if (retval == NULL) {
1539 goto error;
1540 }
1541
1542 /* can be NULL */
1543 cipher_name = SSL_CIPHER_get_name(cipher);
1544 cipher_protocol = SSL_CIPHER_get_version(cipher);
1545 cipher_id = SSL_CIPHER_get_id(cipher);
1546 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
1547 len = strlen(buf);
1548 if (len > 1 && buf[len-1] == '\n')
1549 buf[len-1] = '\0';
1550 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1551
1552#if OPENSSL_VERSION_1_1
1553 aead = SSL_CIPHER_is_aead(cipher);
1554 nid = SSL_CIPHER_get_cipher_nid(cipher);
1555 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1556 nid = SSL_CIPHER_get_digest_nid(cipher);
1557 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1558 nid = SSL_CIPHER_get_kx_nid(cipher);
1559 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1560 nid = SSL_CIPHER_get_auth_nid(cipher);
1561 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1562#endif
1563
1564 retval = Py_BuildValue(
1565 "{sksssssssisi"
1566#if OPENSSL_VERSION_1_1
1567 "sOssssssss"
1568#endif
1569 "}",
1570 "id", cipher_id,
1571 "name", cipher_name,
1572 "protocol", cipher_protocol,
1573 "description", buf,
1574 "strength_bits", strength_bits,
1575 "alg_bits", alg_bits
1576#if OPENSSL_VERSION_1_1
1577 ,"aead", aead ? Py_True : Py_False,
1578 "symmetric", skcipher,
1579 "digest", digest,
1580 "kea", kx,
1581 "auth", auth
1582#endif
1583 );
1584 return retval;
1585
1586 error:
1587 Py_XDECREF(retval);
1588 return NULL;
1589}
1590#endif
1591
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001592/*[clinic input]
1593_ssl._SSLSocket.shared_ciphers
1594[clinic start generated code]*/
1595
1596static PyObject *
1597_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1598/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001599{
1600 STACK_OF(SSL_CIPHER) *ciphers;
1601 int i;
1602 PyObject *res;
1603
Christian Heimes598894f2016-09-05 23:19:05 +02001604 ciphers = SSL_get_ciphers(self->ssl);
1605 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001606 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001607 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1608 if (!res)
1609 return NULL;
1610 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1611 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1612 if (!tup) {
1613 Py_DECREF(res);
1614 return NULL;
1615 }
1616 PyList_SET_ITEM(res, i, tup);
1617 }
1618 return res;
1619}
1620
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001621/*[clinic input]
1622_ssl._SSLSocket.cipher
1623[clinic start generated code]*/
1624
1625static PyObject *
1626_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1627/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001628{
1629 const SSL_CIPHER *current;
1630
1631 if (self->ssl == NULL)
1632 Py_RETURN_NONE;
1633 current = SSL_get_current_cipher(self->ssl);
1634 if (current == NULL)
1635 Py_RETURN_NONE;
1636 return cipher_to_tuple(current);
1637}
1638
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001639/*[clinic input]
1640_ssl._SSLSocket.version
1641[clinic start generated code]*/
1642
1643static PyObject *
1644_ssl__SSLSocket_version_impl(PySSLSocket *self)
1645/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001646{
1647 const char *version;
1648
1649 if (self->ssl == NULL)
1650 Py_RETURN_NONE;
1651 version = SSL_get_version(self->ssl);
1652 if (!strcmp(version, "unknown"))
1653 Py_RETURN_NONE;
1654 return PyUnicode_FromString(version);
1655}
1656
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001657#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001658/*[clinic input]
1659_ssl._SSLSocket.selected_npn_protocol
1660[clinic start generated code]*/
1661
1662static PyObject *
1663_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1664/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1665{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001666 const unsigned char *out;
1667 unsigned int outlen;
1668
Victor Stinner4569cd52013-06-23 14:58:43 +02001669 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001670 &out, &outlen);
1671
1672 if (out == NULL)
1673 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001674 return PyUnicode_FromStringAndSize((char *)out, outlen);
1675}
1676#endif
1677
1678#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001679/*[clinic input]
1680_ssl._SSLSocket.selected_alpn_protocol
1681[clinic start generated code]*/
1682
1683static PyObject *
1684_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1685/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1686{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001687 const unsigned char *out;
1688 unsigned int outlen;
1689
1690 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1691
1692 if (out == NULL)
1693 Py_RETURN_NONE;
1694 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001695}
1696#endif
1697
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001698/*[clinic input]
1699_ssl._SSLSocket.compression
1700[clinic start generated code]*/
1701
1702static PyObject *
1703_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1704/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1705{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001706#ifdef OPENSSL_NO_COMP
1707 Py_RETURN_NONE;
1708#else
1709 const COMP_METHOD *comp_method;
1710 const char *short_name;
1711
1712 if (self->ssl == NULL)
1713 Py_RETURN_NONE;
1714 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001715 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001716 Py_RETURN_NONE;
Christian Heimes598894f2016-09-05 23:19:05 +02001717 short_name = COMP_get_name(comp_method);
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001718 if (short_name == NULL)
1719 Py_RETURN_NONE;
1720 return PyUnicode_DecodeFSDefault(short_name);
1721#endif
1722}
1723
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001724static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1725 Py_INCREF(self->ctx);
1726 return self->ctx;
1727}
1728
1729static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1730 void *closure) {
1731
1732 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001733#if !HAVE_SNI
1734 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1735 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001736 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001737#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001738 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001739 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001740 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001741#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001742 } else {
1743 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1744 return -1;
1745 }
1746
1747 return 0;
1748}
1749
1750PyDoc_STRVAR(PySSL_set_context_doc,
1751"_setter_context(ctx)\n\
1752\
1753This changes the context associated with the SSLSocket. This is typically\n\
1754used from within a callback function set by the set_servername_callback\n\
1755on the SSLContext to change the certificate information associated with the\n\
1756SSLSocket before the cryptographic exchange handshake messages\n");
1757
1758
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001759static PyObject *
1760PySSL_get_server_side(PySSLSocket *self, void *c)
1761{
1762 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1763}
1764
1765PyDoc_STRVAR(PySSL_get_server_side_doc,
1766"Whether this is a server-side socket.");
1767
1768static PyObject *
1769PySSL_get_server_hostname(PySSLSocket *self, void *c)
1770{
1771 if (self->server_hostname == NULL)
1772 Py_RETURN_NONE;
1773 Py_INCREF(self->server_hostname);
1774 return self->server_hostname;
1775}
1776
1777PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1778"The currently set server hostname (for SNI).");
1779
1780static PyObject *
1781PySSL_get_owner(PySSLSocket *self, void *c)
1782{
1783 PyObject *owner;
1784
1785 if (self->owner == NULL)
1786 Py_RETURN_NONE;
1787
1788 owner = PyWeakref_GetObject(self->owner);
1789 Py_INCREF(owner);
1790 return owner;
1791}
1792
1793static int
1794PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1795{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001796 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001797 if (self->owner == NULL)
1798 return -1;
1799 return 0;
1800}
1801
1802PyDoc_STRVAR(PySSL_get_owner_doc,
1803"The Python-level owner of this object.\
1804Passed as \"self\" in servername callback.");
1805
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001806
Antoine Pitrou152efa22010-05-16 18:19:27 +00001807static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001808{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001809 if (self->peer_cert) /* Possible not to have one? */
1810 X509_free (self->peer_cert);
1811 if (self->ssl)
1812 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001813 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001814 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001815 Py_XDECREF(self->server_hostname);
1816 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001817 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001818}
1819
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001820/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001821 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001822 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001823 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001824
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001825static int
Victor Stinner14690702015-04-06 22:46:13 +02001826PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001827{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001828 int rc;
1829#ifdef HAVE_POLL
1830 struct pollfd pollfd;
1831 _PyTime_t ms;
1832#else
1833 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001834 fd_set fds;
1835 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001836#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001837
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001838 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001839 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001840 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001841 else if (timeout < 0) {
1842 if (s->sock_timeout > 0)
1843 return SOCKET_HAS_TIMED_OUT;
1844 else
1845 return SOCKET_IS_BLOCKING;
1846 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001847
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001848 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001849 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001850 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001851
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001852 /* Prefer poll, if available, since you can poll() any fd
1853 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001854#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001855 pollfd.fd = s->sock_fd;
1856 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001857
Victor Stinner14690702015-04-06 22:46:13 +02001858 /* timeout is in seconds, poll() uses milliseconds */
1859 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001860 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001861
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001862 PySSL_BEGIN_ALLOW_THREADS
1863 rc = poll(&pollfd, 1, (int)ms);
1864 PySSL_END_ALLOW_THREADS
1865#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001866 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001867 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001868 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001869
Victor Stinner14690702015-04-06 22:46:13 +02001870 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001871
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001872 FD_ZERO(&fds);
1873 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001874
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001875 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001876 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001877 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001878 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001879 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001880 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001881 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001882 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001883#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001884
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001885 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1886 (when we are able to write or when there's something to read) */
1887 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001888}
1889
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001890/*[clinic input]
1891_ssl._SSLSocket.write
1892 b: Py_buffer
1893 /
1894
1895Writes the bytes-like object b into the SSL object.
1896
1897Returns the number of bytes written.
1898[clinic start generated code]*/
1899
1900static PyObject *
1901_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1902/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001903{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001904 int len;
1905 int sockstate;
1906 int err;
1907 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001908 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001909 _PyTime_t timeout, deadline = 0;
1910 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001911
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001912 if (sock != NULL) {
1913 if (((PyObject*)sock) == Py_None) {
1914 _setSSLError("Underlying socket connection gone",
1915 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1916 return NULL;
1917 }
1918 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001919 }
1920
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001921 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001922 PyErr_Format(PyExc_OverflowError,
1923 "string longer than %d bytes", INT_MAX);
1924 goto error;
1925 }
1926
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001927 if (sock != NULL) {
1928 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001929 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001930 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1931 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1932 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001933
Victor Stinner14690702015-04-06 22:46:13 +02001934 timeout = GET_SOCKET_TIMEOUT(sock);
1935 has_timeout = (timeout > 0);
1936 if (has_timeout)
1937 deadline = _PyTime_GetMonotonicClock() + timeout;
1938
1939 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001940 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001941 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001942 "The write operation timed out");
1943 goto error;
1944 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1945 PyErr_SetString(PySSLErrorObject,
1946 "Underlying socket has been closed.");
1947 goto error;
1948 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1949 PyErr_SetString(PySSLErrorObject,
1950 "Underlying socket too large for select().");
1951 goto error;
1952 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001953
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001954 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001955 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001956 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001957 err = SSL_get_error(self->ssl, len);
1958 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001959
1960 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001961 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001962
Victor Stinner14690702015-04-06 22:46:13 +02001963 if (has_timeout)
1964 timeout = deadline - _PyTime_GetMonotonicClock();
1965
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001966 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001967 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001968 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001969 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001970 } else {
1971 sockstate = SOCKET_OPERATION_OK;
1972 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001973
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001974 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001975 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001976 "The write operation timed out");
1977 goto error;
1978 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1979 PyErr_SetString(PySSLErrorObject,
1980 "Underlying socket has been closed.");
1981 goto error;
1982 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1983 break;
1984 }
1985 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001986
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001987 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001988 if (len > 0)
1989 return PyLong_FromLong(len);
1990 else
1991 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001992
1993error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001994 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001995 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001996}
1997
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001998/*[clinic input]
1999_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002000
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002001Returns the number of already decrypted bytes available for read, pending on the connection.
2002[clinic start generated code]*/
2003
2004static PyObject *
2005_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2006/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002007{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002008 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002009
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002010 PySSL_BEGIN_ALLOW_THREADS
2011 count = SSL_pending(self->ssl);
2012 PySSL_END_ALLOW_THREADS
2013 if (count < 0)
2014 return PySSL_SetError(self, count, __FILE__, __LINE__);
2015 else
2016 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002017}
2018
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002019/*[clinic input]
2020_ssl._SSLSocket.read
2021 size as len: int
2022 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002023 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002024 ]
2025 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002026
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002027Read up to size bytes from the SSL socket.
2028[clinic start generated code]*/
2029
2030static PyObject *
2031_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2032 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002033/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002034{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002035 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002036 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002037 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002038 int sockstate;
2039 int err;
2040 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002041 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002042 _PyTime_t timeout, deadline = 0;
2043 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002044
Martin Panter5503d472016-03-27 05:35:19 +00002045 if (!group_right_1 && len < 0) {
2046 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2047 return NULL;
2048 }
2049
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002050 if (sock != NULL) {
2051 if (((PyObject*)sock) == Py_None) {
2052 _setSSLError("Underlying socket connection gone",
2053 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2054 return NULL;
2055 }
2056 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002057 }
2058
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002059 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002060 dest = PyBytes_FromStringAndSize(NULL, len);
2061 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002062 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002063 if (len == 0) {
2064 Py_XDECREF(sock);
2065 return dest;
2066 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002067 mem = PyBytes_AS_STRING(dest);
2068 }
2069 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002070 mem = buffer->buf;
2071 if (len <= 0 || len > buffer->len) {
2072 len = (int) buffer->len;
2073 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002074 PyErr_SetString(PyExc_OverflowError,
2075 "maximum length can't fit in a C 'int'");
2076 goto error;
2077 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002078 if (len == 0) {
2079 count = 0;
2080 goto done;
2081 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002082 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002083 }
2084
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002085 if (sock != NULL) {
2086 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002087 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002088 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2089 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2090 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002091
Victor Stinner14690702015-04-06 22:46:13 +02002092 timeout = GET_SOCKET_TIMEOUT(sock);
2093 has_timeout = (timeout > 0);
2094 if (has_timeout)
2095 deadline = _PyTime_GetMonotonicClock() + timeout;
2096
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002097 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002098 PySSL_BEGIN_ALLOW_THREADS
2099 count = SSL_read(self->ssl, mem, len);
2100 err = SSL_get_error(self->ssl, count);
2101 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002102
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002103 if (PyErr_CheckSignals())
2104 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002105
Victor Stinner14690702015-04-06 22:46:13 +02002106 if (has_timeout)
2107 timeout = deadline - _PyTime_GetMonotonicClock();
2108
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002109 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002110 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002111 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002112 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002113 } else if (err == SSL_ERROR_ZERO_RETURN &&
2114 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002115 {
2116 count = 0;
2117 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002118 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002119 else
2120 sockstate = SOCKET_OPERATION_OK;
2121
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002122 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002123 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002124 "The read operation timed out");
2125 goto error;
2126 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2127 break;
2128 }
2129 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002130
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002131 if (count <= 0) {
2132 PySSL_SetError(self, count, __FILE__, __LINE__);
2133 goto error;
2134 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002135
2136done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002137 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002138 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002139 _PyBytes_Resize(&dest, count);
2140 return dest;
2141 }
2142 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002143 return PyLong_FromLong(count);
2144 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002145
2146error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002147 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002148 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002149 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002150 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002151}
2152
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002153/*[clinic input]
2154_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002155
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002156Does the SSL shutdown handshake with the remote end.
2157
2158Returns the underlying socket object.
2159[clinic start generated code]*/
2160
2161static PyObject *
2162_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2163/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002164{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002165 int err, ssl_err, sockstate, nonblocking;
2166 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002167 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002168 _PyTime_t timeout, deadline = 0;
2169 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002170
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002171 if (sock != NULL) {
2172 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002173 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002174 _setSSLError("Underlying socket connection gone",
2175 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2176 return NULL;
2177 }
2178 Py_INCREF(sock);
2179
2180 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002181 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002182 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2183 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002184 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002185
Victor Stinner14690702015-04-06 22:46:13 +02002186 timeout = GET_SOCKET_TIMEOUT(sock);
2187 has_timeout = (timeout > 0);
2188 if (has_timeout)
2189 deadline = _PyTime_GetMonotonicClock() + timeout;
2190
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002191 while (1) {
2192 PySSL_BEGIN_ALLOW_THREADS
2193 /* Disable read-ahead so that unwrap can work correctly.
2194 * Otherwise OpenSSL might read in too much data,
2195 * eating clear text data that happens to be
2196 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002197 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002198 * function is used and the shutdown_seen_zero != 0
2199 * condition is met.
2200 */
2201 if (self->shutdown_seen_zero)
2202 SSL_set_read_ahead(self->ssl, 0);
2203 err = SSL_shutdown(self->ssl);
2204 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002205
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002206 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2207 if (err > 0)
2208 break;
2209 if (err == 0) {
2210 /* Don't loop endlessly; instead preserve legacy
2211 behaviour of trying SSL_shutdown() only twice.
2212 This looks necessary for OpenSSL < 0.9.8m */
2213 if (++zeros > 1)
2214 break;
2215 /* Shutdown was sent, now try receiving */
2216 self->shutdown_seen_zero = 1;
2217 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002218 }
2219
Victor Stinner14690702015-04-06 22:46:13 +02002220 if (has_timeout)
2221 timeout = deadline - _PyTime_GetMonotonicClock();
2222
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002223 /* Possibly retry shutdown until timeout or failure */
2224 ssl_err = SSL_get_error(self->ssl, err);
2225 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002226 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002227 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002228 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002229 else
2230 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002231
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002232 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2233 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002234 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002235 "The read operation timed out");
2236 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002237 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002238 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002239 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002240 }
2241 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2242 PyErr_SetString(PySSLErrorObject,
2243 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002244 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002245 }
2246 else if (sockstate != SOCKET_OPERATION_OK)
2247 /* Retain the SSL error code */
2248 break;
2249 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002250
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002251 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002252 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002253 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002254 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002255 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002256 /* It's already INCREF'ed */
2257 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002258 else
2259 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002260
2261error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002262 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002263 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002264}
2265
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002266/*[clinic input]
2267_ssl._SSLSocket.tls_unique_cb
2268
2269Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2270
2271If the TLS handshake is not yet complete, None is returned.
2272[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002273
Antoine Pitroud6494802011-07-21 01:11:30 +02002274static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002275_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2276/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002277{
2278 PyObject *retval = NULL;
2279 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002280 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002281
2282 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2283 /* if session is resumed XOR we are the client */
2284 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2285 }
2286 else {
2287 /* if a new session XOR we are the server */
2288 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2289 }
2290
2291 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002292 if (len == 0)
2293 Py_RETURN_NONE;
2294
2295 retval = PyBytes_FromStringAndSize(buf, len);
2296
2297 return retval;
2298}
2299
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002300static PyGetSetDef ssl_getsetlist[] = {
2301 {"context", (getter) PySSL_get_context,
2302 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002303 {"server_side", (getter) PySSL_get_server_side, NULL,
2304 PySSL_get_server_side_doc},
2305 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2306 PySSL_get_server_hostname_doc},
2307 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2308 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002309 {NULL}, /* sentinel */
2310};
2311
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002312static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002313 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2314 _SSL__SSLSOCKET_WRITE_METHODDEF
2315 _SSL__SSLSOCKET_READ_METHODDEF
2316 _SSL__SSLSOCKET_PENDING_METHODDEF
2317 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2318 _SSL__SSLSOCKET_CIPHER_METHODDEF
2319 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2320 _SSL__SSLSOCKET_VERSION_METHODDEF
2321 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2322 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2323 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2324 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2325 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002326 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002327};
2328
Antoine Pitrou152efa22010-05-16 18:19:27 +00002329static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002330 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002331 "_ssl._SSLSocket", /*tp_name*/
2332 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002333 0, /*tp_itemsize*/
2334 /* methods */
2335 (destructor)PySSL_dealloc, /*tp_dealloc*/
2336 0, /*tp_print*/
2337 0, /*tp_getattr*/
2338 0, /*tp_setattr*/
2339 0, /*tp_reserved*/
2340 0, /*tp_repr*/
2341 0, /*tp_as_number*/
2342 0, /*tp_as_sequence*/
2343 0, /*tp_as_mapping*/
2344 0, /*tp_hash*/
2345 0, /*tp_call*/
2346 0, /*tp_str*/
2347 0, /*tp_getattro*/
2348 0, /*tp_setattro*/
2349 0, /*tp_as_buffer*/
2350 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2351 0, /*tp_doc*/
2352 0, /*tp_traverse*/
2353 0, /*tp_clear*/
2354 0, /*tp_richcompare*/
2355 0, /*tp_weaklistoffset*/
2356 0, /*tp_iter*/
2357 0, /*tp_iternext*/
2358 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002359 0, /*tp_members*/
2360 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002361};
2362
Antoine Pitrou152efa22010-05-16 18:19:27 +00002363
2364/*
2365 * _SSLContext objects
2366 */
2367
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002368/*[clinic input]
2369@classmethod
2370_ssl._SSLContext.__new__
2371 protocol as proto_version: int
2372 /
2373[clinic start generated code]*/
2374
Antoine Pitrou152efa22010-05-16 18:19:27 +00002375static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002376_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2377/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002378{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002379 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002380 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002381 SSL_CTX *ctx = NULL;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002382#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002383 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002384#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002385
Antoine Pitrou152efa22010-05-16 18:19:27 +00002386 PySSL_BEGIN_ALLOW_THREADS
2387 if (proto_version == PY_SSL_VERSION_TLS1)
2388 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002389#if HAVE_TLSv1_2
2390 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2391 ctx = SSL_CTX_new(TLSv1_1_method());
2392 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2393 ctx = SSL_CTX_new(TLSv1_2_method());
2394#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002395#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002396 else if (proto_version == PY_SSL_VERSION_SSL3)
2397 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002398#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002399#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002400 else if (proto_version == PY_SSL_VERSION_SSL2)
2401 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002402#endif
Christian Heimes598894f2016-09-05 23:19:05 +02002403 else if (proto_version == PY_SSL_VERSION_TLS)
2404 ctx = SSL_CTX_new(TLS_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002405 else
2406 proto_version = -1;
2407 PySSL_END_ALLOW_THREADS
2408
2409 if (proto_version == -1) {
2410 PyErr_SetString(PyExc_ValueError,
2411 "invalid protocol version");
2412 return NULL;
2413 }
2414 if (ctx == NULL) {
2415 PyErr_SetString(PySSLErrorObject,
2416 "failed to allocate SSL context");
2417 return NULL;
2418 }
2419
2420 assert(type != NULL && type->tp_alloc != NULL);
2421 self = (PySSLContext *) type->tp_alloc(type, 0);
2422 if (self == NULL) {
2423 SSL_CTX_free(ctx);
2424 return NULL;
2425 }
2426 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002427#ifdef OPENSSL_NPN_NEGOTIATED
2428 self->npn_protocols = NULL;
2429#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002430#ifdef HAVE_ALPN
2431 self->alpn_protocols = NULL;
2432#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002433#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002434 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002435#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002436 /* Don't check host name by default */
2437 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002438 /* Defaults */
2439 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002440 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2441 if (proto_version != PY_SSL_VERSION_SSL2)
2442 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002443 if (proto_version != PY_SSL_VERSION_SSL3)
2444 options |= SSL_OP_NO_SSLv3;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002445 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002446
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002447#if defined(SSL_MODE_RELEASE_BUFFERS)
2448 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2449 usage for no cost at all. However, don't do this for OpenSSL versions
2450 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2451 2014-0198. I can't find exactly which beta fixed this CVE, so be
2452 conservative and assume it wasn't fixed until release. We do this check
2453 at runtime to avoid problems from the dynamic linker.
2454 See #25672 for more on this. */
2455 libver = SSLeay();
2456 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2457 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2458 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2459 }
2460#endif
2461
2462
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002463#ifndef OPENSSL_NO_ECDH
2464 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2465 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002466 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2467 */
2468#if defined(SSL_CTX_set_ecdh_auto) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002469 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2470#else
2471 {
2472 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2473 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2474 EC_KEY_free(key);
2475 }
2476#endif
2477#endif
2478
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002479#define SID_CTX "Python"
2480 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2481 sizeof(SID_CTX));
2482#undef SID_CTX
2483
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002484#ifdef X509_V_FLAG_TRUSTED_FIRST
2485 {
2486 /* Improve trust chain building when cross-signed intermediate
2487 certificates are present. See https://bugs.python.org/issue23476. */
2488 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2489 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2490 }
2491#endif
2492
Antoine Pitrou152efa22010-05-16 18:19:27 +00002493 return (PyObject *)self;
2494}
2495
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002496static int
2497context_traverse(PySSLContext *self, visitproc visit, void *arg)
2498{
2499#ifndef OPENSSL_NO_TLSEXT
2500 Py_VISIT(self->set_hostname);
2501#endif
2502 return 0;
2503}
2504
2505static int
2506context_clear(PySSLContext *self)
2507{
2508#ifndef OPENSSL_NO_TLSEXT
2509 Py_CLEAR(self->set_hostname);
2510#endif
2511 return 0;
2512}
2513
Antoine Pitrou152efa22010-05-16 18:19:27 +00002514static void
2515context_dealloc(PySSLContext *self)
2516{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002517 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002518 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002519#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002520 PyMem_FREE(self->npn_protocols);
2521#endif
2522#ifdef HAVE_ALPN
2523 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002524#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002525 Py_TYPE(self)->tp_free(self);
2526}
2527
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002528/*[clinic input]
2529_ssl._SSLContext.set_ciphers
2530 cipherlist: str
2531 /
2532[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002533
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002534static PyObject *
2535_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2536/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2537{
2538 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002539 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002540 /* Clearing the error queue is necessary on some OpenSSL versions,
2541 otherwise the error will be reported again when another SSL call
2542 is done. */
2543 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002544 PyErr_SetString(PySSLErrorObject,
2545 "No cipher can be selected.");
2546 return NULL;
2547 }
2548 Py_RETURN_NONE;
2549}
2550
Christian Heimes25bfcd52016-09-06 00:04:45 +02002551#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2552/*[clinic input]
2553_ssl._SSLContext.get_ciphers
2554[clinic start generated code]*/
2555
2556static PyObject *
2557_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2558/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2559{
2560 SSL *ssl = NULL;
2561 STACK_OF(SSL_CIPHER) *sk = NULL;
2562 SSL_CIPHER *cipher;
2563 int i=0;
2564 PyObject *result = NULL, *dct;
2565
2566 ssl = SSL_new(self->ctx);
2567 if (ssl == NULL) {
2568 _setSSLError(NULL, 0, __FILE__, __LINE__);
2569 goto exit;
2570 }
2571 sk = SSL_get_ciphers(ssl);
2572
2573 result = PyList_New(sk_SSL_CIPHER_num(sk));
2574 if (result == NULL) {
2575 goto exit;
2576 }
2577
2578 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2579 cipher = sk_SSL_CIPHER_value(sk, i);
2580 dct = cipher_to_dict(cipher);
2581 if (dct == NULL) {
2582 Py_CLEAR(result);
2583 goto exit;
2584 }
2585 PyList_SET_ITEM(result, i, dct);
2586 }
2587
2588 exit:
2589 if (ssl != NULL)
2590 SSL_free(ssl);
2591 return result;
2592
2593}
2594#endif
2595
2596
Benjamin Petersonc54de472015-01-28 12:06:39 -05002597#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002598static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002599do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2600 const unsigned char *server_protocols, unsigned int server_protocols_len,
2601 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002602{
Benjamin Peterson88615022015-01-23 17:30:26 -05002603 int ret;
2604 if (client_protocols == NULL) {
2605 client_protocols = (unsigned char *)"";
2606 client_protocols_len = 0;
2607 }
2608 if (server_protocols == NULL) {
2609 server_protocols = (unsigned char *)"";
2610 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002611 }
2612
Benjamin Peterson88615022015-01-23 17:30:26 -05002613 ret = SSL_select_next_proto(out, outlen,
2614 server_protocols, server_protocols_len,
2615 client_protocols, client_protocols_len);
2616 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2617 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002618
2619 return SSL_TLSEXT_ERR_OK;
2620}
2621
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002622/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2623static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002624_advertiseNPN_cb(SSL *s,
2625 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002626 void *args)
2627{
2628 PySSLContext *ssl_ctx = (PySSLContext *) args;
2629
2630 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002631 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002632 *len = 0;
2633 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002634 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002635 *len = ssl_ctx->npn_protocols_len;
2636 }
2637
2638 return SSL_TLSEXT_ERR_OK;
2639}
2640/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2641static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002642_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002643 unsigned char **out, unsigned char *outlen,
2644 const unsigned char *server, unsigned int server_len,
2645 void *args)
2646{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002647 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002648 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002649 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002650}
2651#endif
2652
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002653/*[clinic input]
2654_ssl._SSLContext._set_npn_protocols
2655 protos: Py_buffer
2656 /
2657[clinic start generated code]*/
2658
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002659static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002660_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2661 Py_buffer *protos)
2662/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002663{
2664#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002665 PyMem_Free(self->npn_protocols);
2666 self->npn_protocols = PyMem_Malloc(protos->len);
2667 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002668 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002669 memcpy(self->npn_protocols, protos->buf, protos->len);
2670 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002671
2672 /* set both server and client callbacks, because the context can
2673 * be used to create both types of sockets */
2674 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2675 _advertiseNPN_cb,
2676 self);
2677 SSL_CTX_set_next_proto_select_cb(self->ctx,
2678 _selectNPN_cb,
2679 self);
2680
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002681 Py_RETURN_NONE;
2682#else
2683 PyErr_SetString(PyExc_NotImplementedError,
2684 "The NPN extension requires OpenSSL 1.0.1 or later.");
2685 return NULL;
2686#endif
2687}
2688
Benjamin Petersoncca27322015-01-23 16:35:37 -05002689#ifdef HAVE_ALPN
2690static int
2691_selectALPN_cb(SSL *s,
2692 const unsigned char **out, unsigned char *outlen,
2693 const unsigned char *client_protocols, unsigned int client_protocols_len,
2694 void *args)
2695{
2696 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002697 return do_protocol_selection(1, (unsigned char **)out, outlen,
2698 ctx->alpn_protocols, ctx->alpn_protocols_len,
2699 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002700}
2701#endif
2702
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002703/*[clinic input]
2704_ssl._SSLContext._set_alpn_protocols
2705 protos: Py_buffer
2706 /
2707[clinic start generated code]*/
2708
Benjamin Petersoncca27322015-01-23 16:35:37 -05002709static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002710_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2711 Py_buffer *protos)
2712/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002713{
2714#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002715 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002716 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002717 if (!self->alpn_protocols)
2718 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002719 memcpy(self->alpn_protocols, protos->buf, protos->len);
2720 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002721
2722 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2723 return PyErr_NoMemory();
2724 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2725
Benjamin Petersoncca27322015-01-23 16:35:37 -05002726 Py_RETURN_NONE;
2727#else
2728 PyErr_SetString(PyExc_NotImplementedError,
2729 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2730 return NULL;
2731#endif
2732}
2733
Antoine Pitrou152efa22010-05-16 18:19:27 +00002734static PyObject *
2735get_verify_mode(PySSLContext *self, void *c)
2736{
2737 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2738 case SSL_VERIFY_NONE:
2739 return PyLong_FromLong(PY_SSL_CERT_NONE);
2740 case SSL_VERIFY_PEER:
2741 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2742 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2743 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2744 }
2745 PyErr_SetString(PySSLErrorObject,
2746 "invalid return value from SSL_CTX_get_verify_mode");
2747 return NULL;
2748}
2749
2750static int
2751set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2752{
2753 int n, mode;
2754 if (!PyArg_Parse(arg, "i", &n))
2755 return -1;
2756 if (n == PY_SSL_CERT_NONE)
2757 mode = SSL_VERIFY_NONE;
2758 else if (n == PY_SSL_CERT_OPTIONAL)
2759 mode = SSL_VERIFY_PEER;
2760 else if (n == PY_SSL_CERT_REQUIRED)
2761 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2762 else {
2763 PyErr_SetString(PyExc_ValueError,
2764 "invalid value for verify_mode");
2765 return -1;
2766 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002767 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2768 PyErr_SetString(PyExc_ValueError,
2769 "Cannot set verify_mode to CERT_NONE when "
2770 "check_hostname is enabled.");
2771 return -1;
2772 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002773 SSL_CTX_set_verify(self->ctx, mode, NULL);
2774 return 0;
2775}
2776
2777static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002778get_verify_flags(PySSLContext *self, void *c)
2779{
2780 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02002781 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01002782 unsigned long flags;
2783
2784 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02002785 param = X509_STORE_get0_param(store);
2786 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01002787 return PyLong_FromUnsignedLong(flags);
2788}
2789
2790static int
2791set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2792{
2793 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02002794 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01002795 unsigned long new_flags, flags, set, clear;
2796
2797 if (!PyArg_Parse(arg, "k", &new_flags))
2798 return -1;
2799 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02002800 param = X509_STORE_get0_param(store);
2801 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01002802 clear = flags & ~new_flags;
2803 set = ~flags & new_flags;
2804 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02002805 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01002806 _setSSLError(NULL, 0, __FILE__, __LINE__);
2807 return -1;
2808 }
2809 }
2810 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02002811 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01002812 _setSSLError(NULL, 0, __FILE__, __LINE__);
2813 return -1;
2814 }
2815 }
2816 return 0;
2817}
2818
2819static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002820get_options(PySSLContext *self, void *c)
2821{
2822 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2823}
2824
2825static int
2826set_options(PySSLContext *self, PyObject *arg, void *c)
2827{
2828 long new_opts, opts, set, clear;
2829 if (!PyArg_Parse(arg, "l", &new_opts))
2830 return -1;
2831 opts = SSL_CTX_get_options(self->ctx);
2832 clear = opts & ~new_opts;
2833 set = ~opts & new_opts;
2834 if (clear) {
2835#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2836 SSL_CTX_clear_options(self->ctx, clear);
2837#else
2838 PyErr_SetString(PyExc_ValueError,
2839 "can't clear options before OpenSSL 0.9.8m");
2840 return -1;
2841#endif
2842 }
2843 if (set)
2844 SSL_CTX_set_options(self->ctx, set);
2845 return 0;
2846}
2847
Christian Heimes1aa9a752013-12-02 02:41:19 +01002848static PyObject *
2849get_check_hostname(PySSLContext *self, void *c)
2850{
2851 return PyBool_FromLong(self->check_hostname);
2852}
2853
2854static int
2855set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2856{
2857 int check_hostname;
2858 if (!PyArg_Parse(arg, "p", &check_hostname))
2859 return -1;
2860 if (check_hostname &&
2861 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2862 PyErr_SetString(PyExc_ValueError,
2863 "check_hostname needs a SSL context with either "
2864 "CERT_OPTIONAL or CERT_REQUIRED");
2865 return -1;
2866 }
2867 self->check_hostname = check_hostname;
2868 return 0;
2869}
2870
2871
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002872typedef struct {
2873 PyThreadState *thread_state;
2874 PyObject *callable;
2875 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002876 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002877 int error;
2878} _PySSLPasswordInfo;
2879
2880static int
2881_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2882 const char *bad_type_error)
2883{
2884 /* Set the password and size fields of a _PySSLPasswordInfo struct
2885 from a unicode, bytes, or byte array object.
2886 The password field will be dynamically allocated and must be freed
2887 by the caller */
2888 PyObject *password_bytes = NULL;
2889 const char *data = NULL;
2890 Py_ssize_t size;
2891
2892 if (PyUnicode_Check(password)) {
2893 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2894 if (!password_bytes) {
2895 goto error;
2896 }
2897 data = PyBytes_AS_STRING(password_bytes);
2898 size = PyBytes_GET_SIZE(password_bytes);
2899 } else if (PyBytes_Check(password)) {
2900 data = PyBytes_AS_STRING(password);
2901 size = PyBytes_GET_SIZE(password);
2902 } else if (PyByteArray_Check(password)) {
2903 data = PyByteArray_AS_STRING(password);
2904 size = PyByteArray_GET_SIZE(password);
2905 } else {
2906 PyErr_SetString(PyExc_TypeError, bad_type_error);
2907 goto error;
2908 }
2909
Victor Stinner9ee02032013-06-23 15:08:23 +02002910 if (size > (Py_ssize_t)INT_MAX) {
2911 PyErr_Format(PyExc_ValueError,
2912 "password cannot be longer than %d bytes", INT_MAX);
2913 goto error;
2914 }
2915
Victor Stinner11ebff22013-07-07 17:07:52 +02002916 PyMem_Free(pw_info->password);
2917 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002918 if (!pw_info->password) {
2919 PyErr_SetString(PyExc_MemoryError,
2920 "unable to allocate password buffer");
2921 goto error;
2922 }
2923 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002924 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002925
2926 Py_XDECREF(password_bytes);
2927 return 1;
2928
2929error:
2930 Py_XDECREF(password_bytes);
2931 return 0;
2932}
2933
2934static int
2935_password_callback(char *buf, int size, int rwflag, void *userdata)
2936{
2937 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2938 PyObject *fn_ret = NULL;
2939
2940 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2941
2942 if (pw_info->callable) {
2943 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2944 if (!fn_ret) {
2945 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2946 core python API, so we could use it to add a frame here */
2947 goto error;
2948 }
2949
2950 if (!_pwinfo_set(pw_info, fn_ret,
2951 "password callback must return a string")) {
2952 goto error;
2953 }
2954 Py_CLEAR(fn_ret);
2955 }
2956
2957 if (pw_info->size > size) {
2958 PyErr_Format(PyExc_ValueError,
2959 "password cannot be longer than %d bytes", size);
2960 goto error;
2961 }
2962
2963 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2964 memcpy(buf, pw_info->password, pw_info->size);
2965 return pw_info->size;
2966
2967error:
2968 Py_XDECREF(fn_ret);
2969 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2970 pw_info->error = 1;
2971 return -1;
2972}
2973
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002974/*[clinic input]
2975_ssl._SSLContext.load_cert_chain
2976 certfile: object
2977 keyfile: object = NULL
2978 password: object = NULL
2979
2980[clinic start generated code]*/
2981
Antoine Pitroub5218772010-05-21 09:56:06 +00002982static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002983_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
2984 PyObject *keyfile, PyObject *password)
2985/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002986{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002987 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02002988 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2989 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002990 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002991 int r;
2992
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002993 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002994 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002995 if (keyfile == Py_None)
2996 keyfile = NULL;
2997 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2998 PyErr_SetString(PyExc_TypeError,
2999 "certfile should be a valid filesystem path");
3000 return NULL;
3001 }
3002 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3003 PyErr_SetString(PyExc_TypeError,
3004 "keyfile should be a valid filesystem path");
3005 goto error;
3006 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003007 if (password && password != Py_None) {
3008 if (PyCallable_Check(password)) {
3009 pw_info.callable = password;
3010 } else if (!_pwinfo_set(&pw_info, password,
3011 "password should be a string or callable")) {
3012 goto error;
3013 }
3014 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3015 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3016 }
3017 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003018 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3019 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003020 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003021 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003022 if (pw_info.error) {
3023 ERR_clear_error();
3024 /* the password callback has already set the error information */
3025 }
3026 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003027 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003028 PyErr_SetFromErrno(PyExc_IOError);
3029 }
3030 else {
3031 _setSSLError(NULL, 0, __FILE__, __LINE__);
3032 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003033 goto error;
3034 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003035 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003036 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003037 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3038 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003039 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3040 Py_CLEAR(keyfile_bytes);
3041 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003042 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003043 if (pw_info.error) {
3044 ERR_clear_error();
3045 /* the password callback has already set the error information */
3046 }
3047 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003048 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003049 PyErr_SetFromErrno(PyExc_IOError);
3050 }
3051 else {
3052 _setSSLError(NULL, 0, __FILE__, __LINE__);
3053 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003054 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003055 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003056 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003057 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003058 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003059 if (r != 1) {
3060 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003061 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003062 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003063 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3064 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003065 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003066 Py_RETURN_NONE;
3067
3068error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003069 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3070 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003071 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003072 Py_XDECREF(keyfile_bytes);
3073 Py_XDECREF(certfile_bytes);
3074 return NULL;
3075}
3076
Christian Heimesefff7062013-11-21 03:35:02 +01003077/* internal helper function, returns -1 on error
3078 */
3079static int
3080_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3081 int filetype)
3082{
3083 BIO *biobuf = NULL;
3084 X509_STORE *store;
3085 int retval = 0, err, loaded = 0;
3086
3087 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3088
3089 if (len <= 0) {
3090 PyErr_SetString(PyExc_ValueError,
3091 "Empty certificate data");
3092 return -1;
3093 } else if (len > INT_MAX) {
3094 PyErr_SetString(PyExc_OverflowError,
3095 "Certificate data is too long.");
3096 return -1;
3097 }
3098
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003099 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003100 if (biobuf == NULL) {
3101 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3102 return -1;
3103 }
3104
3105 store = SSL_CTX_get_cert_store(self->ctx);
3106 assert(store != NULL);
3107
3108 while (1) {
3109 X509 *cert = NULL;
3110 int r;
3111
3112 if (filetype == SSL_FILETYPE_ASN1) {
3113 cert = d2i_X509_bio(biobuf, NULL);
3114 } else {
3115 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003116 SSL_CTX_get_default_passwd_cb(self->ctx),
3117 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3118 );
Christian Heimesefff7062013-11-21 03:35:02 +01003119 }
3120 if (cert == NULL) {
3121 break;
3122 }
3123 r = X509_STORE_add_cert(store, cert);
3124 X509_free(cert);
3125 if (!r) {
3126 err = ERR_peek_last_error();
3127 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3128 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3129 /* cert already in hash table, not an error */
3130 ERR_clear_error();
3131 } else {
3132 break;
3133 }
3134 }
3135 loaded++;
3136 }
3137
3138 err = ERR_peek_last_error();
3139 if ((filetype == SSL_FILETYPE_ASN1) &&
3140 (loaded > 0) &&
3141 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3142 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3143 /* EOF ASN1 file, not an error */
3144 ERR_clear_error();
3145 retval = 0;
3146 } else if ((filetype == SSL_FILETYPE_PEM) &&
3147 (loaded > 0) &&
3148 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3149 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3150 /* EOF PEM file, not an error */
3151 ERR_clear_error();
3152 retval = 0;
3153 } else {
3154 _setSSLError(NULL, 0, __FILE__, __LINE__);
3155 retval = -1;
3156 }
3157
3158 BIO_free(biobuf);
3159 return retval;
3160}
3161
3162
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003163/*[clinic input]
3164_ssl._SSLContext.load_verify_locations
3165 cafile: object = NULL
3166 capath: object = NULL
3167 cadata: object = NULL
3168
3169[clinic start generated code]*/
3170
Antoine Pitrou152efa22010-05-16 18:19:27 +00003171static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003172_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3173 PyObject *cafile,
3174 PyObject *capath,
3175 PyObject *cadata)
3176/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003177{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003178 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3179 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003180 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003181
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003182 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003183 if (cafile == Py_None)
3184 cafile = NULL;
3185 if (capath == Py_None)
3186 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003187 if (cadata == Py_None)
3188 cadata = NULL;
3189
3190 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003191 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003192 "cafile, capath and cadata cannot be all omitted");
3193 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003194 }
3195 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3196 PyErr_SetString(PyExc_TypeError,
3197 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003198 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003199 }
3200 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003201 PyErr_SetString(PyExc_TypeError,
3202 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003203 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003204 }
Christian Heimesefff7062013-11-21 03:35:02 +01003205
3206 /* validata cadata type and load cadata */
3207 if (cadata) {
3208 Py_buffer buf;
3209 PyObject *cadata_ascii = NULL;
3210
3211 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3212 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3213 PyBuffer_Release(&buf);
3214 PyErr_SetString(PyExc_TypeError,
3215 "cadata should be a contiguous buffer with "
3216 "a single dimension");
3217 goto error;
3218 }
3219 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3220 PyBuffer_Release(&buf);
3221 if (r == -1) {
3222 goto error;
3223 }
3224 } else {
3225 PyErr_Clear();
3226 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3227 if (cadata_ascii == NULL) {
3228 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003229 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003230 "bytes-like object");
3231 goto error;
3232 }
3233 r = _add_ca_certs(self,
3234 PyBytes_AS_STRING(cadata_ascii),
3235 PyBytes_GET_SIZE(cadata_ascii),
3236 SSL_FILETYPE_PEM);
3237 Py_DECREF(cadata_ascii);
3238 if (r == -1) {
3239 goto error;
3240 }
3241 }
3242 }
3243
3244 /* load cafile or capath */
3245 if (cafile || capath) {
3246 if (cafile)
3247 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3248 if (capath)
3249 capath_buf = PyBytes_AS_STRING(capath_bytes);
3250 PySSL_BEGIN_ALLOW_THREADS
3251 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3252 PySSL_END_ALLOW_THREADS
3253 if (r != 1) {
3254 ok = 0;
3255 if (errno != 0) {
3256 ERR_clear_error();
3257 PyErr_SetFromErrno(PyExc_IOError);
3258 }
3259 else {
3260 _setSSLError(NULL, 0, __FILE__, __LINE__);
3261 }
3262 goto error;
3263 }
3264 }
3265 goto end;
3266
3267 error:
3268 ok = 0;
3269 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003270 Py_XDECREF(cafile_bytes);
3271 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003272 if (ok) {
3273 Py_RETURN_NONE;
3274 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003275 return NULL;
3276 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003277}
3278
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003279/*[clinic input]
3280_ssl._SSLContext.load_dh_params
3281 path as filepath: object
3282 /
3283
3284[clinic start generated code]*/
3285
Antoine Pitrou152efa22010-05-16 18:19:27 +00003286static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003287_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3288/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003289{
3290 FILE *f;
3291 DH *dh;
3292
Victor Stinnerdaf45552013-08-28 00:53:59 +02003293 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003294 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003295 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003296
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003297 errno = 0;
3298 PySSL_BEGIN_ALLOW_THREADS
3299 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003300 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003301 PySSL_END_ALLOW_THREADS
3302 if (dh == NULL) {
3303 if (errno != 0) {
3304 ERR_clear_error();
3305 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3306 }
3307 else {
3308 _setSSLError(NULL, 0, __FILE__, __LINE__);
3309 }
3310 return NULL;
3311 }
3312 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3313 _setSSLError(NULL, 0, __FILE__, __LINE__);
3314 DH_free(dh);
3315 Py_RETURN_NONE;
3316}
3317
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003318/*[clinic input]
3319_ssl._SSLContext._wrap_socket
3320 sock: object(subclass_of="PySocketModule.Sock_Type")
3321 server_side: int
3322 server_hostname as hostname_obj: object = None
3323
3324[clinic start generated code]*/
3325
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003326static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003327_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3328 int server_side, PyObject *hostname_obj)
3329/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003330{
Antoine Pitroud5323212010-10-22 18:19:07 +00003331 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003332 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003333
Antoine Pitroud5323212010-10-22 18:19:07 +00003334 /* server_hostname is either None (or absent), or to be encoded
3335 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003336 if (hostname_obj != Py_None) {
3337 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003338 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003339 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003340
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003341 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3342 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003343 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003344 if (hostname != NULL)
3345 PyMem_Free(hostname);
3346 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003347}
3348
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003349/*[clinic input]
3350_ssl._SSLContext._wrap_bio
3351 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3352 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3353 server_side: int
3354 server_hostname as hostname_obj: object = None
3355
3356[clinic start generated code]*/
3357
Antoine Pitroub0182c82010-10-12 20:09:02 +00003358static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003359_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3360 PySSLMemoryBIO *outgoing, int server_side,
3361 PyObject *hostname_obj)
3362/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003363{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003364 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003365 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003366
3367 /* server_hostname is either None (or absent), or to be encoded
3368 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003369 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003370 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3371 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003372 }
3373
3374 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3375 incoming, outgoing);
3376
3377 PyMem_Free(hostname);
3378 return res;
3379}
3380
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003381/*[clinic input]
3382_ssl._SSLContext.session_stats
3383[clinic start generated code]*/
3384
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003385static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003386_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3387/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003388{
3389 int r;
3390 PyObject *value, *stats = PyDict_New();
3391 if (!stats)
3392 return NULL;
3393
3394#define ADD_STATS(SSL_NAME, KEY_NAME) \
3395 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3396 if (value == NULL) \
3397 goto error; \
3398 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3399 Py_DECREF(value); \
3400 if (r < 0) \
3401 goto error;
3402
3403 ADD_STATS(number, "number");
3404 ADD_STATS(connect, "connect");
3405 ADD_STATS(connect_good, "connect_good");
3406 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3407 ADD_STATS(accept, "accept");
3408 ADD_STATS(accept_good, "accept_good");
3409 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3410 ADD_STATS(accept, "accept");
3411 ADD_STATS(hits, "hits");
3412 ADD_STATS(misses, "misses");
3413 ADD_STATS(timeouts, "timeouts");
3414 ADD_STATS(cache_full, "cache_full");
3415
3416#undef ADD_STATS
3417
3418 return stats;
3419
3420error:
3421 Py_DECREF(stats);
3422 return NULL;
3423}
3424
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003425/*[clinic input]
3426_ssl._SSLContext.set_default_verify_paths
3427[clinic start generated code]*/
3428
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003429static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003430_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3431/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003432{
3433 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3434 _setSSLError(NULL, 0, __FILE__, __LINE__);
3435 return NULL;
3436 }
3437 Py_RETURN_NONE;
3438}
3439
Antoine Pitrou501da612011-12-21 09:27:41 +01003440#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003441/*[clinic input]
3442_ssl._SSLContext.set_ecdh_curve
3443 name: object
3444 /
3445
3446[clinic start generated code]*/
3447
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003448static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003449_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3450/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003451{
3452 PyObject *name_bytes;
3453 int nid;
3454 EC_KEY *key;
3455
3456 if (!PyUnicode_FSConverter(name, &name_bytes))
3457 return NULL;
3458 assert(PyBytes_Check(name_bytes));
3459 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3460 Py_DECREF(name_bytes);
3461 if (nid == 0) {
3462 PyErr_Format(PyExc_ValueError,
3463 "unknown elliptic curve name %R", name);
3464 return NULL;
3465 }
3466 key = EC_KEY_new_by_curve_name(nid);
3467 if (key == NULL) {
3468 _setSSLError(NULL, 0, __FILE__, __LINE__);
3469 return NULL;
3470 }
3471 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3472 EC_KEY_free(key);
3473 Py_RETURN_NONE;
3474}
Antoine Pitrou501da612011-12-21 09:27:41 +01003475#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003476
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003477#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003478static int
3479_servername_callback(SSL *s, int *al, void *args)
3480{
3481 int ret;
3482 PySSLContext *ssl_ctx = (PySSLContext *) args;
3483 PySSLSocket *ssl;
3484 PyObject *servername_o;
3485 PyObject *servername_idna;
3486 PyObject *result;
3487 /* The high-level ssl.SSLSocket object */
3488 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003489 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003490#ifdef WITH_THREAD
3491 PyGILState_STATE gstate = PyGILState_Ensure();
3492#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003493
3494 if (ssl_ctx->set_hostname == NULL) {
3495 /* remove race condition in this the call back while if removing the
3496 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003497#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003498 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003499#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003500 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003501 }
3502
3503 ssl = SSL_get_app_data(s);
3504 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003505
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003506 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003507 * SSL connection and that has a .context attribute that can be changed to
3508 * identify the requested hostname. Since the official API is the Python
3509 * level API we want to pass the callback a Python level object rather than
3510 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3511 * SSLObject) that will be passed. Otherwise if there's a socket then that
3512 * will be passed. If both do not exist only then the C-level object is
3513 * passed. */
3514 if (ssl->owner)
3515 ssl_socket = PyWeakref_GetObject(ssl->owner);
3516 else if (ssl->Socket)
3517 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3518 else
3519 ssl_socket = (PyObject *) ssl;
3520
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003521 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003522 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003523 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003524
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003525 if (servername == NULL) {
3526 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3527 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003528 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003529 else {
3530 servername_o = PyBytes_FromString(servername);
3531 if (servername_o == NULL) {
3532 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3533 goto error;
3534 }
3535 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3536 if (servername_idna == NULL) {
3537 PyErr_WriteUnraisable(servername_o);
3538 Py_DECREF(servername_o);
3539 goto error;
3540 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003541 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003542 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3543 servername_idna, ssl_ctx, NULL);
3544 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003545 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003546 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003547
3548 if (result == NULL) {
3549 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3550 *al = SSL_AD_HANDSHAKE_FAILURE;
3551 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3552 }
3553 else {
3554 if (result != Py_None) {
3555 *al = (int) PyLong_AsLong(result);
3556 if (PyErr_Occurred()) {
3557 PyErr_WriteUnraisable(result);
3558 *al = SSL_AD_INTERNAL_ERROR;
3559 }
3560 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3561 }
3562 else {
3563 ret = SSL_TLSEXT_ERR_OK;
3564 }
3565 Py_DECREF(result);
3566 }
3567
Stefan Krah20d60802013-01-17 17:07:17 +01003568#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003569 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003570#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003571 return ret;
3572
3573error:
3574 Py_DECREF(ssl_socket);
3575 *al = SSL_AD_INTERNAL_ERROR;
3576 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003577#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003578 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003579#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003580 return ret;
3581}
Antoine Pitroua5963382013-03-30 16:39:00 +01003582#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003583
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003584/*[clinic input]
3585_ssl._SSLContext.set_servername_callback
3586 method as cb: object
3587 /
3588
3589Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3590
3591If the argument is None then the callback is disabled. The method is called
3592with the SSLSocket, the server name as a string, and the SSLContext object.
3593See RFC 6066 for details of the SNI extension.
3594[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003595
3596static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003597_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3598/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003599{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003600#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003601 Py_CLEAR(self->set_hostname);
3602 if (cb == Py_None) {
3603 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3604 }
3605 else {
3606 if (!PyCallable_Check(cb)) {
3607 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3608 PyErr_SetString(PyExc_TypeError,
3609 "not a callable object");
3610 return NULL;
3611 }
3612 Py_INCREF(cb);
3613 self->set_hostname = cb;
3614 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3615 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3616 }
3617 Py_RETURN_NONE;
3618#else
3619 PyErr_SetString(PyExc_NotImplementedError,
3620 "The TLS extension servername callback, "
3621 "SSL_CTX_set_tlsext_servername_callback, "
3622 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003623 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003624#endif
3625}
3626
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003627/*[clinic input]
3628_ssl._SSLContext.cert_store_stats
3629
3630Returns quantities of loaded X.509 certificates.
3631
3632X.509 certificates with a CA extension and certificate revocation lists
3633inside the context's cert store.
3634
3635NOTE: Certificates in a capath directory aren't loaded unless they have
3636been used at least once.
3637[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003638
3639static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003640_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3641/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003642{
3643 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003644 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003645 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003646 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003647
3648 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003649 objs = X509_STORE_get0_objects(store);
3650 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3651 obj = sk_X509_OBJECT_value(objs, i);
3652 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003653 case X509_LU_X509:
3654 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003655 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003656 ca++;
3657 }
3658 break;
3659 case X509_LU_CRL:
3660 crl++;
3661 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003662 default:
3663 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3664 * As far as I can tell they are internal states and never
3665 * stored in a cert store */
3666 break;
3667 }
3668 }
3669 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3670 "x509_ca", ca);
3671}
3672
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003673/*[clinic input]
3674_ssl._SSLContext.get_ca_certs
3675 binary_form: bool = False
3676
3677Returns a list of dicts with information of loaded CA certs.
3678
3679If the optional argument is True, returns a DER-encoded copy of the CA
3680certificate.
3681
3682NOTE: Certificates in a capath directory aren't loaded unless they have
3683been used at least once.
3684[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003685
3686static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003687_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3688/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003689{
3690 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003691 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003692 PyObject *ci = NULL, *rlist = NULL;
3693 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003694
3695 if ((rlist = PyList_New(0)) == NULL) {
3696 return NULL;
3697 }
3698
3699 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003700 objs = X509_STORE_get0_objects(store);
3701 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003702 X509_OBJECT *obj;
3703 X509 *cert;
3704
Christian Heimes598894f2016-09-05 23:19:05 +02003705 obj = sk_X509_OBJECT_value(objs, i);
3706 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003707 /* not a x509 cert */
3708 continue;
3709 }
3710 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003711 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003712 if (!X509_check_ca(cert)) {
3713 continue;
3714 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003715 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003716 ci = _certificate_to_der(cert);
3717 } else {
3718 ci = _decode_certificate(cert);
3719 }
3720 if (ci == NULL) {
3721 goto error;
3722 }
3723 if (PyList_Append(rlist, ci) == -1) {
3724 goto error;
3725 }
3726 Py_CLEAR(ci);
3727 }
3728 return rlist;
3729
3730 error:
3731 Py_XDECREF(ci);
3732 Py_XDECREF(rlist);
3733 return NULL;
3734}
3735
3736
Antoine Pitrou152efa22010-05-16 18:19:27 +00003737static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003738 {"check_hostname", (getter) get_check_hostname,
3739 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003740 {"options", (getter) get_options,
3741 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003742 {"verify_flags", (getter) get_verify_flags,
3743 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003744 {"verify_mode", (getter) get_verify_mode,
3745 (setter) set_verify_mode, NULL},
3746 {NULL}, /* sentinel */
3747};
3748
3749static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003750 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
3751 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
3752 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
3753 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
3754 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
3755 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
3756 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
3757 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
3758 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
3759 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
3760 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
3761 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
3762 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
3763 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02003764 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00003765 {NULL, NULL} /* sentinel */
3766};
3767
3768static PyTypeObject PySSLContext_Type = {
3769 PyVarObject_HEAD_INIT(NULL, 0)
3770 "_ssl._SSLContext", /*tp_name*/
3771 sizeof(PySSLContext), /*tp_basicsize*/
3772 0, /*tp_itemsize*/
3773 (destructor)context_dealloc, /*tp_dealloc*/
3774 0, /*tp_print*/
3775 0, /*tp_getattr*/
3776 0, /*tp_setattr*/
3777 0, /*tp_reserved*/
3778 0, /*tp_repr*/
3779 0, /*tp_as_number*/
3780 0, /*tp_as_sequence*/
3781 0, /*tp_as_mapping*/
3782 0, /*tp_hash*/
3783 0, /*tp_call*/
3784 0, /*tp_str*/
3785 0, /*tp_getattro*/
3786 0, /*tp_setattro*/
3787 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003788 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003789 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003790 (traverseproc) context_traverse, /*tp_traverse*/
3791 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003792 0, /*tp_richcompare*/
3793 0, /*tp_weaklistoffset*/
3794 0, /*tp_iter*/
3795 0, /*tp_iternext*/
3796 context_methods, /*tp_methods*/
3797 0, /*tp_members*/
3798 context_getsetlist, /*tp_getset*/
3799 0, /*tp_base*/
3800 0, /*tp_dict*/
3801 0, /*tp_descr_get*/
3802 0, /*tp_descr_set*/
3803 0, /*tp_dictoffset*/
3804 0, /*tp_init*/
3805 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003806 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003807};
3808
3809
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003810/*
3811 * MemoryBIO objects
3812 */
3813
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003814/*[clinic input]
3815@classmethod
3816_ssl.MemoryBIO.__new__
3817
3818[clinic start generated code]*/
3819
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003820static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003821_ssl_MemoryBIO_impl(PyTypeObject *type)
3822/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003823{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003824 BIO *bio;
3825 PySSLMemoryBIO *self;
3826
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003827 bio = BIO_new(BIO_s_mem());
3828 if (bio == NULL) {
3829 PyErr_SetString(PySSLErrorObject,
3830 "failed to allocate BIO");
3831 return NULL;
3832 }
3833 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3834 * just that no data is currently available. The SSL routines should retry
3835 * the read, which we can achieve by calling BIO_set_retry_read(). */
3836 BIO_set_retry_read(bio);
3837 BIO_set_mem_eof_return(bio, -1);
3838
3839 assert(type != NULL && type->tp_alloc != NULL);
3840 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3841 if (self == NULL) {
3842 BIO_free(bio);
3843 return NULL;
3844 }
3845 self->bio = bio;
3846 self->eof_written = 0;
3847
3848 return (PyObject *) self;
3849}
3850
3851static void
3852memory_bio_dealloc(PySSLMemoryBIO *self)
3853{
3854 BIO_free(self->bio);
3855 Py_TYPE(self)->tp_free(self);
3856}
3857
3858static PyObject *
3859memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3860{
3861 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3862}
3863
3864PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3865"The number of bytes pending in the memory BIO.");
3866
3867static PyObject *
3868memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3869{
3870 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3871 && self->eof_written);
3872}
3873
3874PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3875"Whether the memory BIO is at EOF.");
3876
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003877/*[clinic input]
3878_ssl.MemoryBIO.read
3879 size as len: int = -1
3880 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003881
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003882Read up to size bytes from the memory BIO.
3883
3884If size is not specified, read the entire buffer.
3885If the return value is an empty bytes instance, this means either
3886EOF or that no data is available. Use the "eof" property to
3887distinguish between the two.
3888[clinic start generated code]*/
3889
3890static PyObject *
3891_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
3892/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
3893{
3894 int avail, nbytes;
3895 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003896
3897 avail = BIO_ctrl_pending(self->bio);
3898 if ((len < 0) || (len > avail))
3899 len = avail;
3900
3901 result = PyBytes_FromStringAndSize(NULL, len);
3902 if ((result == NULL) || (len == 0))
3903 return result;
3904
3905 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3906 /* There should never be any short reads but check anyway. */
3907 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3908 Py_DECREF(result);
3909 return NULL;
3910 }
3911
3912 return result;
3913}
3914
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003915/*[clinic input]
3916_ssl.MemoryBIO.write
3917 b: Py_buffer
3918 /
3919
3920Writes the bytes b into the memory BIO.
3921
3922Returns the number of bytes written.
3923[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003924
3925static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003926_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
3927/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003928{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003929 int nbytes;
3930
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003931 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003932 PyErr_Format(PyExc_OverflowError,
3933 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003934 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003935 }
3936
3937 if (self->eof_written) {
3938 PyErr_SetString(PySSLErrorObject,
3939 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003940 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003941 }
3942
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003943 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003944 if (nbytes < 0) {
3945 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003946 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003947 }
3948
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003949 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003950}
3951
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003952/*[clinic input]
3953_ssl.MemoryBIO.write_eof
3954
3955Write an EOF marker to the memory BIO.
3956
3957When all data has been read, the "eof" property will be True.
3958[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003959
3960static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003961_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
3962/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003963{
3964 self->eof_written = 1;
3965 /* After an EOF is written, a zero return from read() should be a real EOF
3966 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3967 BIO_clear_retry_flags(self->bio);
3968 BIO_set_mem_eof_return(self->bio, 0);
3969
3970 Py_RETURN_NONE;
3971}
3972
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003973static PyGetSetDef memory_bio_getsetlist[] = {
3974 {"pending", (getter) memory_bio_get_pending, NULL,
3975 PySSL_memory_bio_pending_doc},
3976 {"eof", (getter) memory_bio_get_eof, NULL,
3977 PySSL_memory_bio_eof_doc},
3978 {NULL}, /* sentinel */
3979};
3980
3981static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003982 _SSL_MEMORYBIO_READ_METHODDEF
3983 _SSL_MEMORYBIO_WRITE_METHODDEF
3984 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003985 {NULL, NULL} /* sentinel */
3986};
3987
3988static PyTypeObject PySSLMemoryBIO_Type = {
3989 PyVarObject_HEAD_INIT(NULL, 0)
3990 "_ssl.MemoryBIO", /*tp_name*/
3991 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3992 0, /*tp_itemsize*/
3993 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3994 0, /*tp_print*/
3995 0, /*tp_getattr*/
3996 0, /*tp_setattr*/
3997 0, /*tp_reserved*/
3998 0, /*tp_repr*/
3999 0, /*tp_as_number*/
4000 0, /*tp_as_sequence*/
4001 0, /*tp_as_mapping*/
4002 0, /*tp_hash*/
4003 0, /*tp_call*/
4004 0, /*tp_str*/
4005 0, /*tp_getattro*/
4006 0, /*tp_setattro*/
4007 0, /*tp_as_buffer*/
4008 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4009 0, /*tp_doc*/
4010 0, /*tp_traverse*/
4011 0, /*tp_clear*/
4012 0, /*tp_richcompare*/
4013 0, /*tp_weaklistoffset*/
4014 0, /*tp_iter*/
4015 0, /*tp_iternext*/
4016 memory_bio_methods, /*tp_methods*/
4017 0, /*tp_members*/
4018 memory_bio_getsetlist, /*tp_getset*/
4019 0, /*tp_base*/
4020 0, /*tp_dict*/
4021 0, /*tp_descr_get*/
4022 0, /*tp_descr_set*/
4023 0, /*tp_dictoffset*/
4024 0, /*tp_init*/
4025 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004026 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004027};
4028
Antoine Pitrou152efa22010-05-16 18:19:27 +00004029
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004030/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004031/*[clinic input]
4032_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004033 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004034 entropy: double
4035 /
4036
4037Mix string into the OpenSSL PRNG state.
4038
4039entropy (a float) is a lower bound on the entropy contained in
4040string. See RFC 1750.
4041[clinic start generated code]*/
4042
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004043static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004044_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
4045/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004046{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004047 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004048 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004049
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004050 buf = (const char *)view->buf;
4051 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004052 do {
4053 written = Py_MIN(len, INT_MAX);
4054 RAND_add(buf, (int)written, entropy);
4055 buf += written;
4056 len -= written;
4057 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004058 Py_INCREF(Py_None);
4059 return Py_None;
4060}
4061
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004062static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004063PySSL_RAND(int len, int pseudo)
4064{
4065 int ok;
4066 PyObject *bytes;
4067 unsigned long err;
4068 const char *errstr;
4069 PyObject *v;
4070
Victor Stinner1e81a392013-12-19 16:47:04 +01004071 if (len < 0) {
4072 PyErr_SetString(PyExc_ValueError, "num must be positive");
4073 return NULL;
4074 }
4075
Victor Stinner99c8b162011-05-24 12:05:19 +02004076 bytes = PyBytes_FromStringAndSize(NULL, len);
4077 if (bytes == NULL)
4078 return NULL;
4079 if (pseudo) {
4080 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4081 if (ok == 0 || ok == 1)
4082 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4083 }
4084 else {
4085 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4086 if (ok == 1)
4087 return bytes;
4088 }
4089 Py_DECREF(bytes);
4090
4091 err = ERR_get_error();
4092 errstr = ERR_reason_error_string(err);
4093 v = Py_BuildValue("(ks)", err, errstr);
4094 if (v != NULL) {
4095 PyErr_SetObject(PySSLErrorObject, v);
4096 Py_DECREF(v);
4097 }
4098 return NULL;
4099}
4100
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004101/*[clinic input]
4102_ssl.RAND_bytes
4103 n: int
4104 /
4105
4106Generate n cryptographically strong pseudo-random bytes.
4107[clinic start generated code]*/
4108
Victor Stinner99c8b162011-05-24 12:05:19 +02004109static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004110_ssl_RAND_bytes_impl(PyObject *module, int n)
4111/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004112{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004113 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004114}
4115
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004116/*[clinic input]
4117_ssl.RAND_pseudo_bytes
4118 n: int
4119 /
4120
4121Generate n pseudo-random bytes.
4122
4123Return a pair (bytes, is_cryptographic). is_cryptographic is True
4124if the bytes generated are cryptographically strong.
4125[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004126
4127static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004128_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4129/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004130{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004131 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004132}
4133
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004134/*[clinic input]
4135_ssl.RAND_status
4136
4137Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4138
4139It is necessary to seed the PRNG with RAND_add() on some platforms before
4140using the ssl() function.
4141[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004142
4143static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004144_ssl_RAND_status_impl(PyObject *module)
4145/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004146{
Christian Heimes217cfd12007-12-02 14:31:20 +00004147 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004148}
4149
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004150#ifndef OPENSSL_NO_EGD
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004151/*[clinic input]
4152_ssl.RAND_egd
4153 path: object(converter="PyUnicode_FSConverter")
4154 /
4155
4156Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4157
4158Returns number of bytes read. Raises SSLError if connection to EGD
4159fails or if it does not provide enough data to seed PRNG.
4160[clinic start generated code]*/
4161
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004162static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004163_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4164/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004165{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004166 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004167 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004168 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004169 PyErr_SetString(PySSLErrorObject,
4170 "EGD connection failed or EGD did not return "
4171 "enough data to seed the PRNG");
4172 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004173 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004174 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004175}
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004176#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004177
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004178
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004179
4180/*[clinic input]
4181_ssl.get_default_verify_paths
4182
4183Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4184
4185The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4186[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004187
4188static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004189_ssl_get_default_verify_paths_impl(PyObject *module)
4190/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004191{
4192 PyObject *ofile_env = NULL;
4193 PyObject *ofile = NULL;
4194 PyObject *odir_env = NULL;
4195 PyObject *odir = NULL;
4196
Benjamin Petersond113c962015-07-18 10:59:13 -07004197#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004198 const char *tmp = (info); \
4199 target = NULL; \
4200 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4201 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4202 target = PyBytes_FromString(tmp); } \
4203 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004204 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004205
Benjamin Petersond113c962015-07-18 10:59:13 -07004206 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4207 CONVERT(X509_get_default_cert_file(), ofile);
4208 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4209 CONVERT(X509_get_default_cert_dir(), odir);
4210#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004211
Christian Heimes200bb1b2013-06-14 15:14:29 +02004212 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004213
4214 error:
4215 Py_XDECREF(ofile_env);
4216 Py_XDECREF(ofile);
4217 Py_XDECREF(odir_env);
4218 Py_XDECREF(odir);
4219 return NULL;
4220}
4221
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004222static PyObject*
4223asn1obj2py(ASN1_OBJECT *obj)
4224{
4225 int nid;
4226 const char *ln, *sn;
4227 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004228 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004229
4230 nid = OBJ_obj2nid(obj);
4231 if (nid == NID_undef) {
4232 PyErr_Format(PyExc_ValueError, "Unknown object");
4233 return NULL;
4234 }
4235 sn = OBJ_nid2sn(nid);
4236 ln = OBJ_nid2ln(nid);
4237 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4238 if (buflen < 0) {
4239 _setSSLError(NULL, 0, __FILE__, __LINE__);
4240 return NULL;
4241 }
4242 if (buflen) {
4243 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4244 } else {
4245 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4246 }
4247}
4248
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004249/*[clinic input]
4250_ssl.txt2obj
4251 txt: str
4252 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004253
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004254Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4255
4256By default objects are looked up by OID. With name=True short and
4257long name are also matched.
4258[clinic start generated code]*/
4259
4260static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004261_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4262/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004263{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004264 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004265 ASN1_OBJECT *obj;
4266
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004267 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4268 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004269 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004270 return NULL;
4271 }
4272 result = asn1obj2py(obj);
4273 ASN1_OBJECT_free(obj);
4274 return result;
4275}
4276
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004277/*[clinic input]
4278_ssl.nid2obj
4279 nid: int
4280 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004281
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004282Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4283[clinic start generated code]*/
4284
4285static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004286_ssl_nid2obj_impl(PyObject *module, int nid)
4287/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004288{
4289 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004290 ASN1_OBJECT *obj;
4291
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004292 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004293 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004294 return NULL;
4295 }
4296 obj = OBJ_nid2obj(nid);
4297 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004298 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004299 return NULL;
4300 }
4301 result = asn1obj2py(obj);
4302 ASN1_OBJECT_free(obj);
4303 return result;
4304}
4305
Christian Heimes46bebee2013-06-09 19:03:31 +02004306#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004307
4308static PyObject*
4309certEncodingType(DWORD encodingType)
4310{
4311 static PyObject *x509_asn = NULL;
4312 static PyObject *pkcs_7_asn = NULL;
4313
4314 if (x509_asn == NULL) {
4315 x509_asn = PyUnicode_InternFromString("x509_asn");
4316 if (x509_asn == NULL)
4317 return NULL;
4318 }
4319 if (pkcs_7_asn == NULL) {
4320 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4321 if (pkcs_7_asn == NULL)
4322 return NULL;
4323 }
4324 switch(encodingType) {
4325 case X509_ASN_ENCODING:
4326 Py_INCREF(x509_asn);
4327 return x509_asn;
4328 case PKCS_7_ASN_ENCODING:
4329 Py_INCREF(pkcs_7_asn);
4330 return pkcs_7_asn;
4331 default:
4332 return PyLong_FromLong(encodingType);
4333 }
4334}
4335
4336static PyObject*
4337parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4338{
4339 CERT_ENHKEY_USAGE *usage;
4340 DWORD size, error, i;
4341 PyObject *retval;
4342
4343 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4344 error = GetLastError();
4345 if (error == CRYPT_E_NOT_FOUND) {
4346 Py_RETURN_TRUE;
4347 }
4348 return PyErr_SetFromWindowsErr(error);
4349 }
4350
4351 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4352 if (usage == NULL) {
4353 return PyErr_NoMemory();
4354 }
4355
4356 /* Now get the actual enhanced usage property */
4357 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4358 PyMem_Free(usage);
4359 error = GetLastError();
4360 if (error == CRYPT_E_NOT_FOUND) {
4361 Py_RETURN_TRUE;
4362 }
4363 return PyErr_SetFromWindowsErr(error);
4364 }
4365 retval = PySet_New(NULL);
4366 if (retval == NULL) {
4367 goto error;
4368 }
4369 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4370 if (usage->rgpszUsageIdentifier[i]) {
4371 PyObject *oid;
4372 int err;
4373 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4374 if (oid == NULL) {
4375 Py_CLEAR(retval);
4376 goto error;
4377 }
4378 err = PySet_Add(retval, oid);
4379 Py_DECREF(oid);
4380 if (err == -1) {
4381 Py_CLEAR(retval);
4382 goto error;
4383 }
4384 }
4385 }
4386 error:
4387 PyMem_Free(usage);
4388 return retval;
4389}
4390
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004391/*[clinic input]
4392_ssl.enum_certificates
4393 store_name: str
4394
4395Retrieve certificates from Windows' cert store.
4396
4397store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4398more cert storages, too. The function returns a list of (bytes,
4399encoding_type, trust) tuples. The encoding_type flag can be interpreted
4400with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4401a set of OIDs or the boolean True.
4402[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004403
Christian Heimes46bebee2013-06-09 19:03:31 +02004404static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004405_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4406/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004407{
Christian Heimes46bebee2013-06-09 19:03:31 +02004408 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004409 PCCERT_CONTEXT pCertCtx = NULL;
4410 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004411 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004412
Christian Heimes44109d72013-11-22 01:51:30 +01004413 result = PyList_New(0);
4414 if (result == NULL) {
4415 return NULL;
4416 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004417 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4418 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4419 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004420 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004421 Py_DECREF(result);
4422 return PyErr_SetFromWindowsErr(GetLastError());
4423 }
4424
Christian Heimes44109d72013-11-22 01:51:30 +01004425 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4426 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4427 pCertCtx->cbCertEncoded);
4428 if (!cert) {
4429 Py_CLEAR(result);
4430 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004431 }
Christian Heimes44109d72013-11-22 01:51:30 +01004432 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4433 Py_CLEAR(result);
4434 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004435 }
Christian Heimes44109d72013-11-22 01:51:30 +01004436 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4437 if (keyusage == Py_True) {
4438 Py_DECREF(keyusage);
4439 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004440 }
Christian Heimes44109d72013-11-22 01:51:30 +01004441 if (keyusage == NULL) {
4442 Py_CLEAR(result);
4443 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004444 }
Christian Heimes44109d72013-11-22 01:51:30 +01004445 if ((tup = PyTuple_New(3)) == NULL) {
4446 Py_CLEAR(result);
4447 break;
4448 }
4449 PyTuple_SET_ITEM(tup, 0, cert);
4450 cert = NULL;
4451 PyTuple_SET_ITEM(tup, 1, enc);
4452 enc = NULL;
4453 PyTuple_SET_ITEM(tup, 2, keyusage);
4454 keyusage = NULL;
4455 if (PyList_Append(result, tup) < 0) {
4456 Py_CLEAR(result);
4457 break;
4458 }
4459 Py_CLEAR(tup);
4460 }
4461 if (pCertCtx) {
4462 /* loop ended with an error, need to clean up context manually */
4463 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004464 }
4465
4466 /* In error cases cert, enc and tup may not be NULL */
4467 Py_XDECREF(cert);
4468 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004469 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004470 Py_XDECREF(tup);
4471
4472 if (!CertCloseStore(hStore, 0)) {
4473 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004474 Py_XDECREF(result);
4475 return PyErr_SetFromWindowsErr(GetLastError());
4476 }
4477 return result;
4478}
4479
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004480/*[clinic input]
4481_ssl.enum_crls
4482 store_name: str
4483
4484Retrieve CRLs from Windows' cert store.
4485
4486store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4487more cert storages, too. The function returns a list of (bytes,
4488encoding_type) tuples. The encoding_type flag can be interpreted with
4489X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4490[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004491
4492static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004493_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4494/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004495{
Christian Heimes44109d72013-11-22 01:51:30 +01004496 HCERTSTORE hStore = NULL;
4497 PCCRL_CONTEXT pCrlCtx = NULL;
4498 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4499 PyObject *result = NULL;
4500
Christian Heimes44109d72013-11-22 01:51:30 +01004501 result = PyList_New(0);
4502 if (result == NULL) {
4503 return NULL;
4504 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004505 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4506 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4507 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004508 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004509 Py_DECREF(result);
4510 return PyErr_SetFromWindowsErr(GetLastError());
4511 }
Christian Heimes44109d72013-11-22 01:51:30 +01004512
4513 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4514 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4515 pCrlCtx->cbCrlEncoded);
4516 if (!crl) {
4517 Py_CLEAR(result);
4518 break;
4519 }
4520 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4521 Py_CLEAR(result);
4522 break;
4523 }
4524 if ((tup = PyTuple_New(2)) == NULL) {
4525 Py_CLEAR(result);
4526 break;
4527 }
4528 PyTuple_SET_ITEM(tup, 0, crl);
4529 crl = NULL;
4530 PyTuple_SET_ITEM(tup, 1, enc);
4531 enc = NULL;
4532
4533 if (PyList_Append(result, tup) < 0) {
4534 Py_CLEAR(result);
4535 break;
4536 }
4537 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004538 }
Christian Heimes44109d72013-11-22 01:51:30 +01004539 if (pCrlCtx) {
4540 /* loop ended with an error, need to clean up context manually */
4541 CertFreeCRLContext(pCrlCtx);
4542 }
4543
4544 /* In error cases cert, enc and tup may not be NULL */
4545 Py_XDECREF(crl);
4546 Py_XDECREF(enc);
4547 Py_XDECREF(tup);
4548
4549 if (!CertCloseStore(hStore, 0)) {
4550 /* This error case might shadow another exception.*/
4551 Py_XDECREF(result);
4552 return PyErr_SetFromWindowsErr(GetLastError());
4553 }
4554 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004555}
Christian Heimes44109d72013-11-22 01:51:30 +01004556
4557#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004558
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004559/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004560static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004561 _SSL__TEST_DECODE_CERT_METHODDEF
4562 _SSL_RAND_ADD_METHODDEF
4563 _SSL_RAND_BYTES_METHODDEF
4564 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4565 _SSL_RAND_EGD_METHODDEF
4566 _SSL_RAND_STATUS_METHODDEF
4567 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
4568 _SSL_ENUM_CERTIFICATES_METHODDEF
4569 _SSL_ENUM_CRLS_METHODDEF
4570 _SSL_TXT2OBJ_METHODDEF
4571 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004572 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004573};
4574
4575
Christian Heimes598894f2016-09-05 23:19:05 +02004576#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004577
4578/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02004579 * of the Python C thread library
4580 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
4581 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004582
4583static PyThread_type_lock *_ssl_locks = NULL;
4584
Christian Heimes4d98ca92013-08-19 17:36:29 +02004585#if OPENSSL_VERSION_NUMBER >= 0x10000000
4586/* use new CRYPTO_THREADID API. */
4587static void
4588_ssl_threadid_callback(CRYPTO_THREADID *id)
4589{
4590 CRYPTO_THREADID_set_numeric(id,
4591 (unsigned long)PyThread_get_thread_ident());
4592}
4593#else
4594/* deprecated CRYPTO_set_id_callback() API. */
4595static unsigned long
4596_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004597 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004598}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004599#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004600
Bill Janssen6e027db2007-11-15 22:23:56 +00004601static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004602 (int mode, int n, const char *file, int line) {
4603 /* this function is needed to perform locking on shared data
4604 structures. (Note that OpenSSL uses a number of global data
4605 structures that will be implicitly shared whenever multiple
4606 threads use OpenSSL.) Multi-threaded applications will
4607 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004608
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004609 locking_function() must be able to handle up to
4610 CRYPTO_num_locks() different mutex locks. It sets the n-th
4611 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004612
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004613 file and line are the file number of the function setting the
4614 lock. They can be useful for debugging.
4615 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004616
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004617 if ((_ssl_locks == NULL) ||
4618 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4619 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004620
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004621 if (mode & CRYPTO_LOCK) {
4622 PyThread_acquire_lock(_ssl_locks[n], 1);
4623 } else {
4624 PyThread_release_lock(_ssl_locks[n]);
4625 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004626}
4627
4628static int _setup_ssl_threads(void) {
4629
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004630 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004631
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004632 if (_ssl_locks == NULL) {
4633 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004634 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4635 if (_ssl_locks == NULL) {
4636 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004637 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004638 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004639 memset(_ssl_locks, 0,
4640 sizeof(PyThread_type_lock) * _ssl_locks_count);
4641 for (i = 0; i < _ssl_locks_count; i++) {
4642 _ssl_locks[i] = PyThread_allocate_lock();
4643 if (_ssl_locks[i] == NULL) {
4644 unsigned int j;
4645 for (j = 0; j < i; j++) {
4646 PyThread_free_lock(_ssl_locks[j]);
4647 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004648 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004649 return 0;
4650 }
4651 }
4652 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004653#if OPENSSL_VERSION_NUMBER >= 0x10000000
4654 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4655#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004656 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004657#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004658 }
4659 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004660}
4661
Christian Heimes598894f2016-09-05 23:19:05 +02004662#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004663
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004664PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004665"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004666for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004667
Martin v. Löwis1a214512008-06-11 05:26:20 +00004668
4669static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004670 PyModuleDef_HEAD_INIT,
4671 "_ssl",
4672 module_doc,
4673 -1,
4674 PySSL_methods,
4675 NULL,
4676 NULL,
4677 NULL,
4678 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004679};
4680
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004681
4682static void
4683parse_openssl_version(unsigned long libver,
4684 unsigned int *major, unsigned int *minor,
4685 unsigned int *fix, unsigned int *patch,
4686 unsigned int *status)
4687{
4688 *status = libver & 0xF;
4689 libver >>= 4;
4690 *patch = libver & 0xFF;
4691 libver >>= 8;
4692 *fix = libver & 0xFF;
4693 libver >>= 8;
4694 *minor = libver & 0xFF;
4695 libver >>= 8;
4696 *major = libver & 0xFF;
4697}
4698
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004699PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004700PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004701{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004702 PyObject *m, *d, *r;
4703 unsigned long libver;
4704 unsigned int major, minor, fix, patch, status;
4705 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004706 struct py_ssl_error_code *errcode;
4707 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004708
Antoine Pitrou152efa22010-05-16 18:19:27 +00004709 if (PyType_Ready(&PySSLContext_Type) < 0)
4710 return NULL;
4711 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004712 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004713 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4714 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004715
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004716 m = PyModule_Create(&_sslmodule);
4717 if (m == NULL)
4718 return NULL;
4719 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004720
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004721 /* Load _socket module and its C API */
4722 socket_api = PySocketModule_ImportModuleAndAPI();
4723 if (!socket_api)
4724 return NULL;
4725 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004726
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004727 /* Init OpenSSL */
4728 SSL_load_error_strings();
4729 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004730#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02004731#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004732 /* note that this will start threading if not already started */
4733 if (!_setup_ssl_threads()) {
4734 return NULL;
4735 }
Christian Heimes598894f2016-09-05 23:19:05 +02004736#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4737 /* OpenSSL 1.1.0 builtin thread support is enabled */
4738 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004739#endif
Christian Heimes598894f2016-09-05 23:19:05 +02004740#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004741 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004742
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004743 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004744 sslerror_type_slots[0].pfunc = PyExc_OSError;
4745 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004746 if (PySSLErrorObject == NULL)
4747 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004748
Antoine Pitrou41032a62011-10-27 23:56:55 +02004749 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4750 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4751 PySSLErrorObject, NULL);
4752 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4753 "ssl.SSLWantReadError", SSLWantReadError_doc,
4754 PySSLErrorObject, NULL);
4755 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4756 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4757 PySSLErrorObject, NULL);
4758 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4759 "ssl.SSLSyscallError", SSLSyscallError_doc,
4760 PySSLErrorObject, NULL);
4761 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4762 "ssl.SSLEOFError", SSLEOFError_doc,
4763 PySSLErrorObject, NULL);
4764 if (PySSLZeroReturnErrorObject == NULL
4765 || PySSLWantReadErrorObject == NULL
4766 || PySSLWantWriteErrorObject == NULL
4767 || PySSLSyscallErrorObject == NULL
4768 || PySSLEOFErrorObject == NULL)
4769 return NULL;
4770 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4771 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4772 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4773 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4774 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4775 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004776 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004777 if (PyDict_SetItemString(d, "_SSLContext",
4778 (PyObject *)&PySSLContext_Type) != 0)
4779 return NULL;
4780 if (PyDict_SetItemString(d, "_SSLSocket",
4781 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004782 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004783 if (PyDict_SetItemString(d, "MemoryBIO",
4784 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4785 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004786 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4787 PY_SSL_ERROR_ZERO_RETURN);
4788 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4789 PY_SSL_ERROR_WANT_READ);
4790 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4791 PY_SSL_ERROR_WANT_WRITE);
4792 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4793 PY_SSL_ERROR_WANT_X509_LOOKUP);
4794 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4795 PY_SSL_ERROR_SYSCALL);
4796 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4797 PY_SSL_ERROR_SSL);
4798 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4799 PY_SSL_ERROR_WANT_CONNECT);
4800 /* non ssl.h errorcodes */
4801 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4802 PY_SSL_ERROR_EOF);
4803 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4804 PY_SSL_ERROR_INVALID_ERROR_CODE);
4805 /* cert requirements */
4806 PyModule_AddIntConstant(m, "CERT_NONE",
4807 PY_SSL_CERT_NONE);
4808 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4809 PY_SSL_CERT_OPTIONAL);
4810 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4811 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004812 /* CRL verification for verification_flags */
4813 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4814 0);
4815 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4816 X509_V_FLAG_CRL_CHECK);
4817 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4818 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4819 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4820 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05004821#ifdef X509_V_FLAG_TRUSTED_FIRST
4822 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4823 X509_V_FLAG_TRUSTED_FIRST);
4824#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004825
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004826 /* Alert Descriptions from ssl.h */
4827 /* note RESERVED constants no longer intended for use have been removed */
4828 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4829
4830#define ADD_AD_CONSTANT(s) \
4831 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4832 SSL_AD_##s)
4833
4834 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4835 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4836 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4837 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4838 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4839 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4840 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4841 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4842 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4843 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4844 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4845 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4846 ADD_AD_CONSTANT(UNKNOWN_CA);
4847 ADD_AD_CONSTANT(ACCESS_DENIED);
4848 ADD_AD_CONSTANT(DECODE_ERROR);
4849 ADD_AD_CONSTANT(DECRYPT_ERROR);
4850 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4851 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4852 ADD_AD_CONSTANT(INTERNAL_ERROR);
4853 ADD_AD_CONSTANT(USER_CANCELLED);
4854 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004855 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004856#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4857 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4858#endif
4859#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4860 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4861#endif
4862#ifdef SSL_AD_UNRECOGNIZED_NAME
4863 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4864#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004865#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4866 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4867#endif
4868#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4869 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4870#endif
4871#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4872 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4873#endif
4874
4875#undef ADD_AD_CONSTANT
4876
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004877 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004878#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004879 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4880 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004881#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004882#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004883 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4884 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004885#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004886 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02004887 PY_SSL_VERSION_TLS);
4888 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4889 PY_SSL_VERSION_TLS);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004890 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4891 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004892#if HAVE_TLSv1_2
4893 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4894 PY_SSL_VERSION_TLS1_1);
4895 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4896 PY_SSL_VERSION_TLS1_2);
4897#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004898
Antoine Pitroub5218772010-05-21 09:56:06 +00004899 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004900 PyModule_AddIntConstant(m, "OP_ALL",
4901 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004902 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4903 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4904 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004905#if HAVE_TLSv1_2
4906 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4907 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4908#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004909 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4910 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004911 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004912#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004913 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004914#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004915#ifdef SSL_OP_NO_COMPRESSION
4916 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4917 SSL_OP_NO_COMPRESSION);
4918#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004919
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004920#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004921 r = Py_True;
4922#else
4923 r = Py_False;
4924#endif
4925 Py_INCREF(r);
4926 PyModule_AddObject(m, "HAS_SNI", r);
4927
Antoine Pitroud6494802011-07-21 01:11:30 +02004928 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004929 Py_INCREF(r);
4930 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4931
Antoine Pitrou501da612011-12-21 09:27:41 +01004932#ifdef OPENSSL_NO_ECDH
4933 r = Py_False;
4934#else
4935 r = Py_True;
4936#endif
4937 Py_INCREF(r);
4938 PyModule_AddObject(m, "HAS_ECDH", r);
4939
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004940#ifdef OPENSSL_NPN_NEGOTIATED
4941 r = Py_True;
4942#else
4943 r = Py_False;
4944#endif
4945 Py_INCREF(r);
4946 PyModule_AddObject(m, "HAS_NPN", r);
4947
Benjamin Petersoncca27322015-01-23 16:35:37 -05004948#ifdef HAVE_ALPN
4949 r = Py_True;
4950#else
4951 r = Py_False;
4952#endif
4953 Py_INCREF(r);
4954 PyModule_AddObject(m, "HAS_ALPN", r);
4955
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004956 /* Mappings for error codes */
4957 err_codes_to_names = PyDict_New();
4958 err_names_to_codes = PyDict_New();
4959 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4960 return NULL;
4961 errcode = error_codes;
4962 while (errcode->mnemonic != NULL) {
4963 PyObject *mnemo, *key;
4964 mnemo = PyUnicode_FromString(errcode->mnemonic);
4965 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4966 if (mnemo == NULL || key == NULL)
4967 return NULL;
4968 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4969 return NULL;
4970 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4971 return NULL;
4972 Py_DECREF(key);
4973 Py_DECREF(mnemo);
4974 errcode++;
4975 }
4976 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4977 return NULL;
4978 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4979 return NULL;
4980
4981 lib_codes_to_names = PyDict_New();
4982 if (lib_codes_to_names == NULL)
4983 return NULL;
4984 libcode = library_codes;
4985 while (libcode->library != NULL) {
4986 PyObject *mnemo, *key;
4987 key = PyLong_FromLong(libcode->code);
4988 mnemo = PyUnicode_FromString(libcode->library);
4989 if (key == NULL || mnemo == NULL)
4990 return NULL;
4991 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4992 return NULL;
4993 Py_DECREF(key);
4994 Py_DECREF(mnemo);
4995 libcode++;
4996 }
4997 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4998 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004999
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005000 /* OpenSSL version */
5001 /* SSLeay() gives us the version of the library linked against,
5002 which could be different from the headers version.
5003 */
5004 libver = SSLeay();
5005 r = PyLong_FromUnsignedLong(libver);
5006 if (r == NULL)
5007 return NULL;
5008 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5009 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005010 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005011 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5012 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5013 return NULL;
5014 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5015 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5016 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005017
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005018 libver = OPENSSL_VERSION_NUMBER;
5019 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5020 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5021 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5022 return NULL;
5023
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005024 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005025}