blob: 151029a50b91f212e2c3b5e1aac5d70968650d53 [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
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001522/*[clinic input]
1523_ssl._SSLSocket.shared_ciphers
1524[clinic start generated code]*/
1525
1526static PyObject *
1527_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1528/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001529{
1530 STACK_OF(SSL_CIPHER) *ciphers;
1531 int i;
1532 PyObject *res;
1533
Christian Heimes598894f2016-09-05 23:19:05 +02001534 ciphers = SSL_get_ciphers(self->ssl);
1535 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001536 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001537 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1538 if (!res)
1539 return NULL;
1540 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1541 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1542 if (!tup) {
1543 Py_DECREF(res);
1544 return NULL;
1545 }
1546 PyList_SET_ITEM(res, i, tup);
1547 }
1548 return res;
1549}
1550
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001551/*[clinic input]
1552_ssl._SSLSocket.cipher
1553[clinic start generated code]*/
1554
1555static PyObject *
1556_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1557/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001558{
1559 const SSL_CIPHER *current;
1560
1561 if (self->ssl == NULL)
1562 Py_RETURN_NONE;
1563 current = SSL_get_current_cipher(self->ssl);
1564 if (current == NULL)
1565 Py_RETURN_NONE;
1566 return cipher_to_tuple(current);
1567}
1568
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001569/*[clinic input]
1570_ssl._SSLSocket.version
1571[clinic start generated code]*/
1572
1573static PyObject *
1574_ssl__SSLSocket_version_impl(PySSLSocket *self)
1575/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001576{
1577 const char *version;
1578
1579 if (self->ssl == NULL)
1580 Py_RETURN_NONE;
1581 version = SSL_get_version(self->ssl);
1582 if (!strcmp(version, "unknown"))
1583 Py_RETURN_NONE;
1584 return PyUnicode_FromString(version);
1585}
1586
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001587#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001588/*[clinic input]
1589_ssl._SSLSocket.selected_npn_protocol
1590[clinic start generated code]*/
1591
1592static PyObject *
1593_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1594/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1595{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001596 const unsigned char *out;
1597 unsigned int outlen;
1598
Victor Stinner4569cd52013-06-23 14:58:43 +02001599 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001600 &out, &outlen);
1601
1602 if (out == NULL)
1603 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001604 return PyUnicode_FromStringAndSize((char *)out, outlen);
1605}
1606#endif
1607
1608#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001609/*[clinic input]
1610_ssl._SSLSocket.selected_alpn_protocol
1611[clinic start generated code]*/
1612
1613static PyObject *
1614_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1615/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1616{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001617 const unsigned char *out;
1618 unsigned int outlen;
1619
1620 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1621
1622 if (out == NULL)
1623 Py_RETURN_NONE;
1624 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001625}
1626#endif
1627
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001628/*[clinic input]
1629_ssl._SSLSocket.compression
1630[clinic start generated code]*/
1631
1632static PyObject *
1633_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1634/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1635{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001636#ifdef OPENSSL_NO_COMP
1637 Py_RETURN_NONE;
1638#else
1639 const COMP_METHOD *comp_method;
1640 const char *short_name;
1641
1642 if (self->ssl == NULL)
1643 Py_RETURN_NONE;
1644 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001645 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001646 Py_RETURN_NONE;
Christian Heimes598894f2016-09-05 23:19:05 +02001647 short_name = COMP_get_name(comp_method);
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001648 if (short_name == NULL)
1649 Py_RETURN_NONE;
1650 return PyUnicode_DecodeFSDefault(short_name);
1651#endif
1652}
1653
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001654static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1655 Py_INCREF(self->ctx);
1656 return self->ctx;
1657}
1658
1659static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1660 void *closure) {
1661
1662 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001663#if !HAVE_SNI
1664 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1665 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001666 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001667#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001668 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001669 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001670 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001671#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001672 } else {
1673 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1674 return -1;
1675 }
1676
1677 return 0;
1678}
1679
1680PyDoc_STRVAR(PySSL_set_context_doc,
1681"_setter_context(ctx)\n\
1682\
1683This changes the context associated with the SSLSocket. This is typically\n\
1684used from within a callback function set by the set_servername_callback\n\
1685on the SSLContext to change the certificate information associated with the\n\
1686SSLSocket before the cryptographic exchange handshake messages\n");
1687
1688
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001689static PyObject *
1690PySSL_get_server_side(PySSLSocket *self, void *c)
1691{
1692 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1693}
1694
1695PyDoc_STRVAR(PySSL_get_server_side_doc,
1696"Whether this is a server-side socket.");
1697
1698static PyObject *
1699PySSL_get_server_hostname(PySSLSocket *self, void *c)
1700{
1701 if (self->server_hostname == NULL)
1702 Py_RETURN_NONE;
1703 Py_INCREF(self->server_hostname);
1704 return self->server_hostname;
1705}
1706
1707PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1708"The currently set server hostname (for SNI).");
1709
1710static PyObject *
1711PySSL_get_owner(PySSLSocket *self, void *c)
1712{
1713 PyObject *owner;
1714
1715 if (self->owner == NULL)
1716 Py_RETURN_NONE;
1717
1718 owner = PyWeakref_GetObject(self->owner);
1719 Py_INCREF(owner);
1720 return owner;
1721}
1722
1723static int
1724PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1725{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001726 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001727 if (self->owner == NULL)
1728 return -1;
1729 return 0;
1730}
1731
1732PyDoc_STRVAR(PySSL_get_owner_doc,
1733"The Python-level owner of this object.\
1734Passed as \"self\" in servername callback.");
1735
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001736
Antoine Pitrou152efa22010-05-16 18:19:27 +00001737static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001738{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001739 if (self->peer_cert) /* Possible not to have one? */
1740 X509_free (self->peer_cert);
1741 if (self->ssl)
1742 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001743 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001744 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001745 Py_XDECREF(self->server_hostname);
1746 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001747 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001748}
1749
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001750/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001751 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001752 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001753 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001754
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001755static int
Victor Stinner14690702015-04-06 22:46:13 +02001756PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001757{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001758 int rc;
1759#ifdef HAVE_POLL
1760 struct pollfd pollfd;
1761 _PyTime_t ms;
1762#else
1763 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001764 fd_set fds;
1765 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001766#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001767
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001768 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001769 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001770 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001771 else if (timeout < 0) {
1772 if (s->sock_timeout > 0)
1773 return SOCKET_HAS_TIMED_OUT;
1774 else
1775 return SOCKET_IS_BLOCKING;
1776 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001777
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001778 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001779 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001780 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001781
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001782 /* Prefer poll, if available, since you can poll() any fd
1783 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001784#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001785 pollfd.fd = s->sock_fd;
1786 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001787
Victor Stinner14690702015-04-06 22:46:13 +02001788 /* timeout is in seconds, poll() uses milliseconds */
1789 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001790 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001791
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001792 PySSL_BEGIN_ALLOW_THREADS
1793 rc = poll(&pollfd, 1, (int)ms);
1794 PySSL_END_ALLOW_THREADS
1795#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001796 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001797 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001798 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001799
Victor Stinner14690702015-04-06 22:46:13 +02001800 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001801
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001802 FD_ZERO(&fds);
1803 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001804
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001805 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001806 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001807 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001808 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001809 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001811 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001812 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001813#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001814
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001815 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1816 (when we are able to write or when there's something to read) */
1817 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001818}
1819
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001820/*[clinic input]
1821_ssl._SSLSocket.write
1822 b: Py_buffer
1823 /
1824
1825Writes the bytes-like object b into the SSL object.
1826
1827Returns the number of bytes written.
1828[clinic start generated code]*/
1829
1830static PyObject *
1831_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1832/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001833{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001834 int len;
1835 int sockstate;
1836 int err;
1837 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001838 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001839 _PyTime_t timeout, deadline = 0;
1840 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001841
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001842 if (sock != NULL) {
1843 if (((PyObject*)sock) == Py_None) {
1844 _setSSLError("Underlying socket connection gone",
1845 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1846 return NULL;
1847 }
1848 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001849 }
1850
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001851 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001852 PyErr_Format(PyExc_OverflowError,
1853 "string longer than %d bytes", INT_MAX);
1854 goto error;
1855 }
1856
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001857 if (sock != NULL) {
1858 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001859 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001860 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1861 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1862 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001863
Victor Stinner14690702015-04-06 22:46:13 +02001864 timeout = GET_SOCKET_TIMEOUT(sock);
1865 has_timeout = (timeout > 0);
1866 if (has_timeout)
1867 deadline = _PyTime_GetMonotonicClock() + timeout;
1868
1869 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001870 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001871 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001872 "The write operation timed out");
1873 goto error;
1874 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1875 PyErr_SetString(PySSLErrorObject,
1876 "Underlying socket has been closed.");
1877 goto error;
1878 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1879 PyErr_SetString(PySSLErrorObject,
1880 "Underlying socket too large for select().");
1881 goto error;
1882 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001883
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001884 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001885 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001886 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001887 err = SSL_get_error(self->ssl, len);
1888 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001889
1890 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001891 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001892
Victor Stinner14690702015-04-06 22:46:13 +02001893 if (has_timeout)
1894 timeout = deadline - _PyTime_GetMonotonicClock();
1895
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001896 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001897 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001898 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001899 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001900 } else {
1901 sockstate = SOCKET_OPERATION_OK;
1902 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001903
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001904 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001905 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001906 "The write operation timed out");
1907 goto error;
1908 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1909 PyErr_SetString(PySSLErrorObject,
1910 "Underlying socket has been closed.");
1911 goto error;
1912 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1913 break;
1914 }
1915 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001916
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001917 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001918 if (len > 0)
1919 return PyLong_FromLong(len);
1920 else
1921 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001922
1923error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001924 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001925 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001926}
1927
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001928/*[clinic input]
1929_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001930
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001931Returns the number of already decrypted bytes available for read, pending on the connection.
1932[clinic start generated code]*/
1933
1934static PyObject *
1935_ssl__SSLSocket_pending_impl(PySSLSocket *self)
1936/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00001937{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001938 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001939
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001940 PySSL_BEGIN_ALLOW_THREADS
1941 count = SSL_pending(self->ssl);
1942 PySSL_END_ALLOW_THREADS
1943 if (count < 0)
1944 return PySSL_SetError(self, count, __FILE__, __LINE__);
1945 else
1946 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001947}
1948
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001949/*[clinic input]
1950_ssl._SSLSocket.read
1951 size as len: int
1952 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001953 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001954 ]
1955 /
Bill Janssen6e027db2007-11-15 22:23:56 +00001956
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001957Read up to size bytes from the SSL socket.
1958[clinic start generated code]*/
1959
1960static PyObject *
1961_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
1962 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001963/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001964{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001965 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001966 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001967 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001968 int sockstate;
1969 int err;
1970 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001971 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001972 _PyTime_t timeout, deadline = 0;
1973 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001974
Martin Panter5503d472016-03-27 05:35:19 +00001975 if (!group_right_1 && len < 0) {
1976 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1977 return NULL;
1978 }
1979
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001980 if (sock != NULL) {
1981 if (((PyObject*)sock) == Py_None) {
1982 _setSSLError("Underlying socket connection gone",
1983 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1984 return NULL;
1985 }
1986 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001987 }
1988
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001989 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001990 dest = PyBytes_FromStringAndSize(NULL, len);
1991 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001992 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00001993 if (len == 0) {
1994 Py_XDECREF(sock);
1995 return dest;
1996 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001997 mem = PyBytes_AS_STRING(dest);
1998 }
1999 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002000 mem = buffer->buf;
2001 if (len <= 0 || len > buffer->len) {
2002 len = (int) buffer->len;
2003 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002004 PyErr_SetString(PyExc_OverflowError,
2005 "maximum length can't fit in a C 'int'");
2006 goto error;
2007 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002008 if (len == 0) {
2009 count = 0;
2010 goto done;
2011 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002012 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002013 }
2014
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002015 if (sock != NULL) {
2016 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002017 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002018 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2019 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2020 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002021
Victor Stinner14690702015-04-06 22:46:13 +02002022 timeout = GET_SOCKET_TIMEOUT(sock);
2023 has_timeout = (timeout > 0);
2024 if (has_timeout)
2025 deadline = _PyTime_GetMonotonicClock() + timeout;
2026
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002027 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002028 PySSL_BEGIN_ALLOW_THREADS
2029 count = SSL_read(self->ssl, mem, len);
2030 err = SSL_get_error(self->ssl, count);
2031 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002032
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002033 if (PyErr_CheckSignals())
2034 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002035
Victor Stinner14690702015-04-06 22:46:13 +02002036 if (has_timeout)
2037 timeout = deadline - _PyTime_GetMonotonicClock();
2038
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002039 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002040 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002041 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002042 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002043 } else if (err == SSL_ERROR_ZERO_RETURN &&
2044 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002045 {
2046 count = 0;
2047 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002048 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002049 else
2050 sockstate = SOCKET_OPERATION_OK;
2051
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002052 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002053 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002054 "The read operation timed out");
2055 goto error;
2056 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2057 break;
2058 }
2059 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002060
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002061 if (count <= 0) {
2062 PySSL_SetError(self, count, __FILE__, __LINE__);
2063 goto error;
2064 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002065
2066done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002067 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002068 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002069 _PyBytes_Resize(&dest, count);
2070 return dest;
2071 }
2072 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002073 return PyLong_FromLong(count);
2074 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002075
2076error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002077 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002078 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002079 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002080 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002081}
2082
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002083/*[clinic input]
2084_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002085
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002086Does the SSL shutdown handshake with the remote end.
2087
2088Returns the underlying socket object.
2089[clinic start generated code]*/
2090
2091static PyObject *
2092_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2093/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002094{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002095 int err, ssl_err, sockstate, nonblocking;
2096 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002097 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002098 _PyTime_t timeout, deadline = 0;
2099 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002100
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002101 if (sock != NULL) {
2102 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002103 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002104 _setSSLError("Underlying socket connection gone",
2105 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2106 return NULL;
2107 }
2108 Py_INCREF(sock);
2109
2110 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002111 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002112 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2113 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002114 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002115
Victor Stinner14690702015-04-06 22:46:13 +02002116 timeout = GET_SOCKET_TIMEOUT(sock);
2117 has_timeout = (timeout > 0);
2118 if (has_timeout)
2119 deadline = _PyTime_GetMonotonicClock() + timeout;
2120
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002121 while (1) {
2122 PySSL_BEGIN_ALLOW_THREADS
2123 /* Disable read-ahead so that unwrap can work correctly.
2124 * Otherwise OpenSSL might read in too much data,
2125 * eating clear text data that happens to be
2126 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002127 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002128 * function is used and the shutdown_seen_zero != 0
2129 * condition is met.
2130 */
2131 if (self->shutdown_seen_zero)
2132 SSL_set_read_ahead(self->ssl, 0);
2133 err = SSL_shutdown(self->ssl);
2134 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002135
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002136 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2137 if (err > 0)
2138 break;
2139 if (err == 0) {
2140 /* Don't loop endlessly; instead preserve legacy
2141 behaviour of trying SSL_shutdown() only twice.
2142 This looks necessary for OpenSSL < 0.9.8m */
2143 if (++zeros > 1)
2144 break;
2145 /* Shutdown was sent, now try receiving */
2146 self->shutdown_seen_zero = 1;
2147 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002148 }
2149
Victor Stinner14690702015-04-06 22:46:13 +02002150 if (has_timeout)
2151 timeout = deadline - _PyTime_GetMonotonicClock();
2152
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002153 /* Possibly retry shutdown until timeout or failure */
2154 ssl_err = SSL_get_error(self->ssl, err);
2155 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002156 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002157 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002158 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002159 else
2160 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002161
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002162 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2163 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002164 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002165 "The read operation timed out");
2166 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002167 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002168 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002169 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002170 }
2171 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2172 PyErr_SetString(PySSLErrorObject,
2173 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002174 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002175 }
2176 else if (sockstate != SOCKET_OPERATION_OK)
2177 /* Retain the SSL error code */
2178 break;
2179 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002180
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002181 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002182 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002183 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002184 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002185 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002186 /* It's already INCREF'ed */
2187 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002188 else
2189 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002190
2191error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002192 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002193 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002194}
2195
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002196/*[clinic input]
2197_ssl._SSLSocket.tls_unique_cb
2198
2199Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2200
2201If the TLS handshake is not yet complete, None is returned.
2202[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002203
Antoine Pitroud6494802011-07-21 01:11:30 +02002204static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002205_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2206/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002207{
2208 PyObject *retval = NULL;
2209 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002210 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002211
2212 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2213 /* if session is resumed XOR we are the client */
2214 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2215 }
2216 else {
2217 /* if a new session XOR we are the server */
2218 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2219 }
2220
2221 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002222 if (len == 0)
2223 Py_RETURN_NONE;
2224
2225 retval = PyBytes_FromStringAndSize(buf, len);
2226
2227 return retval;
2228}
2229
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002230static PyGetSetDef ssl_getsetlist[] = {
2231 {"context", (getter) PySSL_get_context,
2232 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002233 {"server_side", (getter) PySSL_get_server_side, NULL,
2234 PySSL_get_server_side_doc},
2235 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2236 PySSL_get_server_hostname_doc},
2237 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2238 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002239 {NULL}, /* sentinel */
2240};
2241
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002242static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002243 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2244 _SSL__SSLSOCKET_WRITE_METHODDEF
2245 _SSL__SSLSOCKET_READ_METHODDEF
2246 _SSL__SSLSOCKET_PENDING_METHODDEF
2247 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2248 _SSL__SSLSOCKET_CIPHER_METHODDEF
2249 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2250 _SSL__SSLSOCKET_VERSION_METHODDEF
2251 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2252 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2253 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2254 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2255 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002256 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002257};
2258
Antoine Pitrou152efa22010-05-16 18:19:27 +00002259static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002260 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002261 "_ssl._SSLSocket", /*tp_name*/
2262 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002263 0, /*tp_itemsize*/
2264 /* methods */
2265 (destructor)PySSL_dealloc, /*tp_dealloc*/
2266 0, /*tp_print*/
2267 0, /*tp_getattr*/
2268 0, /*tp_setattr*/
2269 0, /*tp_reserved*/
2270 0, /*tp_repr*/
2271 0, /*tp_as_number*/
2272 0, /*tp_as_sequence*/
2273 0, /*tp_as_mapping*/
2274 0, /*tp_hash*/
2275 0, /*tp_call*/
2276 0, /*tp_str*/
2277 0, /*tp_getattro*/
2278 0, /*tp_setattro*/
2279 0, /*tp_as_buffer*/
2280 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2281 0, /*tp_doc*/
2282 0, /*tp_traverse*/
2283 0, /*tp_clear*/
2284 0, /*tp_richcompare*/
2285 0, /*tp_weaklistoffset*/
2286 0, /*tp_iter*/
2287 0, /*tp_iternext*/
2288 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002289 0, /*tp_members*/
2290 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002291};
2292
Antoine Pitrou152efa22010-05-16 18:19:27 +00002293
2294/*
2295 * _SSLContext objects
2296 */
2297
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002298/*[clinic input]
2299@classmethod
2300_ssl._SSLContext.__new__
2301 protocol as proto_version: int
2302 /
2303[clinic start generated code]*/
2304
Antoine Pitrou152efa22010-05-16 18:19:27 +00002305static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002306_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2307/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002308{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002309 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002310 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002311 SSL_CTX *ctx = NULL;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002312#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002313 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002314#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002315
Antoine Pitrou152efa22010-05-16 18:19:27 +00002316 PySSL_BEGIN_ALLOW_THREADS
2317 if (proto_version == PY_SSL_VERSION_TLS1)
2318 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002319#if HAVE_TLSv1_2
2320 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2321 ctx = SSL_CTX_new(TLSv1_1_method());
2322 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2323 ctx = SSL_CTX_new(TLSv1_2_method());
2324#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002325#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002326 else if (proto_version == PY_SSL_VERSION_SSL3)
2327 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002328#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002329#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002330 else if (proto_version == PY_SSL_VERSION_SSL2)
2331 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002332#endif
Christian Heimes598894f2016-09-05 23:19:05 +02002333 else if (proto_version == PY_SSL_VERSION_TLS)
2334 ctx = SSL_CTX_new(TLS_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002335 else
2336 proto_version = -1;
2337 PySSL_END_ALLOW_THREADS
2338
2339 if (proto_version == -1) {
2340 PyErr_SetString(PyExc_ValueError,
2341 "invalid protocol version");
2342 return NULL;
2343 }
2344 if (ctx == NULL) {
2345 PyErr_SetString(PySSLErrorObject,
2346 "failed to allocate SSL context");
2347 return NULL;
2348 }
2349
2350 assert(type != NULL && type->tp_alloc != NULL);
2351 self = (PySSLContext *) type->tp_alloc(type, 0);
2352 if (self == NULL) {
2353 SSL_CTX_free(ctx);
2354 return NULL;
2355 }
2356 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002357#ifdef OPENSSL_NPN_NEGOTIATED
2358 self->npn_protocols = NULL;
2359#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002360#ifdef HAVE_ALPN
2361 self->alpn_protocols = NULL;
2362#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002363#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002364 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002365#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002366 /* Don't check host name by default */
2367 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002368 /* Defaults */
2369 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002370 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2371 if (proto_version != PY_SSL_VERSION_SSL2)
2372 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002373 if (proto_version != PY_SSL_VERSION_SSL3)
2374 options |= SSL_OP_NO_SSLv3;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002375 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002376
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002377#if defined(SSL_MODE_RELEASE_BUFFERS)
2378 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2379 usage for no cost at all. However, don't do this for OpenSSL versions
2380 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2381 2014-0198. I can't find exactly which beta fixed this CVE, so be
2382 conservative and assume it wasn't fixed until release. We do this check
2383 at runtime to avoid problems from the dynamic linker.
2384 See #25672 for more on this. */
2385 libver = SSLeay();
2386 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2387 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2388 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2389 }
2390#endif
2391
2392
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002393#ifndef OPENSSL_NO_ECDH
2394 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2395 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002396 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2397 */
2398#if defined(SSL_CTX_set_ecdh_auto) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002399 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2400#else
2401 {
2402 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2403 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2404 EC_KEY_free(key);
2405 }
2406#endif
2407#endif
2408
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002409#define SID_CTX "Python"
2410 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2411 sizeof(SID_CTX));
2412#undef SID_CTX
2413
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002414#ifdef X509_V_FLAG_TRUSTED_FIRST
2415 {
2416 /* Improve trust chain building when cross-signed intermediate
2417 certificates are present. See https://bugs.python.org/issue23476. */
2418 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2419 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2420 }
2421#endif
2422
Antoine Pitrou152efa22010-05-16 18:19:27 +00002423 return (PyObject *)self;
2424}
2425
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002426static int
2427context_traverse(PySSLContext *self, visitproc visit, void *arg)
2428{
2429#ifndef OPENSSL_NO_TLSEXT
2430 Py_VISIT(self->set_hostname);
2431#endif
2432 return 0;
2433}
2434
2435static int
2436context_clear(PySSLContext *self)
2437{
2438#ifndef OPENSSL_NO_TLSEXT
2439 Py_CLEAR(self->set_hostname);
2440#endif
2441 return 0;
2442}
2443
Antoine Pitrou152efa22010-05-16 18:19:27 +00002444static void
2445context_dealloc(PySSLContext *self)
2446{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002447 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002448 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002449#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002450 PyMem_FREE(self->npn_protocols);
2451#endif
2452#ifdef HAVE_ALPN
2453 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002454#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002455 Py_TYPE(self)->tp_free(self);
2456}
2457
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002458/*[clinic input]
2459_ssl._SSLContext.set_ciphers
2460 cipherlist: str
2461 /
2462[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002463
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002464static PyObject *
2465_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2466/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2467{
2468 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002469 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002470 /* Clearing the error queue is necessary on some OpenSSL versions,
2471 otherwise the error will be reported again when another SSL call
2472 is done. */
2473 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002474 PyErr_SetString(PySSLErrorObject,
2475 "No cipher can be selected.");
2476 return NULL;
2477 }
2478 Py_RETURN_NONE;
2479}
2480
Benjamin Petersonc54de472015-01-28 12:06:39 -05002481#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002482static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002483do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2484 const unsigned char *server_protocols, unsigned int server_protocols_len,
2485 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002486{
Benjamin Peterson88615022015-01-23 17:30:26 -05002487 int ret;
2488 if (client_protocols == NULL) {
2489 client_protocols = (unsigned char *)"";
2490 client_protocols_len = 0;
2491 }
2492 if (server_protocols == NULL) {
2493 server_protocols = (unsigned char *)"";
2494 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002495 }
2496
Benjamin Peterson88615022015-01-23 17:30:26 -05002497 ret = SSL_select_next_proto(out, outlen,
2498 server_protocols, server_protocols_len,
2499 client_protocols, client_protocols_len);
2500 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2501 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002502
2503 return SSL_TLSEXT_ERR_OK;
2504}
2505
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002506/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2507static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002508_advertiseNPN_cb(SSL *s,
2509 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002510 void *args)
2511{
2512 PySSLContext *ssl_ctx = (PySSLContext *) args;
2513
2514 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002515 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002516 *len = 0;
2517 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002518 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002519 *len = ssl_ctx->npn_protocols_len;
2520 }
2521
2522 return SSL_TLSEXT_ERR_OK;
2523}
2524/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2525static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002526_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002527 unsigned char **out, unsigned char *outlen,
2528 const unsigned char *server, unsigned int server_len,
2529 void *args)
2530{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002531 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002532 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002533 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002534}
2535#endif
2536
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002537/*[clinic input]
2538_ssl._SSLContext._set_npn_protocols
2539 protos: Py_buffer
2540 /
2541[clinic start generated code]*/
2542
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002543static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002544_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2545 Py_buffer *protos)
2546/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002547{
2548#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002549 PyMem_Free(self->npn_protocols);
2550 self->npn_protocols = PyMem_Malloc(protos->len);
2551 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002552 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002553 memcpy(self->npn_protocols, protos->buf, protos->len);
2554 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002555
2556 /* set both server and client callbacks, because the context can
2557 * be used to create both types of sockets */
2558 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2559 _advertiseNPN_cb,
2560 self);
2561 SSL_CTX_set_next_proto_select_cb(self->ctx,
2562 _selectNPN_cb,
2563 self);
2564
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002565 Py_RETURN_NONE;
2566#else
2567 PyErr_SetString(PyExc_NotImplementedError,
2568 "The NPN extension requires OpenSSL 1.0.1 or later.");
2569 return NULL;
2570#endif
2571}
2572
Benjamin Petersoncca27322015-01-23 16:35:37 -05002573#ifdef HAVE_ALPN
2574static int
2575_selectALPN_cb(SSL *s,
2576 const unsigned char **out, unsigned char *outlen,
2577 const unsigned char *client_protocols, unsigned int client_protocols_len,
2578 void *args)
2579{
2580 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002581 return do_protocol_selection(1, (unsigned char **)out, outlen,
2582 ctx->alpn_protocols, ctx->alpn_protocols_len,
2583 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002584}
2585#endif
2586
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002587/*[clinic input]
2588_ssl._SSLContext._set_alpn_protocols
2589 protos: Py_buffer
2590 /
2591[clinic start generated code]*/
2592
Benjamin Petersoncca27322015-01-23 16:35:37 -05002593static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002594_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2595 Py_buffer *protos)
2596/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002597{
2598#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002599 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002600 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002601 if (!self->alpn_protocols)
2602 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002603 memcpy(self->alpn_protocols, protos->buf, protos->len);
2604 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002605
2606 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2607 return PyErr_NoMemory();
2608 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2609
Benjamin Petersoncca27322015-01-23 16:35:37 -05002610 Py_RETURN_NONE;
2611#else
2612 PyErr_SetString(PyExc_NotImplementedError,
2613 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2614 return NULL;
2615#endif
2616}
2617
Antoine Pitrou152efa22010-05-16 18:19:27 +00002618static PyObject *
2619get_verify_mode(PySSLContext *self, void *c)
2620{
2621 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2622 case SSL_VERIFY_NONE:
2623 return PyLong_FromLong(PY_SSL_CERT_NONE);
2624 case SSL_VERIFY_PEER:
2625 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2626 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2627 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2628 }
2629 PyErr_SetString(PySSLErrorObject,
2630 "invalid return value from SSL_CTX_get_verify_mode");
2631 return NULL;
2632}
2633
2634static int
2635set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2636{
2637 int n, mode;
2638 if (!PyArg_Parse(arg, "i", &n))
2639 return -1;
2640 if (n == PY_SSL_CERT_NONE)
2641 mode = SSL_VERIFY_NONE;
2642 else if (n == PY_SSL_CERT_OPTIONAL)
2643 mode = SSL_VERIFY_PEER;
2644 else if (n == PY_SSL_CERT_REQUIRED)
2645 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2646 else {
2647 PyErr_SetString(PyExc_ValueError,
2648 "invalid value for verify_mode");
2649 return -1;
2650 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002651 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2652 PyErr_SetString(PyExc_ValueError,
2653 "Cannot set verify_mode to CERT_NONE when "
2654 "check_hostname is enabled.");
2655 return -1;
2656 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002657 SSL_CTX_set_verify(self->ctx, mode, NULL);
2658 return 0;
2659}
2660
2661static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002662get_verify_flags(PySSLContext *self, void *c)
2663{
2664 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02002665 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01002666 unsigned long flags;
2667
2668 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02002669 param = X509_STORE_get0_param(store);
2670 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01002671 return PyLong_FromUnsignedLong(flags);
2672}
2673
2674static int
2675set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2676{
2677 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02002678 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01002679 unsigned long new_flags, flags, set, clear;
2680
2681 if (!PyArg_Parse(arg, "k", &new_flags))
2682 return -1;
2683 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02002684 param = X509_STORE_get0_param(store);
2685 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01002686 clear = flags & ~new_flags;
2687 set = ~flags & new_flags;
2688 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02002689 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01002690 _setSSLError(NULL, 0, __FILE__, __LINE__);
2691 return -1;
2692 }
2693 }
2694 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02002695 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01002696 _setSSLError(NULL, 0, __FILE__, __LINE__);
2697 return -1;
2698 }
2699 }
2700 return 0;
2701}
2702
2703static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002704get_options(PySSLContext *self, void *c)
2705{
2706 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2707}
2708
2709static int
2710set_options(PySSLContext *self, PyObject *arg, void *c)
2711{
2712 long new_opts, opts, set, clear;
2713 if (!PyArg_Parse(arg, "l", &new_opts))
2714 return -1;
2715 opts = SSL_CTX_get_options(self->ctx);
2716 clear = opts & ~new_opts;
2717 set = ~opts & new_opts;
2718 if (clear) {
2719#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2720 SSL_CTX_clear_options(self->ctx, clear);
2721#else
2722 PyErr_SetString(PyExc_ValueError,
2723 "can't clear options before OpenSSL 0.9.8m");
2724 return -1;
2725#endif
2726 }
2727 if (set)
2728 SSL_CTX_set_options(self->ctx, set);
2729 return 0;
2730}
2731
Christian Heimes1aa9a752013-12-02 02:41:19 +01002732static PyObject *
2733get_check_hostname(PySSLContext *self, void *c)
2734{
2735 return PyBool_FromLong(self->check_hostname);
2736}
2737
2738static int
2739set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2740{
2741 int check_hostname;
2742 if (!PyArg_Parse(arg, "p", &check_hostname))
2743 return -1;
2744 if (check_hostname &&
2745 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2746 PyErr_SetString(PyExc_ValueError,
2747 "check_hostname needs a SSL context with either "
2748 "CERT_OPTIONAL or CERT_REQUIRED");
2749 return -1;
2750 }
2751 self->check_hostname = check_hostname;
2752 return 0;
2753}
2754
2755
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002756typedef struct {
2757 PyThreadState *thread_state;
2758 PyObject *callable;
2759 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002760 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002761 int error;
2762} _PySSLPasswordInfo;
2763
2764static int
2765_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2766 const char *bad_type_error)
2767{
2768 /* Set the password and size fields of a _PySSLPasswordInfo struct
2769 from a unicode, bytes, or byte array object.
2770 The password field will be dynamically allocated and must be freed
2771 by the caller */
2772 PyObject *password_bytes = NULL;
2773 const char *data = NULL;
2774 Py_ssize_t size;
2775
2776 if (PyUnicode_Check(password)) {
2777 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2778 if (!password_bytes) {
2779 goto error;
2780 }
2781 data = PyBytes_AS_STRING(password_bytes);
2782 size = PyBytes_GET_SIZE(password_bytes);
2783 } else if (PyBytes_Check(password)) {
2784 data = PyBytes_AS_STRING(password);
2785 size = PyBytes_GET_SIZE(password);
2786 } else if (PyByteArray_Check(password)) {
2787 data = PyByteArray_AS_STRING(password);
2788 size = PyByteArray_GET_SIZE(password);
2789 } else {
2790 PyErr_SetString(PyExc_TypeError, bad_type_error);
2791 goto error;
2792 }
2793
Victor Stinner9ee02032013-06-23 15:08:23 +02002794 if (size > (Py_ssize_t)INT_MAX) {
2795 PyErr_Format(PyExc_ValueError,
2796 "password cannot be longer than %d bytes", INT_MAX);
2797 goto error;
2798 }
2799
Victor Stinner11ebff22013-07-07 17:07:52 +02002800 PyMem_Free(pw_info->password);
2801 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002802 if (!pw_info->password) {
2803 PyErr_SetString(PyExc_MemoryError,
2804 "unable to allocate password buffer");
2805 goto error;
2806 }
2807 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002808 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002809
2810 Py_XDECREF(password_bytes);
2811 return 1;
2812
2813error:
2814 Py_XDECREF(password_bytes);
2815 return 0;
2816}
2817
2818static int
2819_password_callback(char *buf, int size, int rwflag, void *userdata)
2820{
2821 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2822 PyObject *fn_ret = NULL;
2823
2824 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2825
2826 if (pw_info->callable) {
2827 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2828 if (!fn_ret) {
2829 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2830 core python API, so we could use it to add a frame here */
2831 goto error;
2832 }
2833
2834 if (!_pwinfo_set(pw_info, fn_ret,
2835 "password callback must return a string")) {
2836 goto error;
2837 }
2838 Py_CLEAR(fn_ret);
2839 }
2840
2841 if (pw_info->size > size) {
2842 PyErr_Format(PyExc_ValueError,
2843 "password cannot be longer than %d bytes", size);
2844 goto error;
2845 }
2846
2847 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2848 memcpy(buf, pw_info->password, pw_info->size);
2849 return pw_info->size;
2850
2851error:
2852 Py_XDECREF(fn_ret);
2853 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2854 pw_info->error = 1;
2855 return -1;
2856}
2857
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002858/*[clinic input]
2859_ssl._SSLContext.load_cert_chain
2860 certfile: object
2861 keyfile: object = NULL
2862 password: object = NULL
2863
2864[clinic start generated code]*/
2865
Antoine Pitroub5218772010-05-21 09:56:06 +00002866static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002867_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
2868 PyObject *keyfile, PyObject *password)
2869/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002870{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002871 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02002872 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
2873 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002874 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002875 int r;
2876
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002877 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002878 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002879 if (keyfile == Py_None)
2880 keyfile = NULL;
2881 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2882 PyErr_SetString(PyExc_TypeError,
2883 "certfile should be a valid filesystem path");
2884 return NULL;
2885 }
2886 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2887 PyErr_SetString(PyExc_TypeError,
2888 "keyfile should be a valid filesystem path");
2889 goto error;
2890 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002891 if (password && password != Py_None) {
2892 if (PyCallable_Check(password)) {
2893 pw_info.callable = password;
2894 } else if (!_pwinfo_set(&pw_info, password,
2895 "password should be a string or callable")) {
2896 goto error;
2897 }
2898 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2899 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2900 }
2901 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002902 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2903 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002904 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002905 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002906 if (pw_info.error) {
2907 ERR_clear_error();
2908 /* the password callback has already set the error information */
2909 }
2910 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002911 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002912 PyErr_SetFromErrno(PyExc_IOError);
2913 }
2914 else {
2915 _setSSLError(NULL, 0, __FILE__, __LINE__);
2916 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002917 goto error;
2918 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002919 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002920 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002921 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2922 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002923 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2924 Py_CLEAR(keyfile_bytes);
2925 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002926 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002927 if (pw_info.error) {
2928 ERR_clear_error();
2929 /* the password callback has already set the error information */
2930 }
2931 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002932 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002933 PyErr_SetFromErrno(PyExc_IOError);
2934 }
2935 else {
2936 _setSSLError(NULL, 0, __FILE__, __LINE__);
2937 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002938 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002939 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002940 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002941 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002942 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002943 if (r != 1) {
2944 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002945 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002946 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002947 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2948 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002949 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002950 Py_RETURN_NONE;
2951
2952error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002953 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2954 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002955 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002956 Py_XDECREF(keyfile_bytes);
2957 Py_XDECREF(certfile_bytes);
2958 return NULL;
2959}
2960
Christian Heimesefff7062013-11-21 03:35:02 +01002961/* internal helper function, returns -1 on error
2962 */
2963static int
2964_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2965 int filetype)
2966{
2967 BIO *biobuf = NULL;
2968 X509_STORE *store;
2969 int retval = 0, err, loaded = 0;
2970
2971 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2972
2973 if (len <= 0) {
2974 PyErr_SetString(PyExc_ValueError,
2975 "Empty certificate data");
2976 return -1;
2977 } else if (len > INT_MAX) {
2978 PyErr_SetString(PyExc_OverflowError,
2979 "Certificate data is too long.");
2980 return -1;
2981 }
2982
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002983 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002984 if (biobuf == NULL) {
2985 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2986 return -1;
2987 }
2988
2989 store = SSL_CTX_get_cert_store(self->ctx);
2990 assert(store != NULL);
2991
2992 while (1) {
2993 X509 *cert = NULL;
2994 int r;
2995
2996 if (filetype == SSL_FILETYPE_ASN1) {
2997 cert = d2i_X509_bio(biobuf, NULL);
2998 } else {
2999 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003000 SSL_CTX_get_default_passwd_cb(self->ctx),
3001 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3002 );
Christian Heimesefff7062013-11-21 03:35:02 +01003003 }
3004 if (cert == NULL) {
3005 break;
3006 }
3007 r = X509_STORE_add_cert(store, cert);
3008 X509_free(cert);
3009 if (!r) {
3010 err = ERR_peek_last_error();
3011 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3012 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3013 /* cert already in hash table, not an error */
3014 ERR_clear_error();
3015 } else {
3016 break;
3017 }
3018 }
3019 loaded++;
3020 }
3021
3022 err = ERR_peek_last_error();
3023 if ((filetype == SSL_FILETYPE_ASN1) &&
3024 (loaded > 0) &&
3025 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3026 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3027 /* EOF ASN1 file, not an error */
3028 ERR_clear_error();
3029 retval = 0;
3030 } else if ((filetype == SSL_FILETYPE_PEM) &&
3031 (loaded > 0) &&
3032 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3033 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3034 /* EOF PEM file, not an error */
3035 ERR_clear_error();
3036 retval = 0;
3037 } else {
3038 _setSSLError(NULL, 0, __FILE__, __LINE__);
3039 retval = -1;
3040 }
3041
3042 BIO_free(biobuf);
3043 return retval;
3044}
3045
3046
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003047/*[clinic input]
3048_ssl._SSLContext.load_verify_locations
3049 cafile: object = NULL
3050 capath: object = NULL
3051 cadata: object = NULL
3052
3053[clinic start generated code]*/
3054
Antoine Pitrou152efa22010-05-16 18:19:27 +00003055static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003056_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3057 PyObject *cafile,
3058 PyObject *capath,
3059 PyObject *cadata)
3060/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003061{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003062 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3063 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003064 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003065
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003066 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003067 if (cafile == Py_None)
3068 cafile = NULL;
3069 if (capath == Py_None)
3070 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003071 if (cadata == Py_None)
3072 cadata = NULL;
3073
3074 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003075 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003076 "cafile, capath and cadata cannot be all omitted");
3077 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003078 }
3079 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3080 PyErr_SetString(PyExc_TypeError,
3081 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003082 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003083 }
3084 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003085 PyErr_SetString(PyExc_TypeError,
3086 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003087 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003088 }
Christian Heimesefff7062013-11-21 03:35:02 +01003089
3090 /* validata cadata type and load cadata */
3091 if (cadata) {
3092 Py_buffer buf;
3093 PyObject *cadata_ascii = NULL;
3094
3095 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3096 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3097 PyBuffer_Release(&buf);
3098 PyErr_SetString(PyExc_TypeError,
3099 "cadata should be a contiguous buffer with "
3100 "a single dimension");
3101 goto error;
3102 }
3103 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3104 PyBuffer_Release(&buf);
3105 if (r == -1) {
3106 goto error;
3107 }
3108 } else {
3109 PyErr_Clear();
3110 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3111 if (cadata_ascii == NULL) {
3112 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003113 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003114 "bytes-like object");
3115 goto error;
3116 }
3117 r = _add_ca_certs(self,
3118 PyBytes_AS_STRING(cadata_ascii),
3119 PyBytes_GET_SIZE(cadata_ascii),
3120 SSL_FILETYPE_PEM);
3121 Py_DECREF(cadata_ascii);
3122 if (r == -1) {
3123 goto error;
3124 }
3125 }
3126 }
3127
3128 /* load cafile or capath */
3129 if (cafile || capath) {
3130 if (cafile)
3131 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3132 if (capath)
3133 capath_buf = PyBytes_AS_STRING(capath_bytes);
3134 PySSL_BEGIN_ALLOW_THREADS
3135 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3136 PySSL_END_ALLOW_THREADS
3137 if (r != 1) {
3138 ok = 0;
3139 if (errno != 0) {
3140 ERR_clear_error();
3141 PyErr_SetFromErrno(PyExc_IOError);
3142 }
3143 else {
3144 _setSSLError(NULL, 0, __FILE__, __LINE__);
3145 }
3146 goto error;
3147 }
3148 }
3149 goto end;
3150
3151 error:
3152 ok = 0;
3153 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003154 Py_XDECREF(cafile_bytes);
3155 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003156 if (ok) {
3157 Py_RETURN_NONE;
3158 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003159 return NULL;
3160 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003161}
3162
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003163/*[clinic input]
3164_ssl._SSLContext.load_dh_params
3165 path as filepath: object
3166 /
3167
3168[clinic start generated code]*/
3169
Antoine Pitrou152efa22010-05-16 18:19:27 +00003170static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003171_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3172/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003173{
3174 FILE *f;
3175 DH *dh;
3176
Victor Stinnerdaf45552013-08-28 00:53:59 +02003177 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003178 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003179 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003180
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003181 errno = 0;
3182 PySSL_BEGIN_ALLOW_THREADS
3183 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003184 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003185 PySSL_END_ALLOW_THREADS
3186 if (dh == NULL) {
3187 if (errno != 0) {
3188 ERR_clear_error();
3189 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3190 }
3191 else {
3192 _setSSLError(NULL, 0, __FILE__, __LINE__);
3193 }
3194 return NULL;
3195 }
3196 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3197 _setSSLError(NULL, 0, __FILE__, __LINE__);
3198 DH_free(dh);
3199 Py_RETURN_NONE;
3200}
3201
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003202/*[clinic input]
3203_ssl._SSLContext._wrap_socket
3204 sock: object(subclass_of="PySocketModule.Sock_Type")
3205 server_side: int
3206 server_hostname as hostname_obj: object = None
3207
3208[clinic start generated code]*/
3209
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003210static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003211_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3212 int server_side, PyObject *hostname_obj)
3213/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003214{
Antoine Pitroud5323212010-10-22 18:19:07 +00003215 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003216 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003217
Antoine Pitroud5323212010-10-22 18:19:07 +00003218 /* server_hostname is either None (or absent), or to be encoded
3219 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003220 if (hostname_obj != Py_None) {
3221 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003222 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003223 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003224
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003225 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3226 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003227 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003228 if (hostname != NULL)
3229 PyMem_Free(hostname);
3230 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003231}
3232
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003233/*[clinic input]
3234_ssl._SSLContext._wrap_bio
3235 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3236 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3237 server_side: int
3238 server_hostname as hostname_obj: object = None
3239
3240[clinic start generated code]*/
3241
Antoine Pitroub0182c82010-10-12 20:09:02 +00003242static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003243_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3244 PySSLMemoryBIO *outgoing, int server_side,
3245 PyObject *hostname_obj)
3246/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003247{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003248 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003249 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003250
3251 /* server_hostname is either None (or absent), or to be encoded
3252 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003253 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003254 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3255 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003256 }
3257
3258 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3259 incoming, outgoing);
3260
3261 PyMem_Free(hostname);
3262 return res;
3263}
3264
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003265/*[clinic input]
3266_ssl._SSLContext.session_stats
3267[clinic start generated code]*/
3268
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003269static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003270_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3271/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003272{
3273 int r;
3274 PyObject *value, *stats = PyDict_New();
3275 if (!stats)
3276 return NULL;
3277
3278#define ADD_STATS(SSL_NAME, KEY_NAME) \
3279 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3280 if (value == NULL) \
3281 goto error; \
3282 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3283 Py_DECREF(value); \
3284 if (r < 0) \
3285 goto error;
3286
3287 ADD_STATS(number, "number");
3288 ADD_STATS(connect, "connect");
3289 ADD_STATS(connect_good, "connect_good");
3290 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3291 ADD_STATS(accept, "accept");
3292 ADD_STATS(accept_good, "accept_good");
3293 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3294 ADD_STATS(accept, "accept");
3295 ADD_STATS(hits, "hits");
3296 ADD_STATS(misses, "misses");
3297 ADD_STATS(timeouts, "timeouts");
3298 ADD_STATS(cache_full, "cache_full");
3299
3300#undef ADD_STATS
3301
3302 return stats;
3303
3304error:
3305 Py_DECREF(stats);
3306 return NULL;
3307}
3308
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003309/*[clinic input]
3310_ssl._SSLContext.set_default_verify_paths
3311[clinic start generated code]*/
3312
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003313static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003314_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3315/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003316{
3317 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3318 _setSSLError(NULL, 0, __FILE__, __LINE__);
3319 return NULL;
3320 }
3321 Py_RETURN_NONE;
3322}
3323
Antoine Pitrou501da612011-12-21 09:27:41 +01003324#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003325/*[clinic input]
3326_ssl._SSLContext.set_ecdh_curve
3327 name: object
3328 /
3329
3330[clinic start generated code]*/
3331
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003332static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003333_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3334/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003335{
3336 PyObject *name_bytes;
3337 int nid;
3338 EC_KEY *key;
3339
3340 if (!PyUnicode_FSConverter(name, &name_bytes))
3341 return NULL;
3342 assert(PyBytes_Check(name_bytes));
3343 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3344 Py_DECREF(name_bytes);
3345 if (nid == 0) {
3346 PyErr_Format(PyExc_ValueError,
3347 "unknown elliptic curve name %R", name);
3348 return NULL;
3349 }
3350 key = EC_KEY_new_by_curve_name(nid);
3351 if (key == NULL) {
3352 _setSSLError(NULL, 0, __FILE__, __LINE__);
3353 return NULL;
3354 }
3355 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3356 EC_KEY_free(key);
3357 Py_RETURN_NONE;
3358}
Antoine Pitrou501da612011-12-21 09:27:41 +01003359#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003360
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003361#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003362static int
3363_servername_callback(SSL *s, int *al, void *args)
3364{
3365 int ret;
3366 PySSLContext *ssl_ctx = (PySSLContext *) args;
3367 PySSLSocket *ssl;
3368 PyObject *servername_o;
3369 PyObject *servername_idna;
3370 PyObject *result;
3371 /* The high-level ssl.SSLSocket object */
3372 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003373 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003374#ifdef WITH_THREAD
3375 PyGILState_STATE gstate = PyGILState_Ensure();
3376#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003377
3378 if (ssl_ctx->set_hostname == NULL) {
3379 /* remove race condition in this the call back while if removing the
3380 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003381#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003382 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003383#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003384 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003385 }
3386
3387 ssl = SSL_get_app_data(s);
3388 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003389
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003390 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003391 * SSL connection and that has a .context attribute that can be changed to
3392 * identify the requested hostname. Since the official API is the Python
3393 * level API we want to pass the callback a Python level object rather than
3394 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3395 * SSLObject) that will be passed. Otherwise if there's a socket then that
3396 * will be passed. If both do not exist only then the C-level object is
3397 * passed. */
3398 if (ssl->owner)
3399 ssl_socket = PyWeakref_GetObject(ssl->owner);
3400 else if (ssl->Socket)
3401 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3402 else
3403 ssl_socket = (PyObject *) ssl;
3404
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003405 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003406 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003407 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003408
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003409 if (servername == NULL) {
3410 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3411 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003412 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003413 else {
3414 servername_o = PyBytes_FromString(servername);
3415 if (servername_o == NULL) {
3416 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3417 goto error;
3418 }
3419 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3420 if (servername_idna == NULL) {
3421 PyErr_WriteUnraisable(servername_o);
3422 Py_DECREF(servername_o);
3423 goto error;
3424 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003425 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003426 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3427 servername_idna, ssl_ctx, NULL);
3428 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003429 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003430 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003431
3432 if (result == NULL) {
3433 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3434 *al = SSL_AD_HANDSHAKE_FAILURE;
3435 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3436 }
3437 else {
3438 if (result != Py_None) {
3439 *al = (int) PyLong_AsLong(result);
3440 if (PyErr_Occurred()) {
3441 PyErr_WriteUnraisable(result);
3442 *al = SSL_AD_INTERNAL_ERROR;
3443 }
3444 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3445 }
3446 else {
3447 ret = SSL_TLSEXT_ERR_OK;
3448 }
3449 Py_DECREF(result);
3450 }
3451
Stefan Krah20d60802013-01-17 17:07:17 +01003452#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003453 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003454#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003455 return ret;
3456
3457error:
3458 Py_DECREF(ssl_socket);
3459 *al = SSL_AD_INTERNAL_ERROR;
3460 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003461#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003462 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003463#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003464 return ret;
3465}
Antoine Pitroua5963382013-03-30 16:39:00 +01003466#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003467
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003468/*[clinic input]
3469_ssl._SSLContext.set_servername_callback
3470 method as cb: object
3471 /
3472
3473Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3474
3475If the argument is None then the callback is disabled. The method is called
3476with the SSLSocket, the server name as a string, and the SSLContext object.
3477See RFC 6066 for details of the SNI extension.
3478[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003479
3480static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003481_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3482/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003483{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003484#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003485 Py_CLEAR(self->set_hostname);
3486 if (cb == Py_None) {
3487 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3488 }
3489 else {
3490 if (!PyCallable_Check(cb)) {
3491 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3492 PyErr_SetString(PyExc_TypeError,
3493 "not a callable object");
3494 return NULL;
3495 }
3496 Py_INCREF(cb);
3497 self->set_hostname = cb;
3498 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3499 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3500 }
3501 Py_RETURN_NONE;
3502#else
3503 PyErr_SetString(PyExc_NotImplementedError,
3504 "The TLS extension servername callback, "
3505 "SSL_CTX_set_tlsext_servername_callback, "
3506 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003507 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003508#endif
3509}
3510
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003511/*[clinic input]
3512_ssl._SSLContext.cert_store_stats
3513
3514Returns quantities of loaded X.509 certificates.
3515
3516X.509 certificates with a CA extension and certificate revocation lists
3517inside the context's cert store.
3518
3519NOTE: Certificates in a capath directory aren't loaded unless they have
3520been used at least once.
3521[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003522
3523static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003524_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3525/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003526{
3527 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003528 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003529 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003530 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003531
3532 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003533 objs = X509_STORE_get0_objects(store);
3534 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3535 obj = sk_X509_OBJECT_value(objs, i);
3536 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003537 case X509_LU_X509:
3538 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003539 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003540 ca++;
3541 }
3542 break;
3543 case X509_LU_CRL:
3544 crl++;
3545 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003546 default:
3547 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3548 * As far as I can tell they are internal states and never
3549 * stored in a cert store */
3550 break;
3551 }
3552 }
3553 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3554 "x509_ca", ca);
3555}
3556
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003557/*[clinic input]
3558_ssl._SSLContext.get_ca_certs
3559 binary_form: bool = False
3560
3561Returns a list of dicts with information of loaded CA certs.
3562
3563If the optional argument is True, returns a DER-encoded copy of the CA
3564certificate.
3565
3566NOTE: Certificates in a capath directory aren't loaded unless they have
3567been used at least once.
3568[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003569
3570static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003571_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3572/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003573{
3574 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003575 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003576 PyObject *ci = NULL, *rlist = NULL;
3577 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003578
3579 if ((rlist = PyList_New(0)) == NULL) {
3580 return NULL;
3581 }
3582
3583 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003584 objs = X509_STORE_get0_objects(store);
3585 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003586 X509_OBJECT *obj;
3587 X509 *cert;
3588
Christian Heimes598894f2016-09-05 23:19:05 +02003589 obj = sk_X509_OBJECT_value(objs, i);
3590 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003591 /* not a x509 cert */
3592 continue;
3593 }
3594 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003595 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003596 if (!X509_check_ca(cert)) {
3597 continue;
3598 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003599 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003600 ci = _certificate_to_der(cert);
3601 } else {
3602 ci = _decode_certificate(cert);
3603 }
3604 if (ci == NULL) {
3605 goto error;
3606 }
3607 if (PyList_Append(rlist, ci) == -1) {
3608 goto error;
3609 }
3610 Py_CLEAR(ci);
3611 }
3612 return rlist;
3613
3614 error:
3615 Py_XDECREF(ci);
3616 Py_XDECREF(rlist);
3617 return NULL;
3618}
3619
3620
Antoine Pitrou152efa22010-05-16 18:19:27 +00003621static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003622 {"check_hostname", (getter) get_check_hostname,
3623 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003624 {"options", (getter) get_options,
3625 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003626 {"verify_flags", (getter) get_verify_flags,
3627 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003628 {"verify_mode", (getter) get_verify_mode,
3629 (setter) set_verify_mode, NULL},
3630 {NULL}, /* sentinel */
3631};
3632
3633static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003634 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
3635 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
3636 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
3637 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
3638 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
3639 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
3640 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
3641 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
3642 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
3643 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
3644 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
3645 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
3646 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
3647 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00003648 {NULL, NULL} /* sentinel */
3649};
3650
3651static PyTypeObject PySSLContext_Type = {
3652 PyVarObject_HEAD_INIT(NULL, 0)
3653 "_ssl._SSLContext", /*tp_name*/
3654 sizeof(PySSLContext), /*tp_basicsize*/
3655 0, /*tp_itemsize*/
3656 (destructor)context_dealloc, /*tp_dealloc*/
3657 0, /*tp_print*/
3658 0, /*tp_getattr*/
3659 0, /*tp_setattr*/
3660 0, /*tp_reserved*/
3661 0, /*tp_repr*/
3662 0, /*tp_as_number*/
3663 0, /*tp_as_sequence*/
3664 0, /*tp_as_mapping*/
3665 0, /*tp_hash*/
3666 0, /*tp_call*/
3667 0, /*tp_str*/
3668 0, /*tp_getattro*/
3669 0, /*tp_setattro*/
3670 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003671 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003672 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003673 (traverseproc) context_traverse, /*tp_traverse*/
3674 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003675 0, /*tp_richcompare*/
3676 0, /*tp_weaklistoffset*/
3677 0, /*tp_iter*/
3678 0, /*tp_iternext*/
3679 context_methods, /*tp_methods*/
3680 0, /*tp_members*/
3681 context_getsetlist, /*tp_getset*/
3682 0, /*tp_base*/
3683 0, /*tp_dict*/
3684 0, /*tp_descr_get*/
3685 0, /*tp_descr_set*/
3686 0, /*tp_dictoffset*/
3687 0, /*tp_init*/
3688 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003689 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003690};
3691
3692
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003693/*
3694 * MemoryBIO objects
3695 */
3696
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003697/*[clinic input]
3698@classmethod
3699_ssl.MemoryBIO.__new__
3700
3701[clinic start generated code]*/
3702
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003703static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003704_ssl_MemoryBIO_impl(PyTypeObject *type)
3705/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003706{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003707 BIO *bio;
3708 PySSLMemoryBIO *self;
3709
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003710 bio = BIO_new(BIO_s_mem());
3711 if (bio == NULL) {
3712 PyErr_SetString(PySSLErrorObject,
3713 "failed to allocate BIO");
3714 return NULL;
3715 }
3716 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3717 * just that no data is currently available. The SSL routines should retry
3718 * the read, which we can achieve by calling BIO_set_retry_read(). */
3719 BIO_set_retry_read(bio);
3720 BIO_set_mem_eof_return(bio, -1);
3721
3722 assert(type != NULL && type->tp_alloc != NULL);
3723 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3724 if (self == NULL) {
3725 BIO_free(bio);
3726 return NULL;
3727 }
3728 self->bio = bio;
3729 self->eof_written = 0;
3730
3731 return (PyObject *) self;
3732}
3733
3734static void
3735memory_bio_dealloc(PySSLMemoryBIO *self)
3736{
3737 BIO_free(self->bio);
3738 Py_TYPE(self)->tp_free(self);
3739}
3740
3741static PyObject *
3742memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3743{
3744 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3745}
3746
3747PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3748"The number of bytes pending in the memory BIO.");
3749
3750static PyObject *
3751memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3752{
3753 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3754 && self->eof_written);
3755}
3756
3757PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3758"Whether the memory BIO is at EOF.");
3759
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003760/*[clinic input]
3761_ssl.MemoryBIO.read
3762 size as len: int = -1
3763 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003764
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003765Read up to size bytes from the memory BIO.
3766
3767If size is not specified, read the entire buffer.
3768If the return value is an empty bytes instance, this means either
3769EOF or that no data is available. Use the "eof" property to
3770distinguish between the two.
3771[clinic start generated code]*/
3772
3773static PyObject *
3774_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
3775/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
3776{
3777 int avail, nbytes;
3778 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003779
3780 avail = BIO_ctrl_pending(self->bio);
3781 if ((len < 0) || (len > avail))
3782 len = avail;
3783
3784 result = PyBytes_FromStringAndSize(NULL, len);
3785 if ((result == NULL) || (len == 0))
3786 return result;
3787
3788 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3789 /* There should never be any short reads but check anyway. */
3790 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3791 Py_DECREF(result);
3792 return NULL;
3793 }
3794
3795 return result;
3796}
3797
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003798/*[clinic input]
3799_ssl.MemoryBIO.write
3800 b: Py_buffer
3801 /
3802
3803Writes the bytes b into the memory BIO.
3804
3805Returns the number of bytes written.
3806[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003807
3808static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003809_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
3810/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003811{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003812 int nbytes;
3813
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003814 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003815 PyErr_Format(PyExc_OverflowError,
3816 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003817 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003818 }
3819
3820 if (self->eof_written) {
3821 PyErr_SetString(PySSLErrorObject,
3822 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003823 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003824 }
3825
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003826 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003827 if (nbytes < 0) {
3828 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003829 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003830 }
3831
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003832 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003833}
3834
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003835/*[clinic input]
3836_ssl.MemoryBIO.write_eof
3837
3838Write an EOF marker to the memory BIO.
3839
3840When all data has been read, the "eof" property will be True.
3841[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003842
3843static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003844_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
3845/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003846{
3847 self->eof_written = 1;
3848 /* After an EOF is written, a zero return from read() should be a real EOF
3849 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3850 BIO_clear_retry_flags(self->bio);
3851 BIO_set_mem_eof_return(self->bio, 0);
3852
3853 Py_RETURN_NONE;
3854}
3855
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003856static PyGetSetDef memory_bio_getsetlist[] = {
3857 {"pending", (getter) memory_bio_get_pending, NULL,
3858 PySSL_memory_bio_pending_doc},
3859 {"eof", (getter) memory_bio_get_eof, NULL,
3860 PySSL_memory_bio_eof_doc},
3861 {NULL}, /* sentinel */
3862};
3863
3864static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003865 _SSL_MEMORYBIO_READ_METHODDEF
3866 _SSL_MEMORYBIO_WRITE_METHODDEF
3867 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003868 {NULL, NULL} /* sentinel */
3869};
3870
3871static PyTypeObject PySSLMemoryBIO_Type = {
3872 PyVarObject_HEAD_INIT(NULL, 0)
3873 "_ssl.MemoryBIO", /*tp_name*/
3874 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3875 0, /*tp_itemsize*/
3876 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3877 0, /*tp_print*/
3878 0, /*tp_getattr*/
3879 0, /*tp_setattr*/
3880 0, /*tp_reserved*/
3881 0, /*tp_repr*/
3882 0, /*tp_as_number*/
3883 0, /*tp_as_sequence*/
3884 0, /*tp_as_mapping*/
3885 0, /*tp_hash*/
3886 0, /*tp_call*/
3887 0, /*tp_str*/
3888 0, /*tp_getattro*/
3889 0, /*tp_setattro*/
3890 0, /*tp_as_buffer*/
3891 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3892 0, /*tp_doc*/
3893 0, /*tp_traverse*/
3894 0, /*tp_clear*/
3895 0, /*tp_richcompare*/
3896 0, /*tp_weaklistoffset*/
3897 0, /*tp_iter*/
3898 0, /*tp_iternext*/
3899 memory_bio_methods, /*tp_methods*/
3900 0, /*tp_members*/
3901 memory_bio_getsetlist, /*tp_getset*/
3902 0, /*tp_base*/
3903 0, /*tp_dict*/
3904 0, /*tp_descr_get*/
3905 0, /*tp_descr_set*/
3906 0, /*tp_dictoffset*/
3907 0, /*tp_init*/
3908 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003909 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003910};
3911
Antoine Pitrou152efa22010-05-16 18:19:27 +00003912
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003913/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003914/*[clinic input]
3915_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07003916 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003917 entropy: double
3918 /
3919
3920Mix string into the OpenSSL PRNG state.
3921
3922entropy (a float) is a lower bound on the entropy contained in
3923string. See RFC 1750.
3924[clinic start generated code]*/
3925
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003926static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003927_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
3928/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003929{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02003930 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003931 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003932
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003933 buf = (const char *)view->buf;
3934 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003935 do {
3936 written = Py_MIN(len, INT_MAX);
3937 RAND_add(buf, (int)written, entropy);
3938 buf += written;
3939 len -= written;
3940 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003941 Py_INCREF(Py_None);
3942 return Py_None;
3943}
3944
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003945static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003946PySSL_RAND(int len, int pseudo)
3947{
3948 int ok;
3949 PyObject *bytes;
3950 unsigned long err;
3951 const char *errstr;
3952 PyObject *v;
3953
Victor Stinner1e81a392013-12-19 16:47:04 +01003954 if (len < 0) {
3955 PyErr_SetString(PyExc_ValueError, "num must be positive");
3956 return NULL;
3957 }
3958
Victor Stinner99c8b162011-05-24 12:05:19 +02003959 bytes = PyBytes_FromStringAndSize(NULL, len);
3960 if (bytes == NULL)
3961 return NULL;
3962 if (pseudo) {
3963 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3964 if (ok == 0 || ok == 1)
3965 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3966 }
3967 else {
3968 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3969 if (ok == 1)
3970 return bytes;
3971 }
3972 Py_DECREF(bytes);
3973
3974 err = ERR_get_error();
3975 errstr = ERR_reason_error_string(err);
3976 v = Py_BuildValue("(ks)", err, errstr);
3977 if (v != NULL) {
3978 PyErr_SetObject(PySSLErrorObject, v);
3979 Py_DECREF(v);
3980 }
3981 return NULL;
3982}
3983
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003984/*[clinic input]
3985_ssl.RAND_bytes
3986 n: int
3987 /
3988
3989Generate n cryptographically strong pseudo-random bytes.
3990[clinic start generated code]*/
3991
Victor Stinner99c8b162011-05-24 12:05:19 +02003992static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003993_ssl_RAND_bytes_impl(PyObject *module, int n)
3994/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003995{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003996 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02003997}
3998
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003999/*[clinic input]
4000_ssl.RAND_pseudo_bytes
4001 n: int
4002 /
4003
4004Generate n pseudo-random bytes.
4005
4006Return a pair (bytes, is_cryptographic). is_cryptographic is True
4007if the bytes generated are cryptographically strong.
4008[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004009
4010static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004011_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4012/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004013{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004014 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004015}
4016
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004017/*[clinic input]
4018_ssl.RAND_status
4019
4020Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4021
4022It is necessary to seed the PRNG with RAND_add() on some platforms before
4023using the ssl() function.
4024[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004025
4026static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004027_ssl_RAND_status_impl(PyObject *module)
4028/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004029{
Christian Heimes217cfd12007-12-02 14:31:20 +00004030 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004031}
4032
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004033#ifndef OPENSSL_NO_EGD
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004034/*[clinic input]
4035_ssl.RAND_egd
4036 path: object(converter="PyUnicode_FSConverter")
4037 /
4038
4039Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4040
4041Returns number of bytes read. Raises SSLError if connection to EGD
4042fails or if it does not provide enough data to seed PRNG.
4043[clinic start generated code]*/
4044
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004045static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004046_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4047/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004048{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004049 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004050 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004051 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004052 PyErr_SetString(PySSLErrorObject,
4053 "EGD connection failed or EGD did not return "
4054 "enough data to seed the PRNG");
4055 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004056 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004057 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004058}
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004059#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004060
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004061
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004062
4063/*[clinic input]
4064_ssl.get_default_verify_paths
4065
4066Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4067
4068The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4069[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004070
4071static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004072_ssl_get_default_verify_paths_impl(PyObject *module)
4073/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004074{
4075 PyObject *ofile_env = NULL;
4076 PyObject *ofile = NULL;
4077 PyObject *odir_env = NULL;
4078 PyObject *odir = NULL;
4079
Benjamin Petersond113c962015-07-18 10:59:13 -07004080#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004081 const char *tmp = (info); \
4082 target = NULL; \
4083 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4084 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4085 target = PyBytes_FromString(tmp); } \
4086 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004087 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004088
Benjamin Petersond113c962015-07-18 10:59:13 -07004089 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4090 CONVERT(X509_get_default_cert_file(), ofile);
4091 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4092 CONVERT(X509_get_default_cert_dir(), odir);
4093#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004094
Christian Heimes200bb1b2013-06-14 15:14:29 +02004095 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004096
4097 error:
4098 Py_XDECREF(ofile_env);
4099 Py_XDECREF(ofile);
4100 Py_XDECREF(odir_env);
4101 Py_XDECREF(odir);
4102 return NULL;
4103}
4104
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004105static PyObject*
4106asn1obj2py(ASN1_OBJECT *obj)
4107{
4108 int nid;
4109 const char *ln, *sn;
4110 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004111 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004112
4113 nid = OBJ_obj2nid(obj);
4114 if (nid == NID_undef) {
4115 PyErr_Format(PyExc_ValueError, "Unknown object");
4116 return NULL;
4117 }
4118 sn = OBJ_nid2sn(nid);
4119 ln = OBJ_nid2ln(nid);
4120 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4121 if (buflen < 0) {
4122 _setSSLError(NULL, 0, __FILE__, __LINE__);
4123 return NULL;
4124 }
4125 if (buflen) {
4126 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4127 } else {
4128 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4129 }
4130}
4131
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004132/*[clinic input]
4133_ssl.txt2obj
4134 txt: str
4135 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004136
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004137Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4138
4139By default objects are looked up by OID. With name=True short and
4140long name are also matched.
4141[clinic start generated code]*/
4142
4143static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004144_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4145/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004146{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004147 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004148 ASN1_OBJECT *obj;
4149
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004150 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4151 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004152 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004153 return NULL;
4154 }
4155 result = asn1obj2py(obj);
4156 ASN1_OBJECT_free(obj);
4157 return result;
4158}
4159
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004160/*[clinic input]
4161_ssl.nid2obj
4162 nid: int
4163 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004164
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004165Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4166[clinic start generated code]*/
4167
4168static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004169_ssl_nid2obj_impl(PyObject *module, int nid)
4170/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004171{
4172 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004173 ASN1_OBJECT *obj;
4174
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004175 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004176 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004177 return NULL;
4178 }
4179 obj = OBJ_nid2obj(nid);
4180 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004181 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004182 return NULL;
4183 }
4184 result = asn1obj2py(obj);
4185 ASN1_OBJECT_free(obj);
4186 return result;
4187}
4188
Christian Heimes46bebee2013-06-09 19:03:31 +02004189#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004190
4191static PyObject*
4192certEncodingType(DWORD encodingType)
4193{
4194 static PyObject *x509_asn = NULL;
4195 static PyObject *pkcs_7_asn = NULL;
4196
4197 if (x509_asn == NULL) {
4198 x509_asn = PyUnicode_InternFromString("x509_asn");
4199 if (x509_asn == NULL)
4200 return NULL;
4201 }
4202 if (pkcs_7_asn == NULL) {
4203 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4204 if (pkcs_7_asn == NULL)
4205 return NULL;
4206 }
4207 switch(encodingType) {
4208 case X509_ASN_ENCODING:
4209 Py_INCREF(x509_asn);
4210 return x509_asn;
4211 case PKCS_7_ASN_ENCODING:
4212 Py_INCREF(pkcs_7_asn);
4213 return pkcs_7_asn;
4214 default:
4215 return PyLong_FromLong(encodingType);
4216 }
4217}
4218
4219static PyObject*
4220parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4221{
4222 CERT_ENHKEY_USAGE *usage;
4223 DWORD size, error, i;
4224 PyObject *retval;
4225
4226 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4227 error = GetLastError();
4228 if (error == CRYPT_E_NOT_FOUND) {
4229 Py_RETURN_TRUE;
4230 }
4231 return PyErr_SetFromWindowsErr(error);
4232 }
4233
4234 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4235 if (usage == NULL) {
4236 return PyErr_NoMemory();
4237 }
4238
4239 /* Now get the actual enhanced usage property */
4240 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4241 PyMem_Free(usage);
4242 error = GetLastError();
4243 if (error == CRYPT_E_NOT_FOUND) {
4244 Py_RETURN_TRUE;
4245 }
4246 return PyErr_SetFromWindowsErr(error);
4247 }
4248 retval = PySet_New(NULL);
4249 if (retval == NULL) {
4250 goto error;
4251 }
4252 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4253 if (usage->rgpszUsageIdentifier[i]) {
4254 PyObject *oid;
4255 int err;
4256 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4257 if (oid == NULL) {
4258 Py_CLEAR(retval);
4259 goto error;
4260 }
4261 err = PySet_Add(retval, oid);
4262 Py_DECREF(oid);
4263 if (err == -1) {
4264 Py_CLEAR(retval);
4265 goto error;
4266 }
4267 }
4268 }
4269 error:
4270 PyMem_Free(usage);
4271 return retval;
4272}
4273
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004274/*[clinic input]
4275_ssl.enum_certificates
4276 store_name: str
4277
4278Retrieve certificates from Windows' cert store.
4279
4280store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4281more cert storages, too. The function returns a list of (bytes,
4282encoding_type, trust) tuples. The encoding_type flag can be interpreted
4283with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4284a set of OIDs or the boolean True.
4285[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004286
Christian Heimes46bebee2013-06-09 19:03:31 +02004287static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004288_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4289/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004290{
Christian Heimes46bebee2013-06-09 19:03:31 +02004291 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004292 PCCERT_CONTEXT pCertCtx = NULL;
4293 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004294 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004295
Christian Heimes44109d72013-11-22 01:51:30 +01004296 result = PyList_New(0);
4297 if (result == NULL) {
4298 return NULL;
4299 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004300 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4301 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4302 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004303 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004304 Py_DECREF(result);
4305 return PyErr_SetFromWindowsErr(GetLastError());
4306 }
4307
Christian Heimes44109d72013-11-22 01:51:30 +01004308 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4309 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4310 pCertCtx->cbCertEncoded);
4311 if (!cert) {
4312 Py_CLEAR(result);
4313 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004314 }
Christian Heimes44109d72013-11-22 01:51:30 +01004315 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4316 Py_CLEAR(result);
4317 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004318 }
Christian Heimes44109d72013-11-22 01:51:30 +01004319 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4320 if (keyusage == Py_True) {
4321 Py_DECREF(keyusage);
4322 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004323 }
Christian Heimes44109d72013-11-22 01:51:30 +01004324 if (keyusage == NULL) {
4325 Py_CLEAR(result);
4326 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004327 }
Christian Heimes44109d72013-11-22 01:51:30 +01004328 if ((tup = PyTuple_New(3)) == NULL) {
4329 Py_CLEAR(result);
4330 break;
4331 }
4332 PyTuple_SET_ITEM(tup, 0, cert);
4333 cert = NULL;
4334 PyTuple_SET_ITEM(tup, 1, enc);
4335 enc = NULL;
4336 PyTuple_SET_ITEM(tup, 2, keyusage);
4337 keyusage = NULL;
4338 if (PyList_Append(result, tup) < 0) {
4339 Py_CLEAR(result);
4340 break;
4341 }
4342 Py_CLEAR(tup);
4343 }
4344 if (pCertCtx) {
4345 /* loop ended with an error, need to clean up context manually */
4346 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004347 }
4348
4349 /* In error cases cert, enc and tup may not be NULL */
4350 Py_XDECREF(cert);
4351 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004352 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004353 Py_XDECREF(tup);
4354
4355 if (!CertCloseStore(hStore, 0)) {
4356 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004357 Py_XDECREF(result);
4358 return PyErr_SetFromWindowsErr(GetLastError());
4359 }
4360 return result;
4361}
4362
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004363/*[clinic input]
4364_ssl.enum_crls
4365 store_name: str
4366
4367Retrieve CRLs from Windows' cert store.
4368
4369store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4370more cert storages, too. The function returns a list of (bytes,
4371encoding_type) tuples. The encoding_type flag can be interpreted with
4372X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4373[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004374
4375static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004376_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4377/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004378{
Christian Heimes44109d72013-11-22 01:51:30 +01004379 HCERTSTORE hStore = NULL;
4380 PCCRL_CONTEXT pCrlCtx = NULL;
4381 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4382 PyObject *result = NULL;
4383
Christian Heimes44109d72013-11-22 01:51:30 +01004384 result = PyList_New(0);
4385 if (result == NULL) {
4386 return NULL;
4387 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004388 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4389 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4390 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004391 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004392 Py_DECREF(result);
4393 return PyErr_SetFromWindowsErr(GetLastError());
4394 }
Christian Heimes44109d72013-11-22 01:51:30 +01004395
4396 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4397 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4398 pCrlCtx->cbCrlEncoded);
4399 if (!crl) {
4400 Py_CLEAR(result);
4401 break;
4402 }
4403 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4404 Py_CLEAR(result);
4405 break;
4406 }
4407 if ((tup = PyTuple_New(2)) == NULL) {
4408 Py_CLEAR(result);
4409 break;
4410 }
4411 PyTuple_SET_ITEM(tup, 0, crl);
4412 crl = NULL;
4413 PyTuple_SET_ITEM(tup, 1, enc);
4414 enc = NULL;
4415
4416 if (PyList_Append(result, tup) < 0) {
4417 Py_CLEAR(result);
4418 break;
4419 }
4420 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004421 }
Christian Heimes44109d72013-11-22 01:51:30 +01004422 if (pCrlCtx) {
4423 /* loop ended with an error, need to clean up context manually */
4424 CertFreeCRLContext(pCrlCtx);
4425 }
4426
4427 /* In error cases cert, enc and tup may not be NULL */
4428 Py_XDECREF(crl);
4429 Py_XDECREF(enc);
4430 Py_XDECREF(tup);
4431
4432 if (!CertCloseStore(hStore, 0)) {
4433 /* This error case might shadow another exception.*/
4434 Py_XDECREF(result);
4435 return PyErr_SetFromWindowsErr(GetLastError());
4436 }
4437 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004438}
Christian Heimes44109d72013-11-22 01:51:30 +01004439
4440#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004441
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004442/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004443static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004444 _SSL__TEST_DECODE_CERT_METHODDEF
4445 _SSL_RAND_ADD_METHODDEF
4446 _SSL_RAND_BYTES_METHODDEF
4447 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4448 _SSL_RAND_EGD_METHODDEF
4449 _SSL_RAND_STATUS_METHODDEF
4450 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
4451 _SSL_ENUM_CERTIFICATES_METHODDEF
4452 _SSL_ENUM_CRLS_METHODDEF
4453 _SSL_TXT2OBJ_METHODDEF
4454 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004455 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004456};
4457
4458
Christian Heimes598894f2016-09-05 23:19:05 +02004459#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004460
4461/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02004462 * of the Python C thread library
4463 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
4464 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004465
4466static PyThread_type_lock *_ssl_locks = NULL;
4467
Christian Heimes4d98ca92013-08-19 17:36:29 +02004468#if OPENSSL_VERSION_NUMBER >= 0x10000000
4469/* use new CRYPTO_THREADID API. */
4470static void
4471_ssl_threadid_callback(CRYPTO_THREADID *id)
4472{
4473 CRYPTO_THREADID_set_numeric(id,
4474 (unsigned long)PyThread_get_thread_ident());
4475}
4476#else
4477/* deprecated CRYPTO_set_id_callback() API. */
4478static unsigned long
4479_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004480 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004481}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004482#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004483
Bill Janssen6e027db2007-11-15 22:23:56 +00004484static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004485 (int mode, int n, const char *file, int line) {
4486 /* this function is needed to perform locking on shared data
4487 structures. (Note that OpenSSL uses a number of global data
4488 structures that will be implicitly shared whenever multiple
4489 threads use OpenSSL.) Multi-threaded applications will
4490 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004491
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004492 locking_function() must be able to handle up to
4493 CRYPTO_num_locks() different mutex locks. It sets the n-th
4494 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004495
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004496 file and line are the file number of the function setting the
4497 lock. They can be useful for debugging.
4498 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004499
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004500 if ((_ssl_locks == NULL) ||
4501 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4502 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004503
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004504 if (mode & CRYPTO_LOCK) {
4505 PyThread_acquire_lock(_ssl_locks[n], 1);
4506 } else {
4507 PyThread_release_lock(_ssl_locks[n]);
4508 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004509}
4510
4511static int _setup_ssl_threads(void) {
4512
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004513 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004514
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004515 if (_ssl_locks == NULL) {
4516 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004517 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4518 if (_ssl_locks == NULL) {
4519 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004520 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004521 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004522 memset(_ssl_locks, 0,
4523 sizeof(PyThread_type_lock) * _ssl_locks_count);
4524 for (i = 0; i < _ssl_locks_count; i++) {
4525 _ssl_locks[i] = PyThread_allocate_lock();
4526 if (_ssl_locks[i] == NULL) {
4527 unsigned int j;
4528 for (j = 0; j < i; j++) {
4529 PyThread_free_lock(_ssl_locks[j]);
4530 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004531 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004532 return 0;
4533 }
4534 }
4535 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004536#if OPENSSL_VERSION_NUMBER >= 0x10000000
4537 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4538#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004539 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004540#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004541 }
4542 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004543}
4544
Christian Heimes598894f2016-09-05 23:19:05 +02004545#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004546
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004547PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004548"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004549for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004550
Martin v. Löwis1a214512008-06-11 05:26:20 +00004551
4552static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004553 PyModuleDef_HEAD_INIT,
4554 "_ssl",
4555 module_doc,
4556 -1,
4557 PySSL_methods,
4558 NULL,
4559 NULL,
4560 NULL,
4561 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004562};
4563
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004564
4565static void
4566parse_openssl_version(unsigned long libver,
4567 unsigned int *major, unsigned int *minor,
4568 unsigned int *fix, unsigned int *patch,
4569 unsigned int *status)
4570{
4571 *status = libver & 0xF;
4572 libver >>= 4;
4573 *patch = libver & 0xFF;
4574 libver >>= 8;
4575 *fix = libver & 0xFF;
4576 libver >>= 8;
4577 *minor = libver & 0xFF;
4578 libver >>= 8;
4579 *major = libver & 0xFF;
4580}
4581
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004582PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004583PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004584{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004585 PyObject *m, *d, *r;
4586 unsigned long libver;
4587 unsigned int major, minor, fix, patch, status;
4588 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004589 struct py_ssl_error_code *errcode;
4590 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004591
Antoine Pitrou152efa22010-05-16 18:19:27 +00004592 if (PyType_Ready(&PySSLContext_Type) < 0)
4593 return NULL;
4594 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004595 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004596 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4597 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004598
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004599 m = PyModule_Create(&_sslmodule);
4600 if (m == NULL)
4601 return NULL;
4602 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004603
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004604 /* Load _socket module and its C API */
4605 socket_api = PySocketModule_ImportModuleAndAPI();
4606 if (!socket_api)
4607 return NULL;
4608 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004609
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004610 /* Init OpenSSL */
4611 SSL_load_error_strings();
4612 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004613#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02004614#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004615 /* note that this will start threading if not already started */
4616 if (!_setup_ssl_threads()) {
4617 return NULL;
4618 }
Christian Heimes598894f2016-09-05 23:19:05 +02004619#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
4620 /* OpenSSL 1.1.0 builtin thread support is enabled */
4621 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004622#endif
Christian Heimes598894f2016-09-05 23:19:05 +02004623#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004624 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004625
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004626 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004627 sslerror_type_slots[0].pfunc = PyExc_OSError;
4628 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004629 if (PySSLErrorObject == NULL)
4630 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004631
Antoine Pitrou41032a62011-10-27 23:56:55 +02004632 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4633 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4634 PySSLErrorObject, NULL);
4635 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4636 "ssl.SSLWantReadError", SSLWantReadError_doc,
4637 PySSLErrorObject, NULL);
4638 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4639 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4640 PySSLErrorObject, NULL);
4641 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4642 "ssl.SSLSyscallError", SSLSyscallError_doc,
4643 PySSLErrorObject, NULL);
4644 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4645 "ssl.SSLEOFError", SSLEOFError_doc,
4646 PySSLErrorObject, NULL);
4647 if (PySSLZeroReturnErrorObject == NULL
4648 || PySSLWantReadErrorObject == NULL
4649 || PySSLWantWriteErrorObject == NULL
4650 || PySSLSyscallErrorObject == NULL
4651 || PySSLEOFErrorObject == NULL)
4652 return NULL;
4653 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4654 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4655 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4656 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4657 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4658 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004659 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004660 if (PyDict_SetItemString(d, "_SSLContext",
4661 (PyObject *)&PySSLContext_Type) != 0)
4662 return NULL;
4663 if (PyDict_SetItemString(d, "_SSLSocket",
4664 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004665 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004666 if (PyDict_SetItemString(d, "MemoryBIO",
4667 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4668 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004669 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4670 PY_SSL_ERROR_ZERO_RETURN);
4671 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4672 PY_SSL_ERROR_WANT_READ);
4673 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4674 PY_SSL_ERROR_WANT_WRITE);
4675 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4676 PY_SSL_ERROR_WANT_X509_LOOKUP);
4677 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4678 PY_SSL_ERROR_SYSCALL);
4679 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4680 PY_SSL_ERROR_SSL);
4681 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4682 PY_SSL_ERROR_WANT_CONNECT);
4683 /* non ssl.h errorcodes */
4684 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4685 PY_SSL_ERROR_EOF);
4686 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4687 PY_SSL_ERROR_INVALID_ERROR_CODE);
4688 /* cert requirements */
4689 PyModule_AddIntConstant(m, "CERT_NONE",
4690 PY_SSL_CERT_NONE);
4691 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4692 PY_SSL_CERT_OPTIONAL);
4693 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4694 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004695 /* CRL verification for verification_flags */
4696 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4697 0);
4698 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4699 X509_V_FLAG_CRL_CHECK);
4700 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4701 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4702 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4703 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05004704#ifdef X509_V_FLAG_TRUSTED_FIRST
4705 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4706 X509_V_FLAG_TRUSTED_FIRST);
4707#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004708
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004709 /* Alert Descriptions from ssl.h */
4710 /* note RESERVED constants no longer intended for use have been removed */
4711 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4712
4713#define ADD_AD_CONSTANT(s) \
4714 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4715 SSL_AD_##s)
4716
4717 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4718 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4719 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4720 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4721 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4722 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4723 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4724 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4725 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4726 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4727 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4728 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4729 ADD_AD_CONSTANT(UNKNOWN_CA);
4730 ADD_AD_CONSTANT(ACCESS_DENIED);
4731 ADD_AD_CONSTANT(DECODE_ERROR);
4732 ADD_AD_CONSTANT(DECRYPT_ERROR);
4733 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4734 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4735 ADD_AD_CONSTANT(INTERNAL_ERROR);
4736 ADD_AD_CONSTANT(USER_CANCELLED);
4737 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004738 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004739#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4740 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4741#endif
4742#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4743 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4744#endif
4745#ifdef SSL_AD_UNRECOGNIZED_NAME
4746 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4747#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004748#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4749 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4750#endif
4751#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4752 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4753#endif
4754#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4755 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4756#endif
4757
4758#undef ADD_AD_CONSTANT
4759
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004760 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004761#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004762 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4763 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004764#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004765#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004766 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4767 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004768#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004769 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02004770 PY_SSL_VERSION_TLS);
4771 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
4772 PY_SSL_VERSION_TLS);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004773 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4774 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004775#if HAVE_TLSv1_2
4776 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4777 PY_SSL_VERSION_TLS1_1);
4778 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4779 PY_SSL_VERSION_TLS1_2);
4780#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004781
Antoine Pitroub5218772010-05-21 09:56:06 +00004782 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004783 PyModule_AddIntConstant(m, "OP_ALL",
4784 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004785 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4786 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4787 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004788#if HAVE_TLSv1_2
4789 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4790 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4791#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004792 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4793 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004794 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004795#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004796 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004797#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004798#ifdef SSL_OP_NO_COMPRESSION
4799 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4800 SSL_OP_NO_COMPRESSION);
4801#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004802
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004803#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004804 r = Py_True;
4805#else
4806 r = Py_False;
4807#endif
4808 Py_INCREF(r);
4809 PyModule_AddObject(m, "HAS_SNI", r);
4810
Antoine Pitroud6494802011-07-21 01:11:30 +02004811 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004812 Py_INCREF(r);
4813 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4814
Antoine Pitrou501da612011-12-21 09:27:41 +01004815#ifdef OPENSSL_NO_ECDH
4816 r = Py_False;
4817#else
4818 r = Py_True;
4819#endif
4820 Py_INCREF(r);
4821 PyModule_AddObject(m, "HAS_ECDH", r);
4822
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004823#ifdef OPENSSL_NPN_NEGOTIATED
4824 r = Py_True;
4825#else
4826 r = Py_False;
4827#endif
4828 Py_INCREF(r);
4829 PyModule_AddObject(m, "HAS_NPN", r);
4830
Benjamin Petersoncca27322015-01-23 16:35:37 -05004831#ifdef HAVE_ALPN
4832 r = Py_True;
4833#else
4834 r = Py_False;
4835#endif
4836 Py_INCREF(r);
4837 PyModule_AddObject(m, "HAS_ALPN", r);
4838
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004839 /* Mappings for error codes */
4840 err_codes_to_names = PyDict_New();
4841 err_names_to_codes = PyDict_New();
4842 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4843 return NULL;
4844 errcode = error_codes;
4845 while (errcode->mnemonic != NULL) {
4846 PyObject *mnemo, *key;
4847 mnemo = PyUnicode_FromString(errcode->mnemonic);
4848 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4849 if (mnemo == NULL || key == NULL)
4850 return NULL;
4851 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4852 return NULL;
4853 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4854 return NULL;
4855 Py_DECREF(key);
4856 Py_DECREF(mnemo);
4857 errcode++;
4858 }
4859 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4860 return NULL;
4861 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4862 return NULL;
4863
4864 lib_codes_to_names = PyDict_New();
4865 if (lib_codes_to_names == NULL)
4866 return NULL;
4867 libcode = library_codes;
4868 while (libcode->library != NULL) {
4869 PyObject *mnemo, *key;
4870 key = PyLong_FromLong(libcode->code);
4871 mnemo = PyUnicode_FromString(libcode->library);
4872 if (key == NULL || mnemo == NULL)
4873 return NULL;
4874 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4875 return NULL;
4876 Py_DECREF(key);
4877 Py_DECREF(mnemo);
4878 libcode++;
4879 }
4880 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4881 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004882
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004883 /* OpenSSL version */
4884 /* SSLeay() gives us the version of the library linked against,
4885 which could be different from the headers version.
4886 */
4887 libver = SSLeay();
4888 r = PyLong_FromUnsignedLong(libver);
4889 if (r == NULL)
4890 return NULL;
4891 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4892 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004893 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004894 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4895 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4896 return NULL;
4897 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4898 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4899 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004900
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004901 libver = OPENSSL_VERSION_NUMBER;
4902 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4903 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4904 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4905 return NULL;
4906
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004907 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004908}