blob: e43c5026b77cbde84205973ab1332a14481e1c88 [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
58/* Include OpenSSL header files */
59#include "openssl/rsa.h"
60#include "openssl/crypto.h"
61#include "openssl/x509.h"
62#include "openssl/x509v3.h"
63#include "openssl/pem.h"
64#include "openssl/ssl.h"
65#include "openssl/err.h"
66#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020067#include "openssl/bio.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010068
69/* SSL error object */
70static PyObject *PySSLErrorObject;
71static PyObject *PySSLZeroReturnErrorObject;
72static PyObject *PySSLWantReadErrorObject;
73static PyObject *PySSLWantWriteErrorObject;
74static PyObject *PySSLSyscallErrorObject;
75static PyObject *PySSLEOFErrorObject;
76
77/* Error mappings */
78static PyObject *err_codes_to_names;
79static PyObject *err_names_to_codes;
80static PyObject *lib_codes_to_names;
81
82struct py_ssl_error_code {
83 const char *mnemonic;
84 int library, reason;
85};
86struct py_ssl_library_code {
87 const char *library;
88 int code;
89};
90
91/* Include generated data (error codes) */
92#include "_ssl_data.h"
93
94/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
95 http://www.openssl.org/news/changelog.html
96 */
97#if OPENSSL_VERSION_NUMBER >= 0x10001000L
98# define HAVE_TLSv1_2 1
99#else
100# define HAVE_TLSv1_2 0
101#endif
102
Christian Heimes470fba12013-11-28 15:12:15 +0100103/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100104 * This includes the SSL_set_SSL_CTX() function.
105 */
106#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
107# define HAVE_SNI 1
108#else
109# define HAVE_SNI 0
110#endif
111
Benjamin Petersond3308222015-09-27 00:09:02 -0700112#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Benjamin Petersoncca27322015-01-23 16:35:37 -0500113# define HAVE_ALPN
114#endif
115
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000116enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000117 /* these mirror ssl.h */
118 PY_SSL_ERROR_NONE,
119 PY_SSL_ERROR_SSL,
120 PY_SSL_ERROR_WANT_READ,
121 PY_SSL_ERROR_WANT_WRITE,
122 PY_SSL_ERROR_WANT_X509_LOOKUP,
123 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
124 PY_SSL_ERROR_ZERO_RETURN,
125 PY_SSL_ERROR_WANT_CONNECT,
126 /* start of non ssl.h errorcodes */
127 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
128 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
129 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000130};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000131
Thomas Woutersed03b412007-08-28 21:37:11 +0000132enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000133 PY_SSL_CLIENT,
134 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000135};
136
137enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000138 PY_SSL_CERT_NONE,
139 PY_SSL_CERT_OPTIONAL,
140 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000141};
142
143enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000144 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200145 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000146 PY_SSL_VERSION_SSL23,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100147#if HAVE_TLSv1_2
148 PY_SSL_VERSION_TLS1,
149 PY_SSL_VERSION_TLS1_1,
150 PY_SSL_VERSION_TLS1_2
151#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000152 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000153#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100154};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200155
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000156#ifdef WITH_THREAD
157
158/* serves as a flag to see whether we've initialized the SSL thread support. */
159/* 0 means no, greater than 0 means yes */
160
161static unsigned int _ssl_locks_count = 0;
162
163#endif /* def WITH_THREAD */
164
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000165/* SSL socket object */
166
167#define X509_NAME_MAXLEN 256
168
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000169/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
170 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
171 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
172#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000173# define HAVE_SSL_CTX_CLEAR_OPTIONS
174#else
175# undef HAVE_SSL_CTX_CLEAR_OPTIONS
176#endif
177
Antoine Pitroud6494802011-07-21 01:11:30 +0200178/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
179 * older SSL, but let's be safe */
180#define PySSL_CB_MAXLEN 128
181
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100182
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000183typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000184 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000185 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100186#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -0500187 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100188 int npn_protocols_len;
189#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500190#ifdef HAVE_ALPN
191 unsigned char *alpn_protocols;
192 int alpn_protocols_len;
193#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100194#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200195 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100196#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100197 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000198} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000199
Antoine Pitrou152efa22010-05-16 18:19:27 +0000200typedef struct {
201 PyObject_HEAD
202 PyObject *Socket; /* weakref to socket on which we're layered */
203 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100204 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000205 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200206 char shutdown_seen_zero;
207 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200208 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200209 PyObject *owner; /* Python level "owner" passed to servername callback */
210 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000211} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000212
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200213typedef struct {
214 PyObject_HEAD
215 BIO *bio;
216 int eof_written;
217} PySSLMemoryBIO;
218
Antoine Pitrou152efa22010-05-16 18:19:27 +0000219static PyTypeObject PySSLContext_Type;
220static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200221static PyTypeObject PySSLMemoryBIO_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000222
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300223/*[clinic input]
224module _ssl
225class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
226class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
227class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
228[clinic start generated code]*/
229/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7bf7cb832638e2e1]*/
230
231#include "clinic/_ssl.c.h"
232
Victor Stinner14690702015-04-06 22:46:13 +0200233static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000234
Antoine Pitrou152efa22010-05-16 18:19:27 +0000235#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
236#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200237#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000238
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000239typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000240 SOCKET_IS_NONBLOCKING,
241 SOCKET_IS_BLOCKING,
242 SOCKET_HAS_TIMED_OUT,
243 SOCKET_HAS_BEEN_CLOSED,
244 SOCKET_TOO_LARGE_FOR_SELECT,
245 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000246} timeout_state;
247
Thomas Woutersed03b412007-08-28 21:37:11 +0000248/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000249#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200250#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000251
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200252/* Get the socket from a PySSLSocket, if it has one */
253#define GET_SOCKET(obj) ((obj)->Socket ? \
254 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200255
Victor Stinner14690702015-04-06 22:46:13 +0200256/* If sock is NULL, use a timeout of 0 second */
257#define GET_SOCKET_TIMEOUT(sock) \
258 ((sock != NULL) ? (sock)->sock_timeout : 0)
259
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200260/*
261 * SSL errors.
262 */
263
264PyDoc_STRVAR(SSLError_doc,
265"An error occurred in the SSL implementation.");
266
267PyDoc_STRVAR(SSLZeroReturnError_doc,
268"SSL/TLS session closed cleanly.");
269
270PyDoc_STRVAR(SSLWantReadError_doc,
271"Non-blocking SSL socket needs to read more data\n"
272"before the requested operation can be completed.");
273
274PyDoc_STRVAR(SSLWantWriteError_doc,
275"Non-blocking SSL socket needs to write more data\n"
276"before the requested operation can be completed.");
277
278PyDoc_STRVAR(SSLSyscallError_doc,
279"System error when attempting SSL operation.");
280
281PyDoc_STRVAR(SSLEOFError_doc,
282"SSL/TLS connection terminated abruptly.");
283
284static PyObject *
285SSLError_str(PyOSErrorObject *self)
286{
287 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
288 Py_INCREF(self->strerror);
289 return self->strerror;
290 }
291 else
292 return PyObject_Str(self->args);
293}
294
295static PyType_Slot sslerror_type_slots[] = {
296 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
297 {Py_tp_doc, SSLError_doc},
298 {Py_tp_str, SSLError_str},
299 {0, 0},
300};
301
302static PyType_Spec sslerror_type_spec = {
303 "ssl.SSLError",
304 sizeof(PyOSErrorObject),
305 0,
306 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
307 sslerror_type_slots
308};
309
310static void
311fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
312 int lineno, unsigned long errcode)
313{
314 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
315 PyObject *init_value, *msg, *key;
316 _Py_IDENTIFIER(reason);
317 _Py_IDENTIFIER(library);
318
319 if (errcode != 0) {
320 int lib, reason;
321
322 lib = ERR_GET_LIB(errcode);
323 reason = ERR_GET_REASON(errcode);
324 key = Py_BuildValue("ii", lib, reason);
325 if (key == NULL)
326 goto fail;
327 reason_obj = PyDict_GetItem(err_codes_to_names, key);
328 Py_DECREF(key);
329 if (reason_obj == NULL) {
330 /* XXX if reason < 100, it might reflect a library number (!!) */
331 PyErr_Clear();
332 }
333 key = PyLong_FromLong(lib);
334 if (key == NULL)
335 goto fail;
336 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
337 Py_DECREF(key);
338 if (lib_obj == NULL) {
339 PyErr_Clear();
340 }
341 if (errstr == NULL)
342 errstr = ERR_reason_error_string(errcode);
343 }
344 if (errstr == NULL)
345 errstr = "unknown error";
346
347 if (reason_obj && lib_obj)
348 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
349 lib_obj, reason_obj, errstr, lineno);
350 else if (lib_obj)
351 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
352 lib_obj, errstr, lineno);
353 else
354 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200355 if (msg == NULL)
356 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100357
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200358 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100359 if (init_value == NULL)
360 goto fail;
361
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200362 err_value = PyObject_CallObject(type, init_value);
363 Py_DECREF(init_value);
364 if (err_value == NULL)
365 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100366
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200367 if (reason_obj == NULL)
368 reason_obj = Py_None;
369 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
370 goto fail;
371 if (lib_obj == NULL)
372 lib_obj = Py_None;
373 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
374 goto fail;
375 PyErr_SetObject(type, err_value);
376fail:
377 Py_XDECREF(err_value);
378}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000379
380static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000381PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000382{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200383 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200384 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000385 int err;
386 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200387 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000388
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000389 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200390 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000391
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000392 if (obj->ssl != NULL) {
393 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000394
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000395 switch (err) {
396 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200397 errstr = "TLS/SSL connection has been closed (EOF)";
398 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000399 p = PY_SSL_ERROR_ZERO_RETURN;
400 break;
401 case SSL_ERROR_WANT_READ:
402 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200403 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000404 p = PY_SSL_ERROR_WANT_READ;
405 break;
406 case SSL_ERROR_WANT_WRITE:
407 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200408 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000409 errstr = "The operation did not complete (write)";
410 break;
411 case SSL_ERROR_WANT_X509_LOOKUP:
412 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000413 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000414 break;
415 case SSL_ERROR_WANT_CONNECT:
416 p = PY_SSL_ERROR_WANT_CONNECT;
417 errstr = "The operation did not complete (connect)";
418 break;
419 case SSL_ERROR_SYSCALL:
420 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000421 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200422 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000423 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000424 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200425 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000426 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200427 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000428 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000429 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000430 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200431 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000432 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200433 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000434 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000435 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200436 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000437 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000438 }
439 } else {
440 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000441 }
442 break;
443 }
444 case SSL_ERROR_SSL:
445 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000446 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200447 if (e == 0)
448 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000449 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000450 break;
451 }
452 default:
453 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
454 errstr = "Invalid error code";
455 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000456 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200457 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000458 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000459 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000460}
461
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000462static PyObject *
463_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
464
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200465 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000466 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200467 else
468 errcode = 0;
469 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000470 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000471 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000472}
473
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200474/*
475 * SSL objects
476 */
477
Antoine Pitrou152efa22010-05-16 18:19:27 +0000478static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100479newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000480 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200481 char *server_hostname,
482 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000483{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000484 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100485 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200486 PyObject *hostname;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200487 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000488
Antoine Pitrou152efa22010-05-16 18:19:27 +0000489 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000490 if (self == NULL)
491 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000492
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000493 self->peer_cert = NULL;
494 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000495 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100496 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200497 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200498 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200499 self->owner = NULL;
500 if (server_hostname != NULL) {
501 hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
502 "idna", "strict");
503 if (hostname == NULL) {
504 Py_DECREF(self);
505 return NULL;
506 }
507 self->server_hostname = hostname;
508 } else
509 self->server_hostname = NULL;
510
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100511 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000512
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000513 /* Make sure the SSL error state is initialized */
514 (void) ERR_get_state();
515 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000516
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000517 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000518 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000519 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200520 SSL_set_app_data(self->ssl, self);
521 if (sock) {
522 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
523 } else {
524 /* BIOs are reference counted and SSL_set_bio borrows our reference.
525 * To prevent a double free in memory_bio_dealloc() we need to take an
526 * extra reference here. */
527 CRYPTO_add(&inbio->bio->references, 1, CRYPTO_LOCK_BIO);
528 CRYPTO_add(&outbio->bio->references, 1, CRYPTO_LOCK_BIO);
529 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
530 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200531 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000532#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200533 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000534#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200535 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000536
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100537#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000538 if (server_hostname != NULL)
539 SSL_set_tlsext_host_name(self->ssl, server_hostname);
540#endif
541
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000542 /* If the socket is in non-blocking mode or timeout mode, set the BIO
543 * to non-blocking mode (blocking is the default)
544 */
Victor Stinnere2452312015-03-28 03:00:46 +0100545 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000546 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
547 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
548 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000549
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000550 PySSL_BEGIN_ALLOW_THREADS
551 if (socket_type == PY_SSL_CLIENT)
552 SSL_set_connect_state(self->ssl);
553 else
554 SSL_set_accept_state(self->ssl);
555 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000556
Antoine Pitroud6494802011-07-21 01:11:30 +0200557 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200558 if (sock != NULL) {
559 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
560 if (self->Socket == NULL) {
561 Py_DECREF(self);
562 Py_XDECREF(self->server_hostname);
563 return NULL;
564 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100565 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000566 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000567}
568
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000569/* SSL object methods */
570
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300571/*[clinic input]
572_ssl._SSLSocket.do_handshake
573[clinic start generated code]*/
574
575static PyObject *
576_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
577/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000578{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000579 int ret;
580 int err;
581 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200582 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200583 _PyTime_t timeout, deadline = 0;
584 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000585
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200586 if (sock) {
587 if (((PyObject*)sock) == Py_None) {
588 _setSSLError("Underlying socket connection gone",
589 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
590 return NULL;
591 }
592 Py_INCREF(sock);
593
594 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100595 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200596 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
597 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000598 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000599
Victor Stinner14690702015-04-06 22:46:13 +0200600 timeout = GET_SOCKET_TIMEOUT(sock);
601 has_timeout = (timeout > 0);
602 if (has_timeout)
603 deadline = _PyTime_GetMonotonicClock() + timeout;
604
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000605 /* Actually negotiate SSL connection */
606 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000607 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000608 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000609 ret = SSL_do_handshake(self->ssl);
610 err = SSL_get_error(self->ssl, ret);
611 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200612
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000613 if (PyErr_CheckSignals())
614 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200615
Victor Stinner14690702015-04-06 22:46:13 +0200616 if (has_timeout)
617 timeout = deadline - _PyTime_GetMonotonicClock();
618
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000619 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200620 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000621 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200622 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000623 } else {
624 sockstate = SOCKET_OPERATION_OK;
625 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000627 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000628 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000629 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000630 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000631 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
632 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000633 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000634 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000635 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
636 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000637 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000638 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000639 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
640 break;
641 }
642 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200643 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000644 if (ret < 1)
645 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000646
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000647 if (self->peer_cert)
648 X509_free (self->peer_cert);
649 PySSL_BEGIN_ALLOW_THREADS
650 self->peer_cert = SSL_get_peer_certificate(self->ssl);
651 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200652 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000653
654 Py_INCREF(Py_None);
655 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000656
657error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200658 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000659 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000660}
661
Thomas Woutersed03b412007-08-28 21:37:11 +0000662static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000663_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000664
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000665 char namebuf[X509_NAME_MAXLEN];
666 int buflen;
667 PyObject *name_obj;
668 PyObject *value_obj;
669 PyObject *attr;
670 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000671
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000672 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
673 if (buflen < 0) {
674 _setSSLError(NULL, 0, __FILE__, __LINE__);
675 goto fail;
676 }
677 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
678 if (name_obj == NULL)
679 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000680
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000681 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
682 if (buflen < 0) {
683 _setSSLError(NULL, 0, __FILE__, __LINE__);
684 Py_DECREF(name_obj);
685 goto fail;
686 }
687 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000688 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000689 OPENSSL_free(valuebuf);
690 if (value_obj == NULL) {
691 Py_DECREF(name_obj);
692 goto fail;
693 }
694 attr = PyTuple_New(2);
695 if (attr == NULL) {
696 Py_DECREF(name_obj);
697 Py_DECREF(value_obj);
698 goto fail;
699 }
700 PyTuple_SET_ITEM(attr, 0, name_obj);
701 PyTuple_SET_ITEM(attr, 1, value_obj);
702 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000703
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000704 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000705 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000706}
707
708static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000709_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000710{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000711 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
712 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
713 PyObject *rdnt;
714 PyObject *attr = NULL; /* tuple to hold an attribute */
715 int entry_count = X509_NAME_entry_count(xname);
716 X509_NAME_ENTRY *entry;
717 ASN1_OBJECT *name;
718 ASN1_STRING *value;
719 int index_counter;
720 int rdn_level = -1;
721 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000722
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 dn = PyList_New(0);
724 if (dn == NULL)
725 return NULL;
726 /* now create another tuple to hold the top-level RDN */
727 rdn = PyList_New(0);
728 if (rdn == NULL)
729 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000730
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000731 for (index_counter = 0;
732 index_counter < entry_count;
733 index_counter++)
734 {
735 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000736
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000737 /* check to see if we've gotten to a new RDN */
738 if (rdn_level >= 0) {
739 if (rdn_level != entry->set) {
740 /* yes, new RDN */
741 /* add old RDN to DN */
742 rdnt = PyList_AsTuple(rdn);
743 Py_DECREF(rdn);
744 if (rdnt == NULL)
745 goto fail0;
746 retcode = PyList_Append(dn, rdnt);
747 Py_DECREF(rdnt);
748 if (retcode < 0)
749 goto fail0;
750 /* create new RDN */
751 rdn = PyList_New(0);
752 if (rdn == NULL)
753 goto fail0;
754 }
755 }
756 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000757
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000758 /* now add this attribute to the current RDN */
759 name = X509_NAME_ENTRY_get_object(entry);
760 value = X509_NAME_ENTRY_get_data(entry);
761 attr = _create_tuple_for_attribute(name, value);
762 /*
763 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
764 entry->set,
765 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
766 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
767 */
768 if (attr == NULL)
769 goto fail1;
770 retcode = PyList_Append(rdn, attr);
771 Py_DECREF(attr);
772 if (retcode < 0)
773 goto fail1;
774 }
775 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100776 if (rdn != NULL) {
777 if (PyList_GET_SIZE(rdn) > 0) {
778 rdnt = PyList_AsTuple(rdn);
779 Py_DECREF(rdn);
780 if (rdnt == NULL)
781 goto fail0;
782 retcode = PyList_Append(dn, rdnt);
783 Py_DECREF(rdnt);
784 if (retcode < 0)
785 goto fail0;
786 }
787 else {
788 Py_DECREF(rdn);
789 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000791
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 /* convert list to tuple */
793 rdnt = PyList_AsTuple(dn);
794 Py_DECREF(dn);
795 if (rdnt == NULL)
796 return NULL;
797 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000798
799 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000800 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000801
802 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 Py_XDECREF(dn);
804 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805}
806
807static PyObject *
808_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000809
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000810 /* this code follows the procedure outlined in
811 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
812 function to extract the STACK_OF(GENERAL_NAME),
813 then iterates through the stack to add the
814 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000815
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000816 int i, j;
817 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200818 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000819 X509_EXTENSION *ext = NULL;
820 GENERAL_NAMES *names = NULL;
821 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000822 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000823 BIO *biobuf = NULL;
824 char buf[2048];
825 char *vptr;
826 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000827 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000829 if (certificate == NULL)
830 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000831
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 /* get a memory buffer */
833 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000834
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200835 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000836 while ((i = X509_get_ext_by_NID(
837 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000838
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000839 if (peer_alt_names == Py_None) {
840 peer_alt_names = PyList_New(0);
841 if (peer_alt_names == NULL)
842 goto fail;
843 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000844
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000845 /* now decode the altName */
846 ext = X509_get_ext(certificate, i);
847 if(!(method = X509V3_EXT_get(ext))) {
848 PyErr_SetString
849 (PySSLErrorObject,
850 ERRSTR("No method for internalizing subjectAltName!"));
851 goto fail;
852 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000853
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000854 p = ext->value->data;
855 if (method->it)
856 names = (GENERAL_NAMES*)
857 (ASN1_item_d2i(NULL,
858 &p,
859 ext->value->length,
860 ASN1_ITEM_ptr(method->it)));
861 else
862 names = (GENERAL_NAMES*)
863 (method->d2i(NULL,
864 &p,
865 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000866
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000867 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000868 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200869 int gntype;
870 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000871
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000872 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200873 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200874 switch (gntype) {
875 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000876 /* we special-case DirName as a tuple of
877 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000878
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000879 t = PyTuple_New(2);
880 if (t == NULL) {
881 goto fail;
882 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000883
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000884 v = PyUnicode_FromString("DirName");
885 if (v == NULL) {
886 Py_DECREF(t);
887 goto fail;
888 }
889 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 v = _create_tuple_for_X509_NAME (name->d.dirn);
892 if (v == NULL) {
893 Py_DECREF(t);
894 goto fail;
895 }
896 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200897 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000898
Christian Heimes824f7f32013-08-17 00:54:47 +0200899 case GEN_EMAIL:
900 case GEN_DNS:
901 case GEN_URI:
902 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
903 correctly, CVE-2013-4238 */
904 t = PyTuple_New(2);
905 if (t == NULL)
906 goto fail;
907 switch (gntype) {
908 case GEN_EMAIL:
909 v = PyUnicode_FromString("email");
910 as = name->d.rfc822Name;
911 break;
912 case GEN_DNS:
913 v = PyUnicode_FromString("DNS");
914 as = name->d.dNSName;
915 break;
916 case GEN_URI:
917 v = PyUnicode_FromString("URI");
918 as = name->d.uniformResourceIdentifier;
919 break;
920 }
921 if (v == NULL) {
922 Py_DECREF(t);
923 goto fail;
924 }
925 PyTuple_SET_ITEM(t, 0, v);
926 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
927 ASN1_STRING_length(as));
928 if (v == NULL) {
929 Py_DECREF(t);
930 goto fail;
931 }
932 PyTuple_SET_ITEM(t, 1, v);
933 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000934
Christian Heimes824f7f32013-08-17 00:54:47 +0200935 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200937 switch (gntype) {
938 /* check for new general name type */
939 case GEN_OTHERNAME:
940 case GEN_X400:
941 case GEN_EDIPARTY:
942 case GEN_IPADD:
943 case GEN_RID:
944 break;
945 default:
946 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
947 "Unknown general name type %d",
948 gntype) == -1) {
949 goto fail;
950 }
951 break;
952 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000953 (void) BIO_reset(biobuf);
954 GENERAL_NAME_print(biobuf, name);
955 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
956 if (len < 0) {
957 _setSSLError(NULL, 0, __FILE__, __LINE__);
958 goto fail;
959 }
960 vptr = strchr(buf, ':');
961 if (vptr == NULL)
962 goto fail;
963 t = PyTuple_New(2);
964 if (t == NULL)
965 goto fail;
966 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
967 if (v == NULL) {
968 Py_DECREF(t);
969 goto fail;
970 }
971 PyTuple_SET_ITEM(t, 0, v);
972 v = PyUnicode_FromStringAndSize((vptr + 1),
973 (len - (vptr - buf + 1)));
974 if (v == NULL) {
975 Py_DECREF(t);
976 goto fail;
977 }
978 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200979 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000980 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000981
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000982 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000983
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000984 if (PyList_Append(peer_alt_names, t) < 0) {
985 Py_DECREF(t);
986 goto fail;
987 }
988 Py_DECREF(t);
989 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100990 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000991 }
992 BIO_free(biobuf);
993 if (peer_alt_names != Py_None) {
994 v = PyList_AsTuple(peer_alt_names);
995 Py_DECREF(peer_alt_names);
996 return v;
997 } else {
998 return peer_alt_names;
999 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001000
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001001
1002 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001003 if (biobuf != NULL)
1004 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001005
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001006 if (peer_alt_names != Py_None) {
1007 Py_XDECREF(peer_alt_names);
1008 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001009
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001010 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001011}
1012
1013static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001014_get_aia_uri(X509 *certificate, int nid) {
1015 PyObject *lst = NULL, *ostr = NULL;
1016 int i, result;
1017 AUTHORITY_INFO_ACCESS *info;
1018
1019 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
1020 if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
1021 return Py_None;
1022 }
1023
1024 if ((lst = PyList_New(0)) == NULL) {
1025 goto fail;
1026 }
1027
1028 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1029 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1030 ASN1_IA5STRING *uri;
1031
1032 if ((OBJ_obj2nid(ad->method) != nid) ||
1033 (ad->location->type != GEN_URI)) {
1034 continue;
1035 }
1036 uri = ad->location->d.uniformResourceIdentifier;
1037 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1038 uri->length);
1039 if (ostr == NULL) {
1040 goto fail;
1041 }
1042 result = PyList_Append(lst, ostr);
1043 Py_DECREF(ostr);
1044 if (result < 0) {
1045 goto fail;
1046 }
1047 }
1048 AUTHORITY_INFO_ACCESS_free(info);
1049
1050 /* convert to tuple or None */
1051 if (PyList_Size(lst) == 0) {
1052 Py_DECREF(lst);
1053 return Py_None;
1054 } else {
1055 PyObject *tup;
1056 tup = PyList_AsTuple(lst);
1057 Py_DECREF(lst);
1058 return tup;
1059 }
1060
1061 fail:
1062 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001063 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001064 return NULL;
1065}
1066
1067static PyObject *
1068_get_crl_dp(X509 *certificate) {
1069 STACK_OF(DIST_POINT) *dps;
1070 int i, j, result;
1071 PyObject *lst;
1072
Christian Heimes949ec142013-11-21 16:26:51 +01001073#if OPENSSL_VERSION_NUMBER < 0x10001000L
1074 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points,
1075 NULL, NULL);
1076#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001077 /* Calls x509v3_cache_extensions and sets up crldp */
1078 X509_check_ca(certificate);
1079 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001080#endif
1081
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001082 if (dps == NULL) {
1083 return Py_None;
1084 }
1085
1086 if ((lst = PyList_New(0)) == NULL) {
1087 return NULL;
1088 }
1089
1090 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1091 DIST_POINT *dp;
1092 STACK_OF(GENERAL_NAME) *gns;
1093
1094 dp = sk_DIST_POINT_value(dps, i);
1095 gns = dp->distpoint->name.fullname;
1096
1097 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1098 GENERAL_NAME *gn;
1099 ASN1_IA5STRING *uri;
1100 PyObject *ouri;
1101
1102 gn = sk_GENERAL_NAME_value(gns, j);
1103 if (gn->type != GEN_URI) {
1104 continue;
1105 }
1106 uri = gn->d.uniformResourceIdentifier;
1107 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1108 uri->length);
1109 if (ouri == NULL) {
1110 Py_DECREF(lst);
1111 return NULL;
1112 }
1113 result = PyList_Append(lst, ouri);
1114 Py_DECREF(ouri);
1115 if (result < 0) {
1116 Py_DECREF(lst);
1117 return NULL;
1118 }
1119 }
1120 }
1121 /* convert to tuple or None */
1122 if (PyList_Size(lst) == 0) {
1123 Py_DECREF(lst);
1124 return Py_None;
1125 } else {
1126 PyObject *tup;
1127 tup = PyList_AsTuple(lst);
1128 Py_DECREF(lst);
1129 return tup;
1130 }
1131}
1132
1133static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001134_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001135
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001136 PyObject *retval = NULL;
1137 BIO *biobuf = NULL;
1138 PyObject *peer;
1139 PyObject *peer_alt_names = NULL;
1140 PyObject *issuer;
1141 PyObject *version;
1142 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001143 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001144 ASN1_INTEGER *serialNumber;
1145 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001146 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 ASN1_TIME *notBefore, *notAfter;
1148 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001149
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 retval = PyDict_New();
1151 if (retval == NULL)
1152 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001153
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001154 peer = _create_tuple_for_X509_NAME(
1155 X509_get_subject_name(certificate));
1156 if (peer == NULL)
1157 goto fail0;
1158 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1159 Py_DECREF(peer);
1160 goto fail0;
1161 }
1162 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001163
Antoine Pitroufb046912010-11-09 20:21:19 +00001164 issuer = _create_tuple_for_X509_NAME(
1165 X509_get_issuer_name(certificate));
1166 if (issuer == NULL)
1167 goto fail0;
1168 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001169 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001170 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001171 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001172 Py_DECREF(issuer);
1173
1174 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001175 if (version == NULL)
1176 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001177 if (PyDict_SetItemString(retval, "version", version) < 0) {
1178 Py_DECREF(version);
1179 goto fail0;
1180 }
1181 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001182
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001183 /* get a memory buffer */
1184 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001185
Antoine Pitroufb046912010-11-09 20:21:19 +00001186 (void) BIO_reset(biobuf);
1187 serialNumber = X509_get_serialNumber(certificate);
1188 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1189 i2a_ASN1_INTEGER(biobuf, serialNumber);
1190 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1191 if (len < 0) {
1192 _setSSLError(NULL, 0, __FILE__, __LINE__);
1193 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001194 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001195 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1196 if (sn_obj == NULL)
1197 goto fail1;
1198 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1199 Py_DECREF(sn_obj);
1200 goto fail1;
1201 }
1202 Py_DECREF(sn_obj);
1203
1204 (void) BIO_reset(biobuf);
1205 notBefore = X509_get_notBefore(certificate);
1206 ASN1_TIME_print(biobuf, notBefore);
1207 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1208 if (len < 0) {
1209 _setSSLError(NULL, 0, __FILE__, __LINE__);
1210 goto fail1;
1211 }
1212 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1213 if (pnotBefore == NULL)
1214 goto fail1;
1215 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1216 Py_DECREF(pnotBefore);
1217 goto fail1;
1218 }
1219 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001220
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001221 (void) BIO_reset(biobuf);
1222 notAfter = X509_get_notAfter(certificate);
1223 ASN1_TIME_print(biobuf, notAfter);
1224 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1225 if (len < 0) {
1226 _setSSLError(NULL, 0, __FILE__, __LINE__);
1227 goto fail1;
1228 }
1229 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1230 if (pnotAfter == NULL)
1231 goto fail1;
1232 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1233 Py_DECREF(pnotAfter);
1234 goto fail1;
1235 }
1236 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001237
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001238 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001239
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001240 peer_alt_names = _get_peer_alt_names(certificate);
1241 if (peer_alt_names == NULL)
1242 goto fail1;
1243 else if (peer_alt_names != Py_None) {
1244 if (PyDict_SetItemString(retval, "subjectAltName",
1245 peer_alt_names) < 0) {
1246 Py_DECREF(peer_alt_names);
1247 goto fail1;
1248 }
1249 Py_DECREF(peer_alt_names);
1250 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001251
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001252 /* Authority Information Access: OCSP URIs */
1253 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1254 if (obj == NULL) {
1255 goto fail1;
1256 } else if (obj != Py_None) {
1257 result = PyDict_SetItemString(retval, "OCSP", obj);
1258 Py_DECREF(obj);
1259 if (result < 0) {
1260 goto fail1;
1261 }
1262 }
1263
1264 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1265 if (obj == NULL) {
1266 goto fail1;
1267 } else if (obj != Py_None) {
1268 result = PyDict_SetItemString(retval, "caIssuers", obj);
1269 Py_DECREF(obj);
1270 if (result < 0) {
1271 goto fail1;
1272 }
1273 }
1274
1275 /* CDP (CRL distribution points) */
1276 obj = _get_crl_dp(certificate);
1277 if (obj == NULL) {
1278 goto fail1;
1279 } else if (obj != Py_None) {
1280 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1281 Py_DECREF(obj);
1282 if (result < 0) {
1283 goto fail1;
1284 }
1285 }
1286
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 BIO_free(biobuf);
1288 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001289
1290 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001291 if (biobuf != NULL)
1292 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001293 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001294 Py_XDECREF(retval);
1295 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001296}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001297
Christian Heimes9a5395a2013-06-17 15:44:12 +02001298static PyObject *
1299_certificate_to_der(X509 *certificate)
1300{
1301 unsigned char *bytes_buf = NULL;
1302 int len;
1303 PyObject *retval;
1304
1305 bytes_buf = NULL;
1306 len = i2d_X509(certificate, &bytes_buf);
1307 if (len < 0) {
1308 _setSSLError(NULL, 0, __FILE__, __LINE__);
1309 return NULL;
1310 }
1311 /* this is actually an immutable bytes sequence */
1312 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1313 OPENSSL_free(bytes_buf);
1314 return retval;
1315}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001316
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001317/*[clinic input]
1318_ssl._test_decode_cert
1319 path: object(converter="PyUnicode_FSConverter")
1320 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001321
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001322[clinic start generated code]*/
1323
1324static PyObject *
1325_ssl__test_decode_cert_impl(PyModuleDef *module, PyObject *path)
1326/*[clinic end generated code: output=679e01db282804e9 input=cdeaaf02d4346628]*/
1327{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001328 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 X509 *x=NULL;
1330 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001331
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001332 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1333 PyErr_SetString(PySSLErrorObject,
1334 "Can't malloc memory to read file");
1335 goto fail0;
1336 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001337
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001338 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001339 PyErr_SetString(PySSLErrorObject,
1340 "Can't open file");
1341 goto fail0;
1342 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001343
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001344 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1345 if (x == NULL) {
1346 PyErr_SetString(PySSLErrorObject,
1347 "Error decoding PEM-encoded file");
1348 goto fail0;
1349 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001350
Antoine Pitroufb046912010-11-09 20:21:19 +00001351 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001352 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001353
1354 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001355 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001356 if (cert != NULL) BIO_free(cert);
1357 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001358}
1359
1360
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001361/*[clinic input]
1362_ssl._SSLSocket.peer_certificate
1363 der as binary_mode: bool = False
1364 /
1365
1366Returns the certificate for the peer.
1367
1368If no certificate was provided, returns None. If a certificate was
1369provided, but not validated, returns an empty dictionary. Otherwise
1370returns a dict containing information about the peer certificate.
1371
1372If the optional argument is True, returns a DER-encoded copy of the
1373peer certificate, or None if no certificate was provided. This will
1374return the certificate even if it wasn't validated.
1375[clinic start generated code]*/
1376
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001377static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001378_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1379/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001380{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001381 int verification;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001382
Antoine Pitrou20b85552013-09-29 19:50:53 +02001383 if (!self->handshake_done) {
1384 PyErr_SetString(PyExc_ValueError,
1385 "handshake not done yet");
1386 return NULL;
1387 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001388 if (!self->peer_cert)
1389 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001390
Antoine Pitrou721738f2012-08-15 23:20:39 +02001391 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001392 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001393 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001394 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001395 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001396 if ((verification & SSL_VERIFY_PEER) == 0)
1397 return PyDict_New();
1398 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001399 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001400 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001401}
1402
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001403static PyObject *
1404cipher_to_tuple(const SSL_CIPHER *cipher)
1405{
1406 const char *cipher_name, *cipher_protocol;
1407 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001408 if (retval == NULL)
1409 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001410
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001411 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001412 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001413 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001414 PyTuple_SET_ITEM(retval, 0, Py_None);
1415 } else {
1416 v = PyUnicode_FromString(cipher_name);
1417 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001418 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001419 PyTuple_SET_ITEM(retval, 0, v);
1420 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001421
1422 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001423 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001424 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001425 PyTuple_SET_ITEM(retval, 1, Py_None);
1426 } else {
1427 v = PyUnicode_FromString(cipher_protocol);
1428 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001429 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001430 PyTuple_SET_ITEM(retval, 1, v);
1431 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001432
1433 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001434 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001435 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001436 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001437
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001438 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001439
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001440 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001441 Py_DECREF(retval);
1442 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001443}
1444
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001445/*[clinic input]
1446_ssl._SSLSocket.shared_ciphers
1447[clinic start generated code]*/
1448
1449static PyObject *
1450_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1451/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001452{
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001453 SSL_SESSION *sess = SSL_get_session(self->ssl);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001454 STACK_OF(SSL_CIPHER) *ciphers;
1455 int i;
1456 PyObject *res;
1457
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001458 if (!sess || !sess->ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001459 Py_RETURN_NONE;
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001460 ciphers = sess->ciphers;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001461 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1462 if (!res)
1463 return NULL;
1464 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1465 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1466 if (!tup) {
1467 Py_DECREF(res);
1468 return NULL;
1469 }
1470 PyList_SET_ITEM(res, i, tup);
1471 }
1472 return res;
1473}
1474
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001475/*[clinic input]
1476_ssl._SSLSocket.cipher
1477[clinic start generated code]*/
1478
1479static PyObject *
1480_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1481/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001482{
1483 const SSL_CIPHER *current;
1484
1485 if (self->ssl == NULL)
1486 Py_RETURN_NONE;
1487 current = SSL_get_current_cipher(self->ssl);
1488 if (current == NULL)
1489 Py_RETURN_NONE;
1490 return cipher_to_tuple(current);
1491}
1492
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001493/*[clinic input]
1494_ssl._SSLSocket.version
1495[clinic start generated code]*/
1496
1497static PyObject *
1498_ssl__SSLSocket_version_impl(PySSLSocket *self)
1499/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001500{
1501 const char *version;
1502
1503 if (self->ssl == NULL)
1504 Py_RETURN_NONE;
1505 version = SSL_get_version(self->ssl);
1506 if (!strcmp(version, "unknown"))
1507 Py_RETURN_NONE;
1508 return PyUnicode_FromString(version);
1509}
1510
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001511#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001512/*[clinic input]
1513_ssl._SSLSocket.selected_npn_protocol
1514[clinic start generated code]*/
1515
1516static PyObject *
1517_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1518/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1519{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001520 const unsigned char *out;
1521 unsigned int outlen;
1522
Victor Stinner4569cd52013-06-23 14:58:43 +02001523 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001524 &out, &outlen);
1525
1526 if (out == NULL)
1527 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001528 return PyUnicode_FromStringAndSize((char *)out, outlen);
1529}
1530#endif
1531
1532#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001533/*[clinic input]
1534_ssl._SSLSocket.selected_alpn_protocol
1535[clinic start generated code]*/
1536
1537static PyObject *
1538_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1539/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1540{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001541 const unsigned char *out;
1542 unsigned int outlen;
1543
1544 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1545
1546 if (out == NULL)
1547 Py_RETURN_NONE;
1548 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001549}
1550#endif
1551
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001552/*[clinic input]
1553_ssl._SSLSocket.compression
1554[clinic start generated code]*/
1555
1556static PyObject *
1557_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1558/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1559{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001560#ifdef OPENSSL_NO_COMP
1561 Py_RETURN_NONE;
1562#else
1563 const COMP_METHOD *comp_method;
1564 const char *short_name;
1565
1566 if (self->ssl == NULL)
1567 Py_RETURN_NONE;
1568 comp_method = SSL_get_current_compression(self->ssl);
1569 if (comp_method == NULL || comp_method->type == NID_undef)
1570 Py_RETURN_NONE;
1571 short_name = OBJ_nid2sn(comp_method->type);
1572 if (short_name == NULL)
1573 Py_RETURN_NONE;
1574 return PyUnicode_DecodeFSDefault(short_name);
1575#endif
1576}
1577
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001578static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1579 Py_INCREF(self->ctx);
1580 return self->ctx;
1581}
1582
1583static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1584 void *closure) {
1585
1586 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001587#if !HAVE_SNI
1588 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1589 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001590 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001591#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001592 Py_INCREF(value);
1593 Py_DECREF(self->ctx);
1594 self->ctx = (PySSLContext *) value;
1595 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001596#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001597 } else {
1598 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1599 return -1;
1600 }
1601
1602 return 0;
1603}
1604
1605PyDoc_STRVAR(PySSL_set_context_doc,
1606"_setter_context(ctx)\n\
1607\
1608This changes the context associated with the SSLSocket. This is typically\n\
1609used from within a callback function set by the set_servername_callback\n\
1610on the SSLContext to change the certificate information associated with the\n\
1611SSLSocket before the cryptographic exchange handshake messages\n");
1612
1613
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001614static PyObject *
1615PySSL_get_server_side(PySSLSocket *self, void *c)
1616{
1617 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1618}
1619
1620PyDoc_STRVAR(PySSL_get_server_side_doc,
1621"Whether this is a server-side socket.");
1622
1623static PyObject *
1624PySSL_get_server_hostname(PySSLSocket *self, void *c)
1625{
1626 if (self->server_hostname == NULL)
1627 Py_RETURN_NONE;
1628 Py_INCREF(self->server_hostname);
1629 return self->server_hostname;
1630}
1631
1632PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1633"The currently set server hostname (for SNI).");
1634
1635static PyObject *
1636PySSL_get_owner(PySSLSocket *self, void *c)
1637{
1638 PyObject *owner;
1639
1640 if (self->owner == NULL)
1641 Py_RETURN_NONE;
1642
1643 owner = PyWeakref_GetObject(self->owner);
1644 Py_INCREF(owner);
1645 return owner;
1646}
1647
1648static int
1649PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1650{
1651 Py_XDECREF(self->owner);
1652 self->owner = PyWeakref_NewRef(value, NULL);
1653 if (self->owner == NULL)
1654 return -1;
1655 return 0;
1656}
1657
1658PyDoc_STRVAR(PySSL_get_owner_doc,
1659"The Python-level owner of this object.\
1660Passed as \"self\" in servername callback.");
1661
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001662
Antoine Pitrou152efa22010-05-16 18:19:27 +00001663static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001664{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001665 if (self->peer_cert) /* Possible not to have one? */
1666 X509_free (self->peer_cert);
1667 if (self->ssl)
1668 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001669 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001670 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001671 Py_XDECREF(self->server_hostname);
1672 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001673 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001674}
1675
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001676/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001677 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001678 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001679 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001680
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001681static int
Victor Stinner14690702015-04-06 22:46:13 +02001682PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001683{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001684 int rc;
1685#ifdef HAVE_POLL
1686 struct pollfd pollfd;
1687 _PyTime_t ms;
1688#else
1689 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001690 fd_set fds;
1691 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001692#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001693
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001694 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001695 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001696 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001697 else if (timeout < 0) {
1698 if (s->sock_timeout > 0)
1699 return SOCKET_HAS_TIMED_OUT;
1700 else
1701 return SOCKET_IS_BLOCKING;
1702 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001703
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001704 /* Guard against closed socket */
1705 if (s->sock_fd < 0)
1706 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001707
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001708 /* Prefer poll, if available, since you can poll() any fd
1709 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001710#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001711 pollfd.fd = s->sock_fd;
1712 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001713
Victor Stinner14690702015-04-06 22:46:13 +02001714 /* timeout is in seconds, poll() uses milliseconds */
1715 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001716 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001717
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001718 PySSL_BEGIN_ALLOW_THREADS
1719 rc = poll(&pollfd, 1, (int)ms);
1720 PySSL_END_ALLOW_THREADS
1721#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001722 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001723 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001724 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001725
Victor Stinner14690702015-04-06 22:46:13 +02001726 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001727
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001728 FD_ZERO(&fds);
1729 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001730
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001731 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001732 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001733 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001734 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001735 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001736 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001737 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001738 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001739#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001740
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001741 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1742 (when we are able to write or when there's something to read) */
1743 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001744}
1745
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001746/*[clinic input]
1747_ssl._SSLSocket.write
1748 b: Py_buffer
1749 /
1750
1751Writes the bytes-like object b into the SSL object.
1752
1753Returns the number of bytes written.
1754[clinic start generated code]*/
1755
1756static PyObject *
1757_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1758/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001759{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001760 int len;
1761 int sockstate;
1762 int err;
1763 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001764 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001765 _PyTime_t timeout, deadline = 0;
1766 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001767
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001768 if (sock != NULL) {
1769 if (((PyObject*)sock) == Py_None) {
1770 _setSSLError("Underlying socket connection gone",
1771 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1772 return NULL;
1773 }
1774 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001775 }
1776
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001777 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001778 PyErr_Format(PyExc_OverflowError,
1779 "string longer than %d bytes", INT_MAX);
1780 goto error;
1781 }
1782
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001783 if (sock != NULL) {
1784 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001785 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001786 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1787 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1788 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001789
Victor Stinner14690702015-04-06 22:46:13 +02001790 timeout = GET_SOCKET_TIMEOUT(sock);
1791 has_timeout = (timeout > 0);
1792 if (has_timeout)
1793 deadline = _PyTime_GetMonotonicClock() + timeout;
1794
1795 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001796 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001797 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001798 "The write operation timed out");
1799 goto error;
1800 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1801 PyErr_SetString(PySSLErrorObject,
1802 "Underlying socket has been closed.");
1803 goto error;
1804 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1805 PyErr_SetString(PySSLErrorObject,
1806 "Underlying socket too large for select().");
1807 goto error;
1808 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001809
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001811 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001812 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001813 err = SSL_get_error(self->ssl, len);
1814 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001815
1816 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001817 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001818
Victor Stinner14690702015-04-06 22:46:13 +02001819 if (has_timeout)
1820 timeout = deadline - _PyTime_GetMonotonicClock();
1821
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001822 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001823 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001824 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001825 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001826 } else {
1827 sockstate = SOCKET_OPERATION_OK;
1828 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001830 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001831 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001832 "The write operation timed out");
1833 goto error;
1834 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1835 PyErr_SetString(PySSLErrorObject,
1836 "Underlying socket has been closed.");
1837 goto error;
1838 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1839 break;
1840 }
1841 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001842
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001843 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001844 if (len > 0)
1845 return PyLong_FromLong(len);
1846 else
1847 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001848
1849error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001850 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001851 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001852}
1853
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001854/*[clinic input]
1855_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001856
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001857Returns the number of already decrypted bytes available for read, pending on the connection.
1858[clinic start generated code]*/
1859
1860static PyObject *
1861_ssl__SSLSocket_pending_impl(PySSLSocket *self)
1862/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00001863{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001864 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001865
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001866 PySSL_BEGIN_ALLOW_THREADS
1867 count = SSL_pending(self->ssl);
1868 PySSL_END_ALLOW_THREADS
1869 if (count < 0)
1870 return PySSL_SetError(self, count, __FILE__, __LINE__);
1871 else
1872 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001873}
1874
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001875/*[clinic input]
1876_ssl._SSLSocket.read
1877 size as len: int
1878 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001879 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001880 ]
1881 /
Bill Janssen6e027db2007-11-15 22:23:56 +00001882
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001883Read up to size bytes from the SSL socket.
1884[clinic start generated code]*/
1885
1886static PyObject *
1887_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
1888 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001889/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001890{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001891 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001892 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001893 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001894 int sockstate;
1895 int err;
1896 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001897 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001898 _PyTime_t timeout, deadline = 0;
1899 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001900
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001901 if (sock != NULL) {
1902 if (((PyObject*)sock) == Py_None) {
1903 _setSSLError("Underlying socket connection gone",
1904 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1905 return NULL;
1906 }
1907 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001908 }
1909
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001910 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001911 dest = PyBytes_FromStringAndSize(NULL, len);
1912 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001913 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001914 mem = PyBytes_AS_STRING(dest);
1915 }
1916 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001917 mem = buffer->buf;
1918 if (len <= 0 || len > buffer->len) {
1919 len = (int) buffer->len;
1920 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001921 PyErr_SetString(PyExc_OverflowError,
1922 "maximum length can't fit in a C 'int'");
1923 goto error;
1924 }
1925 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001926 }
1927
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001928 if (sock != NULL) {
1929 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001930 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001931 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1932 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1933 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001934
Victor Stinner14690702015-04-06 22:46:13 +02001935 timeout = GET_SOCKET_TIMEOUT(sock);
1936 has_timeout = (timeout > 0);
1937 if (has_timeout)
1938 deadline = _PyTime_GetMonotonicClock() + timeout;
1939
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001940 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001941 PySSL_BEGIN_ALLOW_THREADS
1942 count = SSL_read(self->ssl, mem, len);
1943 err = SSL_get_error(self->ssl, count);
1944 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001945
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001946 if (PyErr_CheckSignals())
1947 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001948
Victor Stinner14690702015-04-06 22:46:13 +02001949 if (has_timeout)
1950 timeout = deadline - _PyTime_GetMonotonicClock();
1951
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001952 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001953 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001954 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001955 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001956 } else if (err == SSL_ERROR_ZERO_RETURN &&
1957 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001958 {
1959 count = 0;
1960 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001961 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001962 else
1963 sockstate = SOCKET_OPERATION_OK;
1964
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001965 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001966 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001967 "The read operation timed out");
1968 goto error;
1969 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1970 break;
1971 }
1972 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001973
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001974 if (count <= 0) {
1975 PySSL_SetError(self, count, __FILE__, __LINE__);
1976 goto error;
1977 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001978
1979done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001980 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001981 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001982 _PyBytes_Resize(&dest, count);
1983 return dest;
1984 }
1985 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001986 return PyLong_FromLong(count);
1987 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001988
1989error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001990 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001991 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001992 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001993 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001994}
1995
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001996/*[clinic input]
1997_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001998
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001999Does the SSL shutdown handshake with the remote end.
2000
2001Returns the underlying socket object.
2002[clinic start generated code]*/
2003
2004static PyObject *
2005_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2006/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002007{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002008 int err, ssl_err, sockstate, nonblocking;
2009 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002010 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002011 _PyTime_t timeout, deadline = 0;
2012 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002013
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002014 if (sock != NULL) {
2015 /* Guard against closed socket */
2016 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
2017 _setSSLError("Underlying socket connection gone",
2018 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2019 return NULL;
2020 }
2021 Py_INCREF(sock);
2022
2023 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002024 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002025 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2026 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002027 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002028
Victor Stinner14690702015-04-06 22:46:13 +02002029 timeout = GET_SOCKET_TIMEOUT(sock);
2030 has_timeout = (timeout > 0);
2031 if (has_timeout)
2032 deadline = _PyTime_GetMonotonicClock() + timeout;
2033
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002034 while (1) {
2035 PySSL_BEGIN_ALLOW_THREADS
2036 /* Disable read-ahead so that unwrap can work correctly.
2037 * Otherwise OpenSSL might read in too much data,
2038 * eating clear text data that happens to be
2039 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002040 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002041 * function is used and the shutdown_seen_zero != 0
2042 * condition is met.
2043 */
2044 if (self->shutdown_seen_zero)
2045 SSL_set_read_ahead(self->ssl, 0);
2046 err = SSL_shutdown(self->ssl);
2047 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002048
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002049 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2050 if (err > 0)
2051 break;
2052 if (err == 0) {
2053 /* Don't loop endlessly; instead preserve legacy
2054 behaviour of trying SSL_shutdown() only twice.
2055 This looks necessary for OpenSSL < 0.9.8m */
2056 if (++zeros > 1)
2057 break;
2058 /* Shutdown was sent, now try receiving */
2059 self->shutdown_seen_zero = 1;
2060 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002061 }
2062
Victor Stinner14690702015-04-06 22:46:13 +02002063 if (has_timeout)
2064 timeout = deadline - _PyTime_GetMonotonicClock();
2065
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002066 /* Possibly retry shutdown until timeout or failure */
2067 ssl_err = SSL_get_error(self->ssl, err);
2068 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002069 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002070 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002071 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002072 else
2073 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002074
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002075 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2076 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002077 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002078 "The read operation timed out");
2079 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002080 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002081 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002082 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002083 }
2084 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2085 PyErr_SetString(PySSLErrorObject,
2086 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002087 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002088 }
2089 else if (sockstate != SOCKET_OPERATION_OK)
2090 /* Retain the SSL error code */
2091 break;
2092 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002093
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002094 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002095 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002096 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002097 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002098 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002099 /* It's already INCREF'ed */
2100 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002101 else
2102 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002103
2104error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002105 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002106 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002107}
2108
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002109/*[clinic input]
2110_ssl._SSLSocket.tls_unique_cb
2111
2112Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2113
2114If the TLS handshake is not yet complete, None is returned.
2115[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002116
Antoine Pitroud6494802011-07-21 01:11:30 +02002117static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002118_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2119/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002120{
2121 PyObject *retval = NULL;
2122 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002123 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002124
2125 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2126 /* if session is resumed XOR we are the client */
2127 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2128 }
2129 else {
2130 /* if a new session XOR we are the server */
2131 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2132 }
2133
2134 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002135 if (len == 0)
2136 Py_RETURN_NONE;
2137
2138 retval = PyBytes_FromStringAndSize(buf, len);
2139
2140 return retval;
2141}
2142
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002143static PyGetSetDef ssl_getsetlist[] = {
2144 {"context", (getter) PySSL_get_context,
2145 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002146 {"server_side", (getter) PySSL_get_server_side, NULL,
2147 PySSL_get_server_side_doc},
2148 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2149 PySSL_get_server_hostname_doc},
2150 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2151 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002152 {NULL}, /* sentinel */
2153};
2154
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002155static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002156 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2157 _SSL__SSLSOCKET_WRITE_METHODDEF
2158 _SSL__SSLSOCKET_READ_METHODDEF
2159 _SSL__SSLSOCKET_PENDING_METHODDEF
2160 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2161 _SSL__SSLSOCKET_CIPHER_METHODDEF
2162 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2163 _SSL__SSLSOCKET_VERSION_METHODDEF
2164 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2165 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2166 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2167 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2168 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002169 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002170};
2171
Antoine Pitrou152efa22010-05-16 18:19:27 +00002172static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002173 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002174 "_ssl._SSLSocket", /*tp_name*/
2175 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002176 0, /*tp_itemsize*/
2177 /* methods */
2178 (destructor)PySSL_dealloc, /*tp_dealloc*/
2179 0, /*tp_print*/
2180 0, /*tp_getattr*/
2181 0, /*tp_setattr*/
2182 0, /*tp_reserved*/
2183 0, /*tp_repr*/
2184 0, /*tp_as_number*/
2185 0, /*tp_as_sequence*/
2186 0, /*tp_as_mapping*/
2187 0, /*tp_hash*/
2188 0, /*tp_call*/
2189 0, /*tp_str*/
2190 0, /*tp_getattro*/
2191 0, /*tp_setattro*/
2192 0, /*tp_as_buffer*/
2193 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2194 0, /*tp_doc*/
2195 0, /*tp_traverse*/
2196 0, /*tp_clear*/
2197 0, /*tp_richcompare*/
2198 0, /*tp_weaklistoffset*/
2199 0, /*tp_iter*/
2200 0, /*tp_iternext*/
2201 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002202 0, /*tp_members*/
2203 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002204};
2205
Antoine Pitrou152efa22010-05-16 18:19:27 +00002206
2207/*
2208 * _SSLContext objects
2209 */
2210
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002211/*[clinic input]
2212@classmethod
2213_ssl._SSLContext.__new__
2214 protocol as proto_version: int
2215 /
2216[clinic start generated code]*/
2217
Antoine Pitrou152efa22010-05-16 18:19:27 +00002218static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002219_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2220/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002221{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002222 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002223 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002224 SSL_CTX *ctx = NULL;
2225
Antoine Pitrou152efa22010-05-16 18:19:27 +00002226 PySSL_BEGIN_ALLOW_THREADS
2227 if (proto_version == PY_SSL_VERSION_TLS1)
2228 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002229#if HAVE_TLSv1_2
2230 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2231 ctx = SSL_CTX_new(TLSv1_1_method());
2232 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2233 ctx = SSL_CTX_new(TLSv1_2_method());
2234#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002235#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002236 else if (proto_version == PY_SSL_VERSION_SSL3)
2237 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002238#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002239#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002240 else if (proto_version == PY_SSL_VERSION_SSL2)
2241 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002242#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002243 else if (proto_version == PY_SSL_VERSION_SSL23)
2244 ctx = SSL_CTX_new(SSLv23_method());
2245 else
2246 proto_version = -1;
2247 PySSL_END_ALLOW_THREADS
2248
2249 if (proto_version == -1) {
2250 PyErr_SetString(PyExc_ValueError,
2251 "invalid protocol version");
2252 return NULL;
2253 }
2254 if (ctx == NULL) {
2255 PyErr_SetString(PySSLErrorObject,
2256 "failed to allocate SSL context");
2257 return NULL;
2258 }
2259
2260 assert(type != NULL && type->tp_alloc != NULL);
2261 self = (PySSLContext *) type->tp_alloc(type, 0);
2262 if (self == NULL) {
2263 SSL_CTX_free(ctx);
2264 return NULL;
2265 }
2266 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002267#ifdef OPENSSL_NPN_NEGOTIATED
2268 self->npn_protocols = NULL;
2269#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002270#ifdef HAVE_ALPN
2271 self->alpn_protocols = NULL;
2272#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002273#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002274 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002275#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002276 /* Don't check host name by default */
2277 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002278 /* Defaults */
2279 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002280 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2281 if (proto_version != PY_SSL_VERSION_SSL2)
2282 options |= SSL_OP_NO_SSLv2;
2283 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002284
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002285#ifndef OPENSSL_NO_ECDH
2286 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2287 prime256v1 by default. This is Apache mod_ssl's initialization
2288 policy, so we should be safe. */
2289#if defined(SSL_CTX_set_ecdh_auto)
2290 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2291#else
2292 {
2293 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2294 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2295 EC_KEY_free(key);
2296 }
2297#endif
2298#endif
2299
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002300#define SID_CTX "Python"
2301 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2302 sizeof(SID_CTX));
2303#undef SID_CTX
2304
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002305#ifdef X509_V_FLAG_TRUSTED_FIRST
2306 {
2307 /* Improve trust chain building when cross-signed intermediate
2308 certificates are present. See https://bugs.python.org/issue23476. */
2309 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2310 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2311 }
2312#endif
2313
Antoine Pitrou152efa22010-05-16 18:19:27 +00002314 return (PyObject *)self;
2315}
2316
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002317static int
2318context_traverse(PySSLContext *self, visitproc visit, void *arg)
2319{
2320#ifndef OPENSSL_NO_TLSEXT
2321 Py_VISIT(self->set_hostname);
2322#endif
2323 return 0;
2324}
2325
2326static int
2327context_clear(PySSLContext *self)
2328{
2329#ifndef OPENSSL_NO_TLSEXT
2330 Py_CLEAR(self->set_hostname);
2331#endif
2332 return 0;
2333}
2334
Antoine Pitrou152efa22010-05-16 18:19:27 +00002335static void
2336context_dealloc(PySSLContext *self)
2337{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002338 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002339 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002340#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002341 PyMem_FREE(self->npn_protocols);
2342#endif
2343#ifdef HAVE_ALPN
2344 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002345#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002346 Py_TYPE(self)->tp_free(self);
2347}
2348
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002349/*[clinic input]
2350_ssl._SSLContext.set_ciphers
2351 cipherlist: str
2352 /
2353[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002354
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002355static PyObject *
2356_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2357/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2358{
2359 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002360 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002361 /* Clearing the error queue is necessary on some OpenSSL versions,
2362 otherwise the error will be reported again when another SSL call
2363 is done. */
2364 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002365 PyErr_SetString(PySSLErrorObject,
2366 "No cipher can be selected.");
2367 return NULL;
2368 }
2369 Py_RETURN_NONE;
2370}
2371
Benjamin Petersonc54de472015-01-28 12:06:39 -05002372#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002373static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002374do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2375 const unsigned char *server_protocols, unsigned int server_protocols_len,
2376 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002377{
Benjamin Peterson88615022015-01-23 17:30:26 -05002378 int ret;
2379 if (client_protocols == NULL) {
2380 client_protocols = (unsigned char *)"";
2381 client_protocols_len = 0;
2382 }
2383 if (server_protocols == NULL) {
2384 server_protocols = (unsigned char *)"";
2385 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002386 }
2387
Benjamin Peterson88615022015-01-23 17:30:26 -05002388 ret = SSL_select_next_proto(out, outlen,
2389 server_protocols, server_protocols_len,
2390 client_protocols, client_protocols_len);
2391 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2392 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002393
2394 return SSL_TLSEXT_ERR_OK;
2395}
2396
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002397/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2398static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002399_advertiseNPN_cb(SSL *s,
2400 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002401 void *args)
2402{
2403 PySSLContext *ssl_ctx = (PySSLContext *) args;
2404
2405 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002406 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002407 *len = 0;
2408 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002409 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002410 *len = ssl_ctx->npn_protocols_len;
2411 }
2412
2413 return SSL_TLSEXT_ERR_OK;
2414}
2415/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2416static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002417_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002418 unsigned char **out, unsigned char *outlen,
2419 const unsigned char *server, unsigned int server_len,
2420 void *args)
2421{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002422 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002423 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002424 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002425}
2426#endif
2427
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002428/*[clinic input]
2429_ssl._SSLContext._set_npn_protocols
2430 protos: Py_buffer
2431 /
2432[clinic start generated code]*/
2433
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002434static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002435_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2436 Py_buffer *protos)
2437/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002438{
2439#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002440 PyMem_Free(self->npn_protocols);
2441 self->npn_protocols = PyMem_Malloc(protos->len);
2442 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002443 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002444 memcpy(self->npn_protocols, protos->buf, protos->len);
2445 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002446
2447 /* set both server and client callbacks, because the context can
2448 * be used to create both types of sockets */
2449 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2450 _advertiseNPN_cb,
2451 self);
2452 SSL_CTX_set_next_proto_select_cb(self->ctx,
2453 _selectNPN_cb,
2454 self);
2455
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002456 Py_RETURN_NONE;
2457#else
2458 PyErr_SetString(PyExc_NotImplementedError,
2459 "The NPN extension requires OpenSSL 1.0.1 or later.");
2460 return NULL;
2461#endif
2462}
2463
Benjamin Petersoncca27322015-01-23 16:35:37 -05002464#ifdef HAVE_ALPN
2465static int
2466_selectALPN_cb(SSL *s,
2467 const unsigned char **out, unsigned char *outlen,
2468 const unsigned char *client_protocols, unsigned int client_protocols_len,
2469 void *args)
2470{
2471 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002472 return do_protocol_selection(1, (unsigned char **)out, outlen,
2473 ctx->alpn_protocols, ctx->alpn_protocols_len,
2474 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002475}
2476#endif
2477
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002478/*[clinic input]
2479_ssl._SSLContext._set_alpn_protocols
2480 protos: Py_buffer
2481 /
2482[clinic start generated code]*/
2483
Benjamin Petersoncca27322015-01-23 16:35:37 -05002484static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002485_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2486 Py_buffer *protos)
2487/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002488{
2489#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002490 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002491 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002492 if (!self->alpn_protocols)
2493 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002494 memcpy(self->alpn_protocols, protos->buf, protos->len);
2495 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002496
2497 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2498 return PyErr_NoMemory();
2499 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2500
Benjamin Petersoncca27322015-01-23 16:35:37 -05002501 Py_RETURN_NONE;
2502#else
2503 PyErr_SetString(PyExc_NotImplementedError,
2504 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2505 return NULL;
2506#endif
2507}
2508
Antoine Pitrou152efa22010-05-16 18:19:27 +00002509static PyObject *
2510get_verify_mode(PySSLContext *self, void *c)
2511{
2512 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2513 case SSL_VERIFY_NONE:
2514 return PyLong_FromLong(PY_SSL_CERT_NONE);
2515 case SSL_VERIFY_PEER:
2516 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2517 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2518 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2519 }
2520 PyErr_SetString(PySSLErrorObject,
2521 "invalid return value from SSL_CTX_get_verify_mode");
2522 return NULL;
2523}
2524
2525static int
2526set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2527{
2528 int n, mode;
2529 if (!PyArg_Parse(arg, "i", &n))
2530 return -1;
2531 if (n == PY_SSL_CERT_NONE)
2532 mode = SSL_VERIFY_NONE;
2533 else if (n == PY_SSL_CERT_OPTIONAL)
2534 mode = SSL_VERIFY_PEER;
2535 else if (n == PY_SSL_CERT_REQUIRED)
2536 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2537 else {
2538 PyErr_SetString(PyExc_ValueError,
2539 "invalid value for verify_mode");
2540 return -1;
2541 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002542 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2543 PyErr_SetString(PyExc_ValueError,
2544 "Cannot set verify_mode to CERT_NONE when "
2545 "check_hostname is enabled.");
2546 return -1;
2547 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002548 SSL_CTX_set_verify(self->ctx, mode, NULL);
2549 return 0;
2550}
2551
2552static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002553get_verify_flags(PySSLContext *self, void *c)
2554{
2555 X509_STORE *store;
2556 unsigned long flags;
2557
2558 store = SSL_CTX_get_cert_store(self->ctx);
2559 flags = X509_VERIFY_PARAM_get_flags(store->param);
2560 return PyLong_FromUnsignedLong(flags);
2561}
2562
2563static int
2564set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2565{
2566 X509_STORE *store;
2567 unsigned long new_flags, flags, set, clear;
2568
2569 if (!PyArg_Parse(arg, "k", &new_flags))
2570 return -1;
2571 store = SSL_CTX_get_cert_store(self->ctx);
2572 flags = X509_VERIFY_PARAM_get_flags(store->param);
2573 clear = flags & ~new_flags;
2574 set = ~flags & new_flags;
2575 if (clear) {
2576 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2577 _setSSLError(NULL, 0, __FILE__, __LINE__);
2578 return -1;
2579 }
2580 }
2581 if (set) {
2582 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2583 _setSSLError(NULL, 0, __FILE__, __LINE__);
2584 return -1;
2585 }
2586 }
2587 return 0;
2588}
2589
2590static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002591get_options(PySSLContext *self, void *c)
2592{
2593 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2594}
2595
2596static int
2597set_options(PySSLContext *self, PyObject *arg, void *c)
2598{
2599 long new_opts, opts, set, clear;
2600 if (!PyArg_Parse(arg, "l", &new_opts))
2601 return -1;
2602 opts = SSL_CTX_get_options(self->ctx);
2603 clear = opts & ~new_opts;
2604 set = ~opts & new_opts;
2605 if (clear) {
2606#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2607 SSL_CTX_clear_options(self->ctx, clear);
2608#else
2609 PyErr_SetString(PyExc_ValueError,
2610 "can't clear options before OpenSSL 0.9.8m");
2611 return -1;
2612#endif
2613 }
2614 if (set)
2615 SSL_CTX_set_options(self->ctx, set);
2616 return 0;
2617}
2618
Christian Heimes1aa9a752013-12-02 02:41:19 +01002619static PyObject *
2620get_check_hostname(PySSLContext *self, void *c)
2621{
2622 return PyBool_FromLong(self->check_hostname);
2623}
2624
2625static int
2626set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2627{
2628 int check_hostname;
2629 if (!PyArg_Parse(arg, "p", &check_hostname))
2630 return -1;
2631 if (check_hostname &&
2632 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2633 PyErr_SetString(PyExc_ValueError,
2634 "check_hostname needs a SSL context with either "
2635 "CERT_OPTIONAL or CERT_REQUIRED");
2636 return -1;
2637 }
2638 self->check_hostname = check_hostname;
2639 return 0;
2640}
2641
2642
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002643typedef struct {
2644 PyThreadState *thread_state;
2645 PyObject *callable;
2646 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002647 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002648 int error;
2649} _PySSLPasswordInfo;
2650
2651static int
2652_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2653 const char *bad_type_error)
2654{
2655 /* Set the password and size fields of a _PySSLPasswordInfo struct
2656 from a unicode, bytes, or byte array object.
2657 The password field will be dynamically allocated and must be freed
2658 by the caller */
2659 PyObject *password_bytes = NULL;
2660 const char *data = NULL;
2661 Py_ssize_t size;
2662
2663 if (PyUnicode_Check(password)) {
2664 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2665 if (!password_bytes) {
2666 goto error;
2667 }
2668 data = PyBytes_AS_STRING(password_bytes);
2669 size = PyBytes_GET_SIZE(password_bytes);
2670 } else if (PyBytes_Check(password)) {
2671 data = PyBytes_AS_STRING(password);
2672 size = PyBytes_GET_SIZE(password);
2673 } else if (PyByteArray_Check(password)) {
2674 data = PyByteArray_AS_STRING(password);
2675 size = PyByteArray_GET_SIZE(password);
2676 } else {
2677 PyErr_SetString(PyExc_TypeError, bad_type_error);
2678 goto error;
2679 }
2680
Victor Stinner9ee02032013-06-23 15:08:23 +02002681 if (size > (Py_ssize_t)INT_MAX) {
2682 PyErr_Format(PyExc_ValueError,
2683 "password cannot be longer than %d bytes", INT_MAX);
2684 goto error;
2685 }
2686
Victor Stinner11ebff22013-07-07 17:07:52 +02002687 PyMem_Free(pw_info->password);
2688 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002689 if (!pw_info->password) {
2690 PyErr_SetString(PyExc_MemoryError,
2691 "unable to allocate password buffer");
2692 goto error;
2693 }
2694 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002695 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002696
2697 Py_XDECREF(password_bytes);
2698 return 1;
2699
2700error:
2701 Py_XDECREF(password_bytes);
2702 return 0;
2703}
2704
2705static int
2706_password_callback(char *buf, int size, int rwflag, void *userdata)
2707{
2708 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2709 PyObject *fn_ret = NULL;
2710
2711 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2712
2713 if (pw_info->callable) {
2714 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2715 if (!fn_ret) {
2716 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2717 core python API, so we could use it to add a frame here */
2718 goto error;
2719 }
2720
2721 if (!_pwinfo_set(pw_info, fn_ret,
2722 "password callback must return a string")) {
2723 goto error;
2724 }
2725 Py_CLEAR(fn_ret);
2726 }
2727
2728 if (pw_info->size > size) {
2729 PyErr_Format(PyExc_ValueError,
2730 "password cannot be longer than %d bytes", size);
2731 goto error;
2732 }
2733
2734 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2735 memcpy(buf, pw_info->password, pw_info->size);
2736 return pw_info->size;
2737
2738error:
2739 Py_XDECREF(fn_ret);
2740 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2741 pw_info->error = 1;
2742 return -1;
2743}
2744
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002745/*[clinic input]
2746_ssl._SSLContext.load_cert_chain
2747 certfile: object
2748 keyfile: object = NULL
2749 password: object = NULL
2750
2751[clinic start generated code]*/
2752
Antoine Pitroub5218772010-05-21 09:56:06 +00002753static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002754_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
2755 PyObject *keyfile, PyObject *password)
2756/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002757{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002758 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002759 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2760 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2761 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002762 int r;
2763
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002764 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002765 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002766 if (keyfile == Py_None)
2767 keyfile = NULL;
2768 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2769 PyErr_SetString(PyExc_TypeError,
2770 "certfile should be a valid filesystem path");
2771 return NULL;
2772 }
2773 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2774 PyErr_SetString(PyExc_TypeError,
2775 "keyfile should be a valid filesystem path");
2776 goto error;
2777 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002778 if (password && password != Py_None) {
2779 if (PyCallable_Check(password)) {
2780 pw_info.callable = password;
2781 } else if (!_pwinfo_set(&pw_info, password,
2782 "password should be a string or callable")) {
2783 goto error;
2784 }
2785 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2786 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2787 }
2788 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002789 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2790 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002791 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002792 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002793 if (pw_info.error) {
2794 ERR_clear_error();
2795 /* the password callback has already set the error information */
2796 }
2797 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002798 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002799 PyErr_SetFromErrno(PyExc_IOError);
2800 }
2801 else {
2802 _setSSLError(NULL, 0, __FILE__, __LINE__);
2803 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002804 goto error;
2805 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002806 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002807 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002808 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2809 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002810 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2811 Py_CLEAR(keyfile_bytes);
2812 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002813 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002814 if (pw_info.error) {
2815 ERR_clear_error();
2816 /* the password callback has already set the error information */
2817 }
2818 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002819 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002820 PyErr_SetFromErrno(PyExc_IOError);
2821 }
2822 else {
2823 _setSSLError(NULL, 0, __FILE__, __LINE__);
2824 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002825 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002826 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002827 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002828 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002829 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002830 if (r != 1) {
2831 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002832 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002833 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002834 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2835 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002836 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002837 Py_RETURN_NONE;
2838
2839error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002840 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2841 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002842 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002843 Py_XDECREF(keyfile_bytes);
2844 Py_XDECREF(certfile_bytes);
2845 return NULL;
2846}
2847
Christian Heimesefff7062013-11-21 03:35:02 +01002848/* internal helper function, returns -1 on error
2849 */
2850static int
2851_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2852 int filetype)
2853{
2854 BIO *biobuf = NULL;
2855 X509_STORE *store;
2856 int retval = 0, err, loaded = 0;
2857
2858 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2859
2860 if (len <= 0) {
2861 PyErr_SetString(PyExc_ValueError,
2862 "Empty certificate data");
2863 return -1;
2864 } else if (len > INT_MAX) {
2865 PyErr_SetString(PyExc_OverflowError,
2866 "Certificate data is too long.");
2867 return -1;
2868 }
2869
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002870 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002871 if (biobuf == NULL) {
2872 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2873 return -1;
2874 }
2875
2876 store = SSL_CTX_get_cert_store(self->ctx);
2877 assert(store != NULL);
2878
2879 while (1) {
2880 X509 *cert = NULL;
2881 int r;
2882
2883 if (filetype == SSL_FILETYPE_ASN1) {
2884 cert = d2i_X509_bio(biobuf, NULL);
2885 } else {
2886 cert = PEM_read_bio_X509(biobuf, NULL,
2887 self->ctx->default_passwd_callback,
2888 self->ctx->default_passwd_callback_userdata);
2889 }
2890 if (cert == NULL) {
2891 break;
2892 }
2893 r = X509_STORE_add_cert(store, cert);
2894 X509_free(cert);
2895 if (!r) {
2896 err = ERR_peek_last_error();
2897 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2898 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2899 /* cert already in hash table, not an error */
2900 ERR_clear_error();
2901 } else {
2902 break;
2903 }
2904 }
2905 loaded++;
2906 }
2907
2908 err = ERR_peek_last_error();
2909 if ((filetype == SSL_FILETYPE_ASN1) &&
2910 (loaded > 0) &&
2911 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2912 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2913 /* EOF ASN1 file, not an error */
2914 ERR_clear_error();
2915 retval = 0;
2916 } else if ((filetype == SSL_FILETYPE_PEM) &&
2917 (loaded > 0) &&
2918 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2919 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2920 /* EOF PEM file, not an error */
2921 ERR_clear_error();
2922 retval = 0;
2923 } else {
2924 _setSSLError(NULL, 0, __FILE__, __LINE__);
2925 retval = -1;
2926 }
2927
2928 BIO_free(biobuf);
2929 return retval;
2930}
2931
2932
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002933/*[clinic input]
2934_ssl._SSLContext.load_verify_locations
2935 cafile: object = NULL
2936 capath: object = NULL
2937 cadata: object = NULL
2938
2939[clinic start generated code]*/
2940
Antoine Pitrou152efa22010-05-16 18:19:27 +00002941static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002942_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
2943 PyObject *cafile,
2944 PyObject *capath,
2945 PyObject *cadata)
2946/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002947{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002948 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2949 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002950 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002951
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002952 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002953 if (cafile == Py_None)
2954 cafile = NULL;
2955 if (capath == Py_None)
2956 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002957 if (cadata == Py_None)
2958 cadata = NULL;
2959
2960 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002961 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002962 "cafile, capath and cadata cannot be all omitted");
2963 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002964 }
2965 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2966 PyErr_SetString(PyExc_TypeError,
2967 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002968 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002969 }
2970 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002971 PyErr_SetString(PyExc_TypeError,
2972 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002973 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002974 }
Christian Heimesefff7062013-11-21 03:35:02 +01002975
2976 /* validata cadata type and load cadata */
2977 if (cadata) {
2978 Py_buffer buf;
2979 PyObject *cadata_ascii = NULL;
2980
2981 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2982 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2983 PyBuffer_Release(&buf);
2984 PyErr_SetString(PyExc_TypeError,
2985 "cadata should be a contiguous buffer with "
2986 "a single dimension");
2987 goto error;
2988 }
2989 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2990 PyBuffer_Release(&buf);
2991 if (r == -1) {
2992 goto error;
2993 }
2994 } else {
2995 PyErr_Clear();
2996 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2997 if (cadata_ascii == NULL) {
2998 PyErr_SetString(PyExc_TypeError,
2999 "cadata should be a ASCII string or a "
3000 "bytes-like object");
3001 goto error;
3002 }
3003 r = _add_ca_certs(self,
3004 PyBytes_AS_STRING(cadata_ascii),
3005 PyBytes_GET_SIZE(cadata_ascii),
3006 SSL_FILETYPE_PEM);
3007 Py_DECREF(cadata_ascii);
3008 if (r == -1) {
3009 goto error;
3010 }
3011 }
3012 }
3013
3014 /* load cafile or capath */
3015 if (cafile || capath) {
3016 if (cafile)
3017 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3018 if (capath)
3019 capath_buf = PyBytes_AS_STRING(capath_bytes);
3020 PySSL_BEGIN_ALLOW_THREADS
3021 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3022 PySSL_END_ALLOW_THREADS
3023 if (r != 1) {
3024 ok = 0;
3025 if (errno != 0) {
3026 ERR_clear_error();
3027 PyErr_SetFromErrno(PyExc_IOError);
3028 }
3029 else {
3030 _setSSLError(NULL, 0, __FILE__, __LINE__);
3031 }
3032 goto error;
3033 }
3034 }
3035 goto end;
3036
3037 error:
3038 ok = 0;
3039 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003040 Py_XDECREF(cafile_bytes);
3041 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003042 if (ok) {
3043 Py_RETURN_NONE;
3044 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003045 return NULL;
3046 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003047}
3048
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003049/*[clinic input]
3050_ssl._SSLContext.load_dh_params
3051 path as filepath: object
3052 /
3053
3054[clinic start generated code]*/
3055
Antoine Pitrou152efa22010-05-16 18:19:27 +00003056static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003057_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3058/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003059{
3060 FILE *f;
3061 DH *dh;
3062
Victor Stinnerdaf45552013-08-28 00:53:59 +02003063 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003064 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003065 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003066
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003067 errno = 0;
3068 PySSL_BEGIN_ALLOW_THREADS
3069 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003070 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003071 PySSL_END_ALLOW_THREADS
3072 if (dh == NULL) {
3073 if (errno != 0) {
3074 ERR_clear_error();
3075 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3076 }
3077 else {
3078 _setSSLError(NULL, 0, __FILE__, __LINE__);
3079 }
3080 return NULL;
3081 }
3082 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3083 _setSSLError(NULL, 0, __FILE__, __LINE__);
3084 DH_free(dh);
3085 Py_RETURN_NONE;
3086}
3087
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003088/*[clinic input]
3089_ssl._SSLContext._wrap_socket
3090 sock: object(subclass_of="PySocketModule.Sock_Type")
3091 server_side: int
3092 server_hostname as hostname_obj: object = None
3093
3094[clinic start generated code]*/
3095
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003096static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003097_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3098 int server_side, PyObject *hostname_obj)
3099/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003100{
Antoine Pitroud5323212010-10-22 18:19:07 +00003101 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003102 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003103
Antoine Pitroud5323212010-10-22 18:19:07 +00003104 /* server_hostname is either None (or absent), or to be encoded
3105 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003106 if (hostname_obj != Py_None) {
3107 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003108 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003109 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003110
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003111 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3112 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003113 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003114 if (hostname != NULL)
3115 PyMem_Free(hostname);
3116 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003117}
3118
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003119/*[clinic input]
3120_ssl._SSLContext._wrap_bio
3121 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3122 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3123 server_side: int
3124 server_hostname as hostname_obj: object = None
3125
3126[clinic start generated code]*/
3127
Antoine Pitroub0182c82010-10-12 20:09:02 +00003128static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003129_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3130 PySSLMemoryBIO *outgoing, int server_side,
3131 PyObject *hostname_obj)
3132/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003133{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003134 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003135 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003136
3137 /* server_hostname is either None (or absent), or to be encoded
3138 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003139 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003140 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3141 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003142 }
3143
3144 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3145 incoming, outgoing);
3146
3147 PyMem_Free(hostname);
3148 return res;
3149}
3150
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003151/*[clinic input]
3152_ssl._SSLContext.session_stats
3153[clinic start generated code]*/
3154
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003155static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003156_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3157/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003158{
3159 int r;
3160 PyObject *value, *stats = PyDict_New();
3161 if (!stats)
3162 return NULL;
3163
3164#define ADD_STATS(SSL_NAME, KEY_NAME) \
3165 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3166 if (value == NULL) \
3167 goto error; \
3168 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3169 Py_DECREF(value); \
3170 if (r < 0) \
3171 goto error;
3172
3173 ADD_STATS(number, "number");
3174 ADD_STATS(connect, "connect");
3175 ADD_STATS(connect_good, "connect_good");
3176 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3177 ADD_STATS(accept, "accept");
3178 ADD_STATS(accept_good, "accept_good");
3179 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3180 ADD_STATS(accept, "accept");
3181 ADD_STATS(hits, "hits");
3182 ADD_STATS(misses, "misses");
3183 ADD_STATS(timeouts, "timeouts");
3184 ADD_STATS(cache_full, "cache_full");
3185
3186#undef ADD_STATS
3187
3188 return stats;
3189
3190error:
3191 Py_DECREF(stats);
3192 return NULL;
3193}
3194
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003195/*[clinic input]
3196_ssl._SSLContext.set_default_verify_paths
3197[clinic start generated code]*/
3198
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003199static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003200_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3201/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003202{
3203 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3204 _setSSLError(NULL, 0, __FILE__, __LINE__);
3205 return NULL;
3206 }
3207 Py_RETURN_NONE;
3208}
3209
Antoine Pitrou501da612011-12-21 09:27:41 +01003210#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003211/*[clinic input]
3212_ssl._SSLContext.set_ecdh_curve
3213 name: object
3214 /
3215
3216[clinic start generated code]*/
3217
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003218static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003219_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3220/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003221{
3222 PyObject *name_bytes;
3223 int nid;
3224 EC_KEY *key;
3225
3226 if (!PyUnicode_FSConverter(name, &name_bytes))
3227 return NULL;
3228 assert(PyBytes_Check(name_bytes));
3229 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3230 Py_DECREF(name_bytes);
3231 if (nid == 0) {
3232 PyErr_Format(PyExc_ValueError,
3233 "unknown elliptic curve name %R", name);
3234 return NULL;
3235 }
3236 key = EC_KEY_new_by_curve_name(nid);
3237 if (key == NULL) {
3238 _setSSLError(NULL, 0, __FILE__, __LINE__);
3239 return NULL;
3240 }
3241 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3242 EC_KEY_free(key);
3243 Py_RETURN_NONE;
3244}
Antoine Pitrou501da612011-12-21 09:27:41 +01003245#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003246
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003247#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003248static int
3249_servername_callback(SSL *s, int *al, void *args)
3250{
3251 int ret;
3252 PySSLContext *ssl_ctx = (PySSLContext *) args;
3253 PySSLSocket *ssl;
3254 PyObject *servername_o;
3255 PyObject *servername_idna;
3256 PyObject *result;
3257 /* The high-level ssl.SSLSocket object */
3258 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003259 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003260#ifdef WITH_THREAD
3261 PyGILState_STATE gstate = PyGILState_Ensure();
3262#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003263
3264 if (ssl_ctx->set_hostname == NULL) {
3265 /* remove race condition in this the call back while if removing the
3266 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003267#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003268 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003269#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003270 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003271 }
3272
3273 ssl = SSL_get_app_data(s);
3274 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003275
3276 /* The servername callback expects a argument that represents the current
3277 * SSL connection and that has a .context attribute that can be changed to
3278 * identify the requested hostname. Since the official API is the Python
3279 * level API we want to pass the callback a Python level object rather than
3280 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3281 * SSLObject) that will be passed. Otherwise if there's a socket then that
3282 * will be passed. If both do not exist only then the C-level object is
3283 * passed. */
3284 if (ssl->owner)
3285 ssl_socket = PyWeakref_GetObject(ssl->owner);
3286 else if (ssl->Socket)
3287 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3288 else
3289 ssl_socket = (PyObject *) ssl;
3290
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003291 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003292 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003293 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003294
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003295 if (servername == NULL) {
3296 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3297 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003298 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003299 else {
3300 servername_o = PyBytes_FromString(servername);
3301 if (servername_o == NULL) {
3302 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3303 goto error;
3304 }
3305 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3306 if (servername_idna == NULL) {
3307 PyErr_WriteUnraisable(servername_o);
3308 Py_DECREF(servername_o);
3309 goto error;
3310 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003311 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003312 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3313 servername_idna, ssl_ctx, NULL);
3314 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003315 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003316 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003317
3318 if (result == NULL) {
3319 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3320 *al = SSL_AD_HANDSHAKE_FAILURE;
3321 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3322 }
3323 else {
3324 if (result != Py_None) {
3325 *al = (int) PyLong_AsLong(result);
3326 if (PyErr_Occurred()) {
3327 PyErr_WriteUnraisable(result);
3328 *al = SSL_AD_INTERNAL_ERROR;
3329 }
3330 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3331 }
3332 else {
3333 ret = SSL_TLSEXT_ERR_OK;
3334 }
3335 Py_DECREF(result);
3336 }
3337
Stefan Krah20d60802013-01-17 17:07:17 +01003338#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003339 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003340#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003341 return ret;
3342
3343error:
3344 Py_DECREF(ssl_socket);
3345 *al = SSL_AD_INTERNAL_ERROR;
3346 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003347#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003348 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003349#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003350 return ret;
3351}
Antoine Pitroua5963382013-03-30 16:39:00 +01003352#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003353
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003354/*[clinic input]
3355_ssl._SSLContext.set_servername_callback
3356 method as cb: object
3357 /
3358
3359Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3360
3361If the argument is None then the callback is disabled. The method is called
3362with the SSLSocket, the server name as a string, and the SSLContext object.
3363See RFC 6066 for details of the SNI extension.
3364[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003365
3366static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003367_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3368/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003369{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003370#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003371 Py_CLEAR(self->set_hostname);
3372 if (cb == Py_None) {
3373 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3374 }
3375 else {
3376 if (!PyCallable_Check(cb)) {
3377 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3378 PyErr_SetString(PyExc_TypeError,
3379 "not a callable object");
3380 return NULL;
3381 }
3382 Py_INCREF(cb);
3383 self->set_hostname = cb;
3384 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3385 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3386 }
3387 Py_RETURN_NONE;
3388#else
3389 PyErr_SetString(PyExc_NotImplementedError,
3390 "The TLS extension servername callback, "
3391 "SSL_CTX_set_tlsext_servername_callback, "
3392 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003393 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003394#endif
3395}
3396
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003397/*[clinic input]
3398_ssl._SSLContext.cert_store_stats
3399
3400Returns quantities of loaded X.509 certificates.
3401
3402X.509 certificates with a CA extension and certificate revocation lists
3403inside the context's cert store.
3404
3405NOTE: Certificates in a capath directory aren't loaded unless they have
3406been used at least once.
3407[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003408
3409static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003410_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3411/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003412{
3413 X509_STORE *store;
3414 X509_OBJECT *obj;
3415 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3416
3417 store = SSL_CTX_get_cert_store(self->ctx);
3418 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3419 obj = sk_X509_OBJECT_value(store->objs, i);
3420 switch (obj->type) {
3421 case X509_LU_X509:
3422 x509++;
3423 if (X509_check_ca(obj->data.x509)) {
3424 ca++;
3425 }
3426 break;
3427 case X509_LU_CRL:
3428 crl++;
3429 break;
3430 case X509_LU_PKEY:
3431 pkey++;
3432 break;
3433 default:
3434 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3435 * As far as I can tell they are internal states and never
3436 * stored in a cert store */
3437 break;
3438 }
3439 }
3440 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3441 "x509_ca", ca);
3442}
3443
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003444/*[clinic input]
3445_ssl._SSLContext.get_ca_certs
3446 binary_form: bool = False
3447
3448Returns a list of dicts with information of loaded CA certs.
3449
3450If the optional argument is True, returns a DER-encoded copy of the CA
3451certificate.
3452
3453NOTE: Certificates in a capath directory aren't loaded unless they have
3454been used at least once.
3455[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003456
3457static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003458_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3459/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003460{
3461 X509_STORE *store;
3462 PyObject *ci = NULL, *rlist = NULL;
3463 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003464
3465 if ((rlist = PyList_New(0)) == NULL) {
3466 return NULL;
3467 }
3468
3469 store = SSL_CTX_get_cert_store(self->ctx);
3470 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3471 X509_OBJECT *obj;
3472 X509 *cert;
3473
3474 obj = sk_X509_OBJECT_value(store->objs, i);
3475 if (obj->type != X509_LU_X509) {
3476 /* not a x509 cert */
3477 continue;
3478 }
3479 /* CA for any purpose */
3480 cert = obj->data.x509;
3481 if (!X509_check_ca(cert)) {
3482 continue;
3483 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003484 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003485 ci = _certificate_to_der(cert);
3486 } else {
3487 ci = _decode_certificate(cert);
3488 }
3489 if (ci == NULL) {
3490 goto error;
3491 }
3492 if (PyList_Append(rlist, ci) == -1) {
3493 goto error;
3494 }
3495 Py_CLEAR(ci);
3496 }
3497 return rlist;
3498
3499 error:
3500 Py_XDECREF(ci);
3501 Py_XDECREF(rlist);
3502 return NULL;
3503}
3504
3505
Antoine Pitrou152efa22010-05-16 18:19:27 +00003506static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003507 {"check_hostname", (getter) get_check_hostname,
3508 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003509 {"options", (getter) get_options,
3510 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003511 {"verify_flags", (getter) get_verify_flags,
3512 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003513 {"verify_mode", (getter) get_verify_mode,
3514 (setter) set_verify_mode, NULL},
3515 {NULL}, /* sentinel */
3516};
3517
3518static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003519 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
3520 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
3521 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
3522 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
3523 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
3524 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
3525 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
3526 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
3527 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
3528 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
3529 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
3530 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
3531 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
3532 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00003533 {NULL, NULL} /* sentinel */
3534};
3535
3536static PyTypeObject PySSLContext_Type = {
3537 PyVarObject_HEAD_INIT(NULL, 0)
3538 "_ssl._SSLContext", /*tp_name*/
3539 sizeof(PySSLContext), /*tp_basicsize*/
3540 0, /*tp_itemsize*/
3541 (destructor)context_dealloc, /*tp_dealloc*/
3542 0, /*tp_print*/
3543 0, /*tp_getattr*/
3544 0, /*tp_setattr*/
3545 0, /*tp_reserved*/
3546 0, /*tp_repr*/
3547 0, /*tp_as_number*/
3548 0, /*tp_as_sequence*/
3549 0, /*tp_as_mapping*/
3550 0, /*tp_hash*/
3551 0, /*tp_call*/
3552 0, /*tp_str*/
3553 0, /*tp_getattro*/
3554 0, /*tp_setattro*/
3555 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003556 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003557 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003558 (traverseproc) context_traverse, /*tp_traverse*/
3559 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003560 0, /*tp_richcompare*/
3561 0, /*tp_weaklistoffset*/
3562 0, /*tp_iter*/
3563 0, /*tp_iternext*/
3564 context_methods, /*tp_methods*/
3565 0, /*tp_members*/
3566 context_getsetlist, /*tp_getset*/
3567 0, /*tp_base*/
3568 0, /*tp_dict*/
3569 0, /*tp_descr_get*/
3570 0, /*tp_descr_set*/
3571 0, /*tp_dictoffset*/
3572 0, /*tp_init*/
3573 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003574 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003575};
3576
3577
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003578/*
3579 * MemoryBIO objects
3580 */
3581
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003582/*[clinic input]
3583@classmethod
3584_ssl.MemoryBIO.__new__
3585
3586[clinic start generated code]*/
3587
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003588static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003589_ssl_MemoryBIO_impl(PyTypeObject *type)
3590/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003591{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003592 BIO *bio;
3593 PySSLMemoryBIO *self;
3594
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003595 bio = BIO_new(BIO_s_mem());
3596 if (bio == NULL) {
3597 PyErr_SetString(PySSLErrorObject,
3598 "failed to allocate BIO");
3599 return NULL;
3600 }
3601 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3602 * just that no data is currently available. The SSL routines should retry
3603 * the read, which we can achieve by calling BIO_set_retry_read(). */
3604 BIO_set_retry_read(bio);
3605 BIO_set_mem_eof_return(bio, -1);
3606
3607 assert(type != NULL && type->tp_alloc != NULL);
3608 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3609 if (self == NULL) {
3610 BIO_free(bio);
3611 return NULL;
3612 }
3613 self->bio = bio;
3614 self->eof_written = 0;
3615
3616 return (PyObject *) self;
3617}
3618
3619static void
3620memory_bio_dealloc(PySSLMemoryBIO *self)
3621{
3622 BIO_free(self->bio);
3623 Py_TYPE(self)->tp_free(self);
3624}
3625
3626static PyObject *
3627memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3628{
3629 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3630}
3631
3632PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3633"The number of bytes pending in the memory BIO.");
3634
3635static PyObject *
3636memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3637{
3638 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3639 && self->eof_written);
3640}
3641
3642PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3643"Whether the memory BIO is at EOF.");
3644
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003645/*[clinic input]
3646_ssl.MemoryBIO.read
3647 size as len: int = -1
3648 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003649
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003650Read up to size bytes from the memory BIO.
3651
3652If size is not specified, read the entire buffer.
3653If the return value is an empty bytes instance, this means either
3654EOF or that no data is available. Use the "eof" property to
3655distinguish between the two.
3656[clinic start generated code]*/
3657
3658static PyObject *
3659_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
3660/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
3661{
3662 int avail, nbytes;
3663 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003664
3665 avail = BIO_ctrl_pending(self->bio);
3666 if ((len < 0) || (len > avail))
3667 len = avail;
3668
3669 result = PyBytes_FromStringAndSize(NULL, len);
3670 if ((result == NULL) || (len == 0))
3671 return result;
3672
3673 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3674 /* There should never be any short reads but check anyway. */
3675 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3676 Py_DECREF(result);
3677 return NULL;
3678 }
3679
3680 return result;
3681}
3682
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003683/*[clinic input]
3684_ssl.MemoryBIO.write
3685 b: Py_buffer
3686 /
3687
3688Writes the bytes b into the memory BIO.
3689
3690Returns the number of bytes written.
3691[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003692
3693static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003694_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
3695/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003696{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003697 int nbytes;
3698
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003699 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003700 PyErr_Format(PyExc_OverflowError,
3701 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003702 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003703 }
3704
3705 if (self->eof_written) {
3706 PyErr_SetString(PySSLErrorObject,
3707 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003708 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003709 }
3710
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003711 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003712 if (nbytes < 0) {
3713 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003714 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003715 }
3716
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003717 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003718}
3719
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003720/*[clinic input]
3721_ssl.MemoryBIO.write_eof
3722
3723Write an EOF marker to the memory BIO.
3724
3725When all data has been read, the "eof" property will be True.
3726[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003727
3728static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003729_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
3730/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003731{
3732 self->eof_written = 1;
3733 /* After an EOF is written, a zero return from read() should be a real EOF
3734 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3735 BIO_clear_retry_flags(self->bio);
3736 BIO_set_mem_eof_return(self->bio, 0);
3737
3738 Py_RETURN_NONE;
3739}
3740
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003741static PyGetSetDef memory_bio_getsetlist[] = {
3742 {"pending", (getter) memory_bio_get_pending, NULL,
3743 PySSL_memory_bio_pending_doc},
3744 {"eof", (getter) memory_bio_get_eof, NULL,
3745 PySSL_memory_bio_eof_doc},
3746 {NULL}, /* sentinel */
3747};
3748
3749static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003750 _SSL_MEMORYBIO_READ_METHODDEF
3751 _SSL_MEMORYBIO_WRITE_METHODDEF
3752 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003753 {NULL, NULL} /* sentinel */
3754};
3755
3756static PyTypeObject PySSLMemoryBIO_Type = {
3757 PyVarObject_HEAD_INIT(NULL, 0)
3758 "_ssl.MemoryBIO", /*tp_name*/
3759 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3760 0, /*tp_itemsize*/
3761 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3762 0, /*tp_print*/
3763 0, /*tp_getattr*/
3764 0, /*tp_setattr*/
3765 0, /*tp_reserved*/
3766 0, /*tp_repr*/
3767 0, /*tp_as_number*/
3768 0, /*tp_as_sequence*/
3769 0, /*tp_as_mapping*/
3770 0, /*tp_hash*/
3771 0, /*tp_call*/
3772 0, /*tp_str*/
3773 0, /*tp_getattro*/
3774 0, /*tp_setattro*/
3775 0, /*tp_as_buffer*/
3776 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3777 0, /*tp_doc*/
3778 0, /*tp_traverse*/
3779 0, /*tp_clear*/
3780 0, /*tp_richcompare*/
3781 0, /*tp_weaklistoffset*/
3782 0, /*tp_iter*/
3783 0, /*tp_iternext*/
3784 memory_bio_methods, /*tp_methods*/
3785 0, /*tp_members*/
3786 memory_bio_getsetlist, /*tp_getset*/
3787 0, /*tp_base*/
3788 0, /*tp_dict*/
3789 0, /*tp_descr_get*/
3790 0, /*tp_descr_set*/
3791 0, /*tp_dictoffset*/
3792 0, /*tp_init*/
3793 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003794 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003795};
3796
Antoine Pitrou152efa22010-05-16 18:19:27 +00003797
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003798/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003799/*[clinic input]
3800_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07003801 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003802 entropy: double
3803 /
3804
3805Mix string into the OpenSSL PRNG state.
3806
3807entropy (a float) is a lower bound on the entropy contained in
3808string. See RFC 1750.
3809[clinic start generated code]*/
3810
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003811static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003812_ssl_RAND_add_impl(PyModuleDef *module, Py_buffer *view, double entropy)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07003813/*[clinic end generated code: output=0f8d5c8cce328958 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003814{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02003815 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003816 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003817
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003818 buf = (const char *)view->buf;
3819 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003820 do {
3821 written = Py_MIN(len, INT_MAX);
3822 RAND_add(buf, (int)written, entropy);
3823 buf += written;
3824 len -= written;
3825 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003826 Py_INCREF(Py_None);
3827 return Py_None;
3828}
3829
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003830static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003831PySSL_RAND(int len, int pseudo)
3832{
3833 int ok;
3834 PyObject *bytes;
3835 unsigned long err;
3836 const char *errstr;
3837 PyObject *v;
3838
Victor Stinner1e81a392013-12-19 16:47:04 +01003839 if (len < 0) {
3840 PyErr_SetString(PyExc_ValueError, "num must be positive");
3841 return NULL;
3842 }
3843
Victor Stinner99c8b162011-05-24 12:05:19 +02003844 bytes = PyBytes_FromStringAndSize(NULL, len);
3845 if (bytes == NULL)
3846 return NULL;
3847 if (pseudo) {
3848 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3849 if (ok == 0 || ok == 1)
3850 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3851 }
3852 else {
3853 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3854 if (ok == 1)
3855 return bytes;
3856 }
3857 Py_DECREF(bytes);
3858
3859 err = ERR_get_error();
3860 errstr = ERR_reason_error_string(err);
3861 v = Py_BuildValue("(ks)", err, errstr);
3862 if (v != NULL) {
3863 PyErr_SetObject(PySSLErrorObject, v);
3864 Py_DECREF(v);
3865 }
3866 return NULL;
3867}
3868
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003869/*[clinic input]
3870_ssl.RAND_bytes
3871 n: int
3872 /
3873
3874Generate n cryptographically strong pseudo-random bytes.
3875[clinic start generated code]*/
3876
Victor Stinner99c8b162011-05-24 12:05:19 +02003877static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003878_ssl_RAND_bytes_impl(PyModuleDef *module, int n)
3879/*[clinic end generated code: output=7d8741bdc1d435f3 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003880{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003881 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02003882}
3883
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003884/*[clinic input]
3885_ssl.RAND_pseudo_bytes
3886 n: int
3887 /
3888
3889Generate n pseudo-random bytes.
3890
3891Return a pair (bytes, is_cryptographic). is_cryptographic is True
3892if the bytes generated are cryptographically strong.
3893[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003894
3895static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003896_ssl_RAND_pseudo_bytes_impl(PyModuleDef *module, int n)
3897/*[clinic end generated code: output=dd673813107f3875 input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003898{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003899 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02003900}
3901
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003902/*[clinic input]
3903_ssl.RAND_status
3904
3905Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
3906
3907It is necessary to seed the PRNG with RAND_add() on some platforms before
3908using the ssl() function.
3909[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003910
3911static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003912_ssl_RAND_status_impl(PyModuleDef *module)
3913/*[clinic end generated code: output=7f7ef57bc7dd1d1c input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003914{
Christian Heimes217cfd12007-12-02 14:31:20 +00003915 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003916}
3917
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003918#ifdef HAVE_RAND_EGD
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003919/*[clinic input]
3920_ssl.RAND_egd
3921 path: object(converter="PyUnicode_FSConverter")
3922 /
3923
3924Queries the entropy gather daemon (EGD) on the socket named by 'path'.
3925
3926Returns number of bytes read. Raises SSLError if connection to EGD
3927fails or if it does not provide enough data to seed PRNG.
3928[clinic start generated code]*/
3929
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003930static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003931_ssl_RAND_egd_impl(PyModuleDef *module, PyObject *path)
3932/*[clinic end generated code: output=8e728e501e28541b input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003933{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003934 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003935 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003936 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003937 PyErr_SetString(PySSLErrorObject,
3938 "EGD connection failed or EGD did not return "
3939 "enough data to seed the PRNG");
3940 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003941 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003942 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003943}
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003944#endif /* HAVE_RAND_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003945
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003946
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003947
3948/*[clinic input]
3949_ssl.get_default_verify_paths
3950
3951Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
3952
3953The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
3954[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02003955
3956static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003957_ssl_get_default_verify_paths_impl(PyModuleDef *module)
3958/*[clinic end generated code: output=5a2820ce7e3304d3 input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02003959{
3960 PyObject *ofile_env = NULL;
3961 PyObject *ofile = NULL;
3962 PyObject *odir_env = NULL;
3963 PyObject *odir = NULL;
3964
Benjamin Petersond113c962015-07-18 10:59:13 -07003965#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02003966 const char *tmp = (info); \
3967 target = NULL; \
3968 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3969 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3970 target = PyBytes_FromString(tmp); } \
3971 if (!target) goto error; \
Benjamin Petersond113c962015-07-18 10:59:13 -07003972 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02003973
Benjamin Petersond113c962015-07-18 10:59:13 -07003974 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3975 CONVERT(X509_get_default_cert_file(), ofile);
3976 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3977 CONVERT(X509_get_default_cert_dir(), odir);
3978#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02003979
Christian Heimes200bb1b2013-06-14 15:14:29 +02003980 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003981
3982 error:
3983 Py_XDECREF(ofile_env);
3984 Py_XDECREF(ofile);
3985 Py_XDECREF(odir_env);
3986 Py_XDECREF(odir);
3987 return NULL;
3988}
3989
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003990static PyObject*
3991asn1obj2py(ASN1_OBJECT *obj)
3992{
3993 int nid;
3994 const char *ln, *sn;
3995 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02003996 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003997
3998 nid = OBJ_obj2nid(obj);
3999 if (nid == NID_undef) {
4000 PyErr_Format(PyExc_ValueError, "Unknown object");
4001 return NULL;
4002 }
4003 sn = OBJ_nid2sn(nid);
4004 ln = OBJ_nid2ln(nid);
4005 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4006 if (buflen < 0) {
4007 _setSSLError(NULL, 0, __FILE__, __LINE__);
4008 return NULL;
4009 }
4010 if (buflen) {
4011 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4012 } else {
4013 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4014 }
4015}
4016
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004017/*[clinic input]
4018_ssl.txt2obj
4019 txt: str
4020 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004021
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004022Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4023
4024By default objects are looked up by OID. With name=True short and
4025long name are also matched.
4026[clinic start generated code]*/
4027
4028static PyObject *
4029_ssl_txt2obj_impl(PyModuleDef *module, const char *txt, int name)
4030/*[clinic end generated code: output=2ae2c30531b8809f input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004031{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004032 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004033 ASN1_OBJECT *obj;
4034
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004035 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4036 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004037 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004038 return NULL;
4039 }
4040 result = asn1obj2py(obj);
4041 ASN1_OBJECT_free(obj);
4042 return result;
4043}
4044
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004045/*[clinic input]
4046_ssl.nid2obj
4047 nid: int
4048 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004049
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004050Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4051[clinic start generated code]*/
4052
4053static PyObject *
4054_ssl_nid2obj_impl(PyModuleDef *module, int nid)
4055/*[clinic end generated code: output=8db1df89e44badb8 input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004056{
4057 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004058 ASN1_OBJECT *obj;
4059
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004060 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004061 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004062 return NULL;
4063 }
4064 obj = OBJ_nid2obj(nid);
4065 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004066 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004067 return NULL;
4068 }
4069 result = asn1obj2py(obj);
4070 ASN1_OBJECT_free(obj);
4071 return result;
4072}
4073
Christian Heimes46bebee2013-06-09 19:03:31 +02004074#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004075
4076static PyObject*
4077certEncodingType(DWORD encodingType)
4078{
4079 static PyObject *x509_asn = NULL;
4080 static PyObject *pkcs_7_asn = NULL;
4081
4082 if (x509_asn == NULL) {
4083 x509_asn = PyUnicode_InternFromString("x509_asn");
4084 if (x509_asn == NULL)
4085 return NULL;
4086 }
4087 if (pkcs_7_asn == NULL) {
4088 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4089 if (pkcs_7_asn == NULL)
4090 return NULL;
4091 }
4092 switch(encodingType) {
4093 case X509_ASN_ENCODING:
4094 Py_INCREF(x509_asn);
4095 return x509_asn;
4096 case PKCS_7_ASN_ENCODING:
4097 Py_INCREF(pkcs_7_asn);
4098 return pkcs_7_asn;
4099 default:
4100 return PyLong_FromLong(encodingType);
4101 }
4102}
4103
4104static PyObject*
4105parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4106{
4107 CERT_ENHKEY_USAGE *usage;
4108 DWORD size, error, i;
4109 PyObject *retval;
4110
4111 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4112 error = GetLastError();
4113 if (error == CRYPT_E_NOT_FOUND) {
4114 Py_RETURN_TRUE;
4115 }
4116 return PyErr_SetFromWindowsErr(error);
4117 }
4118
4119 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4120 if (usage == NULL) {
4121 return PyErr_NoMemory();
4122 }
4123
4124 /* Now get the actual enhanced usage property */
4125 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4126 PyMem_Free(usage);
4127 error = GetLastError();
4128 if (error == CRYPT_E_NOT_FOUND) {
4129 Py_RETURN_TRUE;
4130 }
4131 return PyErr_SetFromWindowsErr(error);
4132 }
4133 retval = PySet_New(NULL);
4134 if (retval == NULL) {
4135 goto error;
4136 }
4137 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4138 if (usage->rgpszUsageIdentifier[i]) {
4139 PyObject *oid;
4140 int err;
4141 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4142 if (oid == NULL) {
4143 Py_CLEAR(retval);
4144 goto error;
4145 }
4146 err = PySet_Add(retval, oid);
4147 Py_DECREF(oid);
4148 if (err == -1) {
4149 Py_CLEAR(retval);
4150 goto error;
4151 }
4152 }
4153 }
4154 error:
4155 PyMem_Free(usage);
4156 return retval;
4157}
4158
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004159/*[clinic input]
4160_ssl.enum_certificates
4161 store_name: str
4162
4163Retrieve certificates from Windows' cert store.
4164
4165store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4166more cert storages, too. The function returns a list of (bytes,
4167encoding_type, trust) tuples. The encoding_type flag can be interpreted
4168with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4169a set of OIDs or the boolean True.
4170[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004171
Christian Heimes46bebee2013-06-09 19:03:31 +02004172static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004173_ssl_enum_certificates_impl(PyModuleDef *module, const char *store_name)
4174/*[clinic end generated code: output=cc4ebc10b8adacfc input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004175{
Christian Heimes46bebee2013-06-09 19:03:31 +02004176 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004177 PCCERT_CONTEXT pCertCtx = NULL;
4178 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004179 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004180
Christian Heimes44109d72013-11-22 01:51:30 +01004181 result = PyList_New(0);
4182 if (result == NULL) {
4183 return NULL;
4184 }
4185 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4186 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004187 Py_DECREF(result);
4188 return PyErr_SetFromWindowsErr(GetLastError());
4189 }
4190
Christian Heimes44109d72013-11-22 01:51:30 +01004191 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4192 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4193 pCertCtx->cbCertEncoded);
4194 if (!cert) {
4195 Py_CLEAR(result);
4196 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004197 }
Christian Heimes44109d72013-11-22 01:51:30 +01004198 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4199 Py_CLEAR(result);
4200 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004201 }
Christian Heimes44109d72013-11-22 01:51:30 +01004202 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4203 if (keyusage == Py_True) {
4204 Py_DECREF(keyusage);
4205 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004206 }
Christian Heimes44109d72013-11-22 01:51:30 +01004207 if (keyusage == NULL) {
4208 Py_CLEAR(result);
4209 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004210 }
Christian Heimes44109d72013-11-22 01:51:30 +01004211 if ((tup = PyTuple_New(3)) == NULL) {
4212 Py_CLEAR(result);
4213 break;
4214 }
4215 PyTuple_SET_ITEM(tup, 0, cert);
4216 cert = NULL;
4217 PyTuple_SET_ITEM(tup, 1, enc);
4218 enc = NULL;
4219 PyTuple_SET_ITEM(tup, 2, keyusage);
4220 keyusage = NULL;
4221 if (PyList_Append(result, tup) < 0) {
4222 Py_CLEAR(result);
4223 break;
4224 }
4225 Py_CLEAR(tup);
4226 }
4227 if (pCertCtx) {
4228 /* loop ended with an error, need to clean up context manually */
4229 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004230 }
4231
4232 /* In error cases cert, enc and tup may not be NULL */
4233 Py_XDECREF(cert);
4234 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004235 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004236 Py_XDECREF(tup);
4237
4238 if (!CertCloseStore(hStore, 0)) {
4239 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004240 Py_XDECREF(result);
4241 return PyErr_SetFromWindowsErr(GetLastError());
4242 }
4243 return result;
4244}
4245
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004246/*[clinic input]
4247_ssl.enum_crls
4248 store_name: str
4249
4250Retrieve CRLs from Windows' cert store.
4251
4252store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4253more cert storages, too. The function returns a list of (bytes,
4254encoding_type) tuples. The encoding_type flag can be interpreted with
4255X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4256[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004257
4258static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004259_ssl_enum_crls_impl(PyModuleDef *module, const char *store_name)
4260/*[clinic end generated code: output=763490a2aa1c50d5 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004261{
Christian Heimes44109d72013-11-22 01:51:30 +01004262 HCERTSTORE hStore = NULL;
4263 PCCRL_CONTEXT pCrlCtx = NULL;
4264 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4265 PyObject *result = NULL;
4266
Christian Heimes44109d72013-11-22 01:51:30 +01004267 result = PyList_New(0);
4268 if (result == NULL) {
4269 return NULL;
4270 }
4271 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4272 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004273 Py_DECREF(result);
4274 return PyErr_SetFromWindowsErr(GetLastError());
4275 }
Christian Heimes44109d72013-11-22 01:51:30 +01004276
4277 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4278 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4279 pCrlCtx->cbCrlEncoded);
4280 if (!crl) {
4281 Py_CLEAR(result);
4282 break;
4283 }
4284 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4285 Py_CLEAR(result);
4286 break;
4287 }
4288 if ((tup = PyTuple_New(2)) == NULL) {
4289 Py_CLEAR(result);
4290 break;
4291 }
4292 PyTuple_SET_ITEM(tup, 0, crl);
4293 crl = NULL;
4294 PyTuple_SET_ITEM(tup, 1, enc);
4295 enc = NULL;
4296
4297 if (PyList_Append(result, tup) < 0) {
4298 Py_CLEAR(result);
4299 break;
4300 }
4301 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004302 }
Christian Heimes44109d72013-11-22 01:51:30 +01004303 if (pCrlCtx) {
4304 /* loop ended with an error, need to clean up context manually */
4305 CertFreeCRLContext(pCrlCtx);
4306 }
4307
4308 /* In error cases cert, enc and tup may not be NULL */
4309 Py_XDECREF(crl);
4310 Py_XDECREF(enc);
4311 Py_XDECREF(tup);
4312
4313 if (!CertCloseStore(hStore, 0)) {
4314 /* This error case might shadow another exception.*/
4315 Py_XDECREF(result);
4316 return PyErr_SetFromWindowsErr(GetLastError());
4317 }
4318 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004319}
Christian Heimes44109d72013-11-22 01:51:30 +01004320
4321#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004322
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004323/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004324static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004325 _SSL__TEST_DECODE_CERT_METHODDEF
4326 _SSL_RAND_ADD_METHODDEF
4327 _SSL_RAND_BYTES_METHODDEF
4328 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4329 _SSL_RAND_EGD_METHODDEF
4330 _SSL_RAND_STATUS_METHODDEF
4331 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
4332 _SSL_ENUM_CERTIFICATES_METHODDEF
4333 _SSL_ENUM_CRLS_METHODDEF
4334 _SSL_TXT2OBJ_METHODDEF
4335 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004336 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004337};
4338
4339
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004340#ifdef WITH_THREAD
4341
4342/* an implementation of OpenSSL threading operations in terms
4343 of the Python C thread library */
4344
4345static PyThread_type_lock *_ssl_locks = NULL;
4346
Christian Heimes4d98ca92013-08-19 17:36:29 +02004347#if OPENSSL_VERSION_NUMBER >= 0x10000000
4348/* use new CRYPTO_THREADID API. */
4349static void
4350_ssl_threadid_callback(CRYPTO_THREADID *id)
4351{
4352 CRYPTO_THREADID_set_numeric(id,
4353 (unsigned long)PyThread_get_thread_ident());
4354}
4355#else
4356/* deprecated CRYPTO_set_id_callback() API. */
4357static unsigned long
4358_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004359 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004360}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004361#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004362
Bill Janssen6e027db2007-11-15 22:23:56 +00004363static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004364 (int mode, int n, const char *file, int line) {
4365 /* this function is needed to perform locking on shared data
4366 structures. (Note that OpenSSL uses a number of global data
4367 structures that will be implicitly shared whenever multiple
4368 threads use OpenSSL.) Multi-threaded applications will
4369 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004370
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004371 locking_function() must be able to handle up to
4372 CRYPTO_num_locks() different mutex locks. It sets the n-th
4373 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004374
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004375 file and line are the file number of the function setting the
4376 lock. They can be useful for debugging.
4377 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004378
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004379 if ((_ssl_locks == NULL) ||
4380 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4381 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004382
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004383 if (mode & CRYPTO_LOCK) {
4384 PyThread_acquire_lock(_ssl_locks[n], 1);
4385 } else {
4386 PyThread_release_lock(_ssl_locks[n]);
4387 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004388}
4389
4390static int _setup_ssl_threads(void) {
4391
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004392 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004393
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004394 if (_ssl_locks == NULL) {
4395 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004396 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4397 if (_ssl_locks == NULL) {
4398 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004399 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004400 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004401 memset(_ssl_locks, 0,
4402 sizeof(PyThread_type_lock) * _ssl_locks_count);
4403 for (i = 0; i < _ssl_locks_count; i++) {
4404 _ssl_locks[i] = PyThread_allocate_lock();
4405 if (_ssl_locks[i] == NULL) {
4406 unsigned int j;
4407 for (j = 0; j < i; j++) {
4408 PyThread_free_lock(_ssl_locks[j]);
4409 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004410 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004411 return 0;
4412 }
4413 }
4414 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004415#if OPENSSL_VERSION_NUMBER >= 0x10000000
4416 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4417#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004418 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004419#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004420 }
4421 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004422}
4423
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004424#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004425
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004426PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004427"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004428for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004429
Martin v. Löwis1a214512008-06-11 05:26:20 +00004430
4431static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004432 PyModuleDef_HEAD_INIT,
4433 "_ssl",
4434 module_doc,
4435 -1,
4436 PySSL_methods,
4437 NULL,
4438 NULL,
4439 NULL,
4440 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004441};
4442
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004443
4444static void
4445parse_openssl_version(unsigned long libver,
4446 unsigned int *major, unsigned int *minor,
4447 unsigned int *fix, unsigned int *patch,
4448 unsigned int *status)
4449{
4450 *status = libver & 0xF;
4451 libver >>= 4;
4452 *patch = libver & 0xFF;
4453 libver >>= 8;
4454 *fix = libver & 0xFF;
4455 libver >>= 8;
4456 *minor = libver & 0xFF;
4457 libver >>= 8;
4458 *major = libver & 0xFF;
4459}
4460
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004461PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004462PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004463{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004464 PyObject *m, *d, *r;
4465 unsigned long libver;
4466 unsigned int major, minor, fix, patch, status;
4467 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004468 struct py_ssl_error_code *errcode;
4469 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004470
Antoine Pitrou152efa22010-05-16 18:19:27 +00004471 if (PyType_Ready(&PySSLContext_Type) < 0)
4472 return NULL;
4473 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004474 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004475 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4476 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004477
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004478 m = PyModule_Create(&_sslmodule);
4479 if (m == NULL)
4480 return NULL;
4481 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004482
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004483 /* Load _socket module and its C API */
4484 socket_api = PySocketModule_ImportModuleAndAPI();
4485 if (!socket_api)
4486 return NULL;
4487 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004488
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004489 /* Init OpenSSL */
4490 SSL_load_error_strings();
4491 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004492#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004493 /* note that this will start threading if not already started */
4494 if (!_setup_ssl_threads()) {
4495 return NULL;
4496 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004497#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004498 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004499
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004500 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004501 sslerror_type_slots[0].pfunc = PyExc_OSError;
4502 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004503 if (PySSLErrorObject == NULL)
4504 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004505
Antoine Pitrou41032a62011-10-27 23:56:55 +02004506 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4507 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4508 PySSLErrorObject, NULL);
4509 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4510 "ssl.SSLWantReadError", SSLWantReadError_doc,
4511 PySSLErrorObject, NULL);
4512 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4513 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4514 PySSLErrorObject, NULL);
4515 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4516 "ssl.SSLSyscallError", SSLSyscallError_doc,
4517 PySSLErrorObject, NULL);
4518 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4519 "ssl.SSLEOFError", SSLEOFError_doc,
4520 PySSLErrorObject, NULL);
4521 if (PySSLZeroReturnErrorObject == NULL
4522 || PySSLWantReadErrorObject == NULL
4523 || PySSLWantWriteErrorObject == NULL
4524 || PySSLSyscallErrorObject == NULL
4525 || PySSLEOFErrorObject == NULL)
4526 return NULL;
4527 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4528 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4529 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4530 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4531 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4532 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004533 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004534 if (PyDict_SetItemString(d, "_SSLContext",
4535 (PyObject *)&PySSLContext_Type) != 0)
4536 return NULL;
4537 if (PyDict_SetItemString(d, "_SSLSocket",
4538 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004539 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004540 if (PyDict_SetItemString(d, "MemoryBIO",
4541 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4542 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004543 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4544 PY_SSL_ERROR_ZERO_RETURN);
4545 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4546 PY_SSL_ERROR_WANT_READ);
4547 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4548 PY_SSL_ERROR_WANT_WRITE);
4549 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4550 PY_SSL_ERROR_WANT_X509_LOOKUP);
4551 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4552 PY_SSL_ERROR_SYSCALL);
4553 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4554 PY_SSL_ERROR_SSL);
4555 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4556 PY_SSL_ERROR_WANT_CONNECT);
4557 /* non ssl.h errorcodes */
4558 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4559 PY_SSL_ERROR_EOF);
4560 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4561 PY_SSL_ERROR_INVALID_ERROR_CODE);
4562 /* cert requirements */
4563 PyModule_AddIntConstant(m, "CERT_NONE",
4564 PY_SSL_CERT_NONE);
4565 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4566 PY_SSL_CERT_OPTIONAL);
4567 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4568 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004569 /* CRL verification for verification_flags */
4570 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4571 0);
4572 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4573 X509_V_FLAG_CRL_CHECK);
4574 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4575 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4576 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4577 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05004578#ifdef X509_V_FLAG_TRUSTED_FIRST
4579 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4580 X509_V_FLAG_TRUSTED_FIRST);
4581#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004582
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004583 /* Alert Descriptions from ssl.h */
4584 /* note RESERVED constants no longer intended for use have been removed */
4585 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4586
4587#define ADD_AD_CONSTANT(s) \
4588 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4589 SSL_AD_##s)
4590
4591 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4592 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4593 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4594 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4595 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4596 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4597 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4598 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4599 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4600 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4601 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4602 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4603 ADD_AD_CONSTANT(UNKNOWN_CA);
4604 ADD_AD_CONSTANT(ACCESS_DENIED);
4605 ADD_AD_CONSTANT(DECODE_ERROR);
4606 ADD_AD_CONSTANT(DECRYPT_ERROR);
4607 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4608 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4609 ADD_AD_CONSTANT(INTERNAL_ERROR);
4610 ADD_AD_CONSTANT(USER_CANCELLED);
4611 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004612 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004613#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4614 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4615#endif
4616#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4617 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4618#endif
4619#ifdef SSL_AD_UNRECOGNIZED_NAME
4620 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4621#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004622#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4623 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4624#endif
4625#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4626 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4627#endif
4628#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4629 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4630#endif
4631
4632#undef ADD_AD_CONSTANT
4633
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004634 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004635#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004636 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4637 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004638#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004639#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004640 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4641 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004642#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004643 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4644 PY_SSL_VERSION_SSL23);
4645 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4646 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004647#if HAVE_TLSv1_2
4648 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4649 PY_SSL_VERSION_TLS1_1);
4650 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4651 PY_SSL_VERSION_TLS1_2);
4652#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004653
Antoine Pitroub5218772010-05-21 09:56:06 +00004654 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004655 PyModule_AddIntConstant(m, "OP_ALL",
4656 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004657 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4658 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4659 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004660#if HAVE_TLSv1_2
4661 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4662 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4663#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004664 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4665 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004666 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004667#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004668 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004669#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004670#ifdef SSL_OP_NO_COMPRESSION
4671 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4672 SSL_OP_NO_COMPRESSION);
4673#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004674
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004675#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004676 r = Py_True;
4677#else
4678 r = Py_False;
4679#endif
4680 Py_INCREF(r);
4681 PyModule_AddObject(m, "HAS_SNI", r);
4682
Antoine Pitroud6494802011-07-21 01:11:30 +02004683 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004684 Py_INCREF(r);
4685 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4686
Antoine Pitrou501da612011-12-21 09:27:41 +01004687#ifdef OPENSSL_NO_ECDH
4688 r = Py_False;
4689#else
4690 r = Py_True;
4691#endif
4692 Py_INCREF(r);
4693 PyModule_AddObject(m, "HAS_ECDH", r);
4694
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004695#ifdef OPENSSL_NPN_NEGOTIATED
4696 r = Py_True;
4697#else
4698 r = Py_False;
4699#endif
4700 Py_INCREF(r);
4701 PyModule_AddObject(m, "HAS_NPN", r);
4702
Benjamin Petersoncca27322015-01-23 16:35:37 -05004703#ifdef HAVE_ALPN
4704 r = Py_True;
4705#else
4706 r = Py_False;
4707#endif
4708 Py_INCREF(r);
4709 PyModule_AddObject(m, "HAS_ALPN", r);
4710
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004711 /* Mappings for error codes */
4712 err_codes_to_names = PyDict_New();
4713 err_names_to_codes = PyDict_New();
4714 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4715 return NULL;
4716 errcode = error_codes;
4717 while (errcode->mnemonic != NULL) {
4718 PyObject *mnemo, *key;
4719 mnemo = PyUnicode_FromString(errcode->mnemonic);
4720 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4721 if (mnemo == NULL || key == NULL)
4722 return NULL;
4723 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4724 return NULL;
4725 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4726 return NULL;
4727 Py_DECREF(key);
4728 Py_DECREF(mnemo);
4729 errcode++;
4730 }
4731 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4732 return NULL;
4733 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4734 return NULL;
4735
4736 lib_codes_to_names = PyDict_New();
4737 if (lib_codes_to_names == NULL)
4738 return NULL;
4739 libcode = library_codes;
4740 while (libcode->library != NULL) {
4741 PyObject *mnemo, *key;
4742 key = PyLong_FromLong(libcode->code);
4743 mnemo = PyUnicode_FromString(libcode->library);
4744 if (key == NULL || mnemo == NULL)
4745 return NULL;
4746 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4747 return NULL;
4748 Py_DECREF(key);
4749 Py_DECREF(mnemo);
4750 libcode++;
4751 }
4752 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4753 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004754
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004755 /* OpenSSL version */
4756 /* SSLeay() gives us the version of the library linked against,
4757 which could be different from the headers version.
4758 */
4759 libver = SSLeay();
4760 r = PyLong_FromUnsignedLong(libver);
4761 if (r == NULL)
4762 return NULL;
4763 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4764 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004765 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004766 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4767 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4768 return NULL;
4769 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4770 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4771 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004772
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004773 libver = OPENSSL_VERSION_NUMBER;
4774 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4775 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4776 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4777 return NULL;
4778
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004779 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004780}