blob: e2c43869b7d2ec1503ae3f7dd944f40bba88966b [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
Victor Stinner524714e2016-07-22 17:43:59 +0200116#ifndef INVALID_SOCKET /* MS defines this */
117#define INVALID_SOCKET (-1)
118#endif
119
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000120enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000121 /* these mirror ssl.h */
122 PY_SSL_ERROR_NONE,
123 PY_SSL_ERROR_SSL,
124 PY_SSL_ERROR_WANT_READ,
125 PY_SSL_ERROR_WANT_WRITE,
126 PY_SSL_ERROR_WANT_X509_LOOKUP,
127 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
128 PY_SSL_ERROR_ZERO_RETURN,
129 PY_SSL_ERROR_WANT_CONNECT,
130 /* start of non ssl.h errorcodes */
131 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
132 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
133 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000134};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000135
Thomas Woutersed03b412007-08-28 21:37:11 +0000136enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000137 PY_SSL_CLIENT,
138 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000139};
140
141enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000142 PY_SSL_CERT_NONE,
143 PY_SSL_CERT_OPTIONAL,
144 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000145};
146
147enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000148 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200149 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000150 PY_SSL_VERSION_SSL23,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100151#if HAVE_TLSv1_2
152 PY_SSL_VERSION_TLS1,
153 PY_SSL_VERSION_TLS1_1,
154 PY_SSL_VERSION_TLS1_2
155#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000156 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000157#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100158};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200159
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000160#ifdef WITH_THREAD
161
162/* serves as a flag to see whether we've initialized the SSL thread support. */
163/* 0 means no, greater than 0 means yes */
164
165static unsigned int _ssl_locks_count = 0;
166
167#endif /* def WITH_THREAD */
168
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000169/* SSL socket object */
170
171#define X509_NAME_MAXLEN 256
172
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000173/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
174 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
175 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
176#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000177# define HAVE_SSL_CTX_CLEAR_OPTIONS
178#else
179# undef HAVE_SSL_CTX_CLEAR_OPTIONS
180#endif
181
Antoine Pitroud6494802011-07-21 01:11:30 +0200182/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
183 * older SSL, but let's be safe */
184#define PySSL_CB_MAXLEN 128
185
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100186
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000187typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000188 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000189 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100190#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -0500191 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100192 int npn_protocols_len;
193#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500194#ifdef HAVE_ALPN
195 unsigned char *alpn_protocols;
196 int alpn_protocols_len;
197#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100198#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200199 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100200#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100201 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000202} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000203
Antoine Pitrou152efa22010-05-16 18:19:27 +0000204typedef struct {
205 PyObject_HEAD
206 PyObject *Socket; /* weakref to socket on which we're layered */
207 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100208 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000209 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200210 char shutdown_seen_zero;
211 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200212 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200213 PyObject *owner; /* Python level "owner" passed to servername callback */
214 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000215} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000216
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200217typedef struct {
218 PyObject_HEAD
219 BIO *bio;
220 int eof_written;
221} PySSLMemoryBIO;
222
Antoine Pitrou152efa22010-05-16 18:19:27 +0000223static PyTypeObject PySSLContext_Type;
224static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200225static PyTypeObject PySSLMemoryBIO_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000226
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300227/*[clinic input]
228module _ssl
229class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
230class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
231class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
232[clinic start generated code]*/
233/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7bf7cb832638e2e1]*/
234
235#include "clinic/_ssl.c.h"
236
Victor Stinner14690702015-04-06 22:46:13 +0200237static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000238
Antoine Pitrou152efa22010-05-16 18:19:27 +0000239#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
240#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200241#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000242
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000243typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000244 SOCKET_IS_NONBLOCKING,
245 SOCKET_IS_BLOCKING,
246 SOCKET_HAS_TIMED_OUT,
247 SOCKET_HAS_BEEN_CLOSED,
248 SOCKET_TOO_LARGE_FOR_SELECT,
249 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000250} timeout_state;
251
Thomas Woutersed03b412007-08-28 21:37:11 +0000252/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000253#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200254#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000255
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200256/* Get the socket from a PySSLSocket, if it has one */
257#define GET_SOCKET(obj) ((obj)->Socket ? \
258 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200259
Victor Stinner14690702015-04-06 22:46:13 +0200260/* If sock is NULL, use a timeout of 0 second */
261#define GET_SOCKET_TIMEOUT(sock) \
262 ((sock != NULL) ? (sock)->sock_timeout : 0)
263
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200264/*
265 * SSL errors.
266 */
267
268PyDoc_STRVAR(SSLError_doc,
269"An error occurred in the SSL implementation.");
270
271PyDoc_STRVAR(SSLZeroReturnError_doc,
272"SSL/TLS session closed cleanly.");
273
274PyDoc_STRVAR(SSLWantReadError_doc,
275"Non-blocking SSL socket needs to read more data\n"
276"before the requested operation can be completed.");
277
278PyDoc_STRVAR(SSLWantWriteError_doc,
279"Non-blocking SSL socket needs to write more data\n"
280"before the requested operation can be completed.");
281
282PyDoc_STRVAR(SSLSyscallError_doc,
283"System error when attempting SSL operation.");
284
285PyDoc_STRVAR(SSLEOFError_doc,
286"SSL/TLS connection terminated abruptly.");
287
288static PyObject *
289SSLError_str(PyOSErrorObject *self)
290{
291 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
292 Py_INCREF(self->strerror);
293 return self->strerror;
294 }
295 else
296 return PyObject_Str(self->args);
297}
298
299static PyType_Slot sslerror_type_slots[] = {
300 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
301 {Py_tp_doc, SSLError_doc},
302 {Py_tp_str, SSLError_str},
303 {0, 0},
304};
305
306static PyType_Spec sslerror_type_spec = {
307 "ssl.SSLError",
308 sizeof(PyOSErrorObject),
309 0,
310 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
311 sslerror_type_slots
312};
313
314static void
315fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
316 int lineno, unsigned long errcode)
317{
318 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
319 PyObject *init_value, *msg, *key;
320 _Py_IDENTIFIER(reason);
321 _Py_IDENTIFIER(library);
322
323 if (errcode != 0) {
324 int lib, reason;
325
326 lib = ERR_GET_LIB(errcode);
327 reason = ERR_GET_REASON(errcode);
328 key = Py_BuildValue("ii", lib, reason);
329 if (key == NULL)
330 goto fail;
331 reason_obj = PyDict_GetItem(err_codes_to_names, key);
332 Py_DECREF(key);
333 if (reason_obj == NULL) {
334 /* XXX if reason < 100, it might reflect a library number (!!) */
335 PyErr_Clear();
336 }
337 key = PyLong_FromLong(lib);
338 if (key == NULL)
339 goto fail;
340 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
341 Py_DECREF(key);
342 if (lib_obj == NULL) {
343 PyErr_Clear();
344 }
345 if (errstr == NULL)
346 errstr = ERR_reason_error_string(errcode);
347 }
348 if (errstr == NULL)
349 errstr = "unknown error";
350
351 if (reason_obj && lib_obj)
352 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
353 lib_obj, reason_obj, errstr, lineno);
354 else if (lib_obj)
355 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
356 lib_obj, errstr, lineno);
357 else
358 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200359 if (msg == NULL)
360 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100361
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200362 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100363 if (init_value == NULL)
364 goto fail;
365
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200366 err_value = PyObject_CallObject(type, init_value);
367 Py_DECREF(init_value);
368 if (err_value == NULL)
369 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100370
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200371 if (reason_obj == NULL)
372 reason_obj = Py_None;
373 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
374 goto fail;
375 if (lib_obj == NULL)
376 lib_obj = Py_None;
377 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
378 goto fail;
379 PyErr_SetObject(type, err_value);
380fail:
381 Py_XDECREF(err_value);
382}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000383
384static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200385PySSL_SetError(PySSLSocket *obj, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000386{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200387 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200388 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000389 int err;
390 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200391 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000392
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000393 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200394 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000395
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000396 if (obj->ssl != NULL) {
397 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000398
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000399 switch (err) {
400 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200401 errstr = "TLS/SSL connection has been closed (EOF)";
402 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000403 p = PY_SSL_ERROR_ZERO_RETURN;
404 break;
405 case SSL_ERROR_WANT_READ:
406 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200407 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000408 p = PY_SSL_ERROR_WANT_READ;
409 break;
410 case SSL_ERROR_WANT_WRITE:
411 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200412 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000413 errstr = "The operation did not complete (write)";
414 break;
415 case SSL_ERROR_WANT_X509_LOOKUP:
416 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000417 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000418 break;
419 case SSL_ERROR_WANT_CONNECT:
420 p = PY_SSL_ERROR_WANT_CONNECT;
421 errstr = "The operation did not complete (connect)";
422 break;
423 case SSL_ERROR_SYSCALL:
424 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000425 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200426 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000427 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000428 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200429 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000430 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200431 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000432 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000433 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000434 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200435 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000436 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200437 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000438 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000439 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200440 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000441 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000442 }
443 } else {
444 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000445 }
446 break;
447 }
448 case SSL_ERROR_SSL:
449 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000450 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200451 if (e == 0)
452 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000453 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000454 break;
455 }
456 default:
457 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
458 errstr = "Invalid error code";
459 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000460 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200461 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000462 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000463 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000464}
465
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000466static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200467_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000468
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200469 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000470 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200471 else
472 errcode = 0;
473 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000474 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000475 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000476}
477
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200478/*
479 * SSL objects
480 */
481
Antoine Pitrou152efa22010-05-16 18:19:27 +0000482static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100483newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000484 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200485 char *server_hostname,
486 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000487{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000488 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100489 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200490 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000491
Antoine Pitrou152efa22010-05-16 18:19:27 +0000492 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000493 if (self == NULL)
494 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000495
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000496 self->peer_cert = NULL;
497 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000498 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100499 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200500 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200501 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200502 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700503 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200504 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700505 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
506 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200507 if (hostname == NULL) {
508 Py_DECREF(self);
509 return NULL;
510 }
511 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700512 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200513
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100514 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000515
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000516 /* Make sure the SSL error state is initialized */
517 (void) ERR_get_state();
518 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000519
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000520 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000521 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000522 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200523 SSL_set_app_data(self->ssl, self);
524 if (sock) {
525 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
526 } else {
527 /* BIOs are reference counted and SSL_set_bio borrows our reference.
528 * To prevent a double free in memory_bio_dealloc() we need to take an
529 * extra reference here. */
530 CRYPTO_add(&inbio->bio->references, 1, CRYPTO_LOCK_BIO);
531 CRYPTO_add(&outbio->bio->references, 1, CRYPTO_LOCK_BIO);
532 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
533 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200534 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000535#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200536 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000537#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200538 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000539
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100540#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000541 if (server_hostname != NULL)
542 SSL_set_tlsext_host_name(self->ssl, server_hostname);
543#endif
544
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000545 /* If the socket is in non-blocking mode or timeout mode, set the BIO
546 * to non-blocking mode (blocking is the default)
547 */
Victor Stinnere2452312015-03-28 03:00:46 +0100548 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000549 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
550 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
551 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000552
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000553 PySSL_BEGIN_ALLOW_THREADS
554 if (socket_type == PY_SSL_CLIENT)
555 SSL_set_connect_state(self->ssl);
556 else
557 SSL_set_accept_state(self->ssl);
558 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000559
Antoine Pitroud6494802011-07-21 01:11:30 +0200560 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200561 if (sock != NULL) {
562 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
563 if (self->Socket == NULL) {
564 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200565 return NULL;
566 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100567 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000568 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000569}
570
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000571/* SSL object methods */
572
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300573/*[clinic input]
574_ssl._SSLSocket.do_handshake
575[clinic start generated code]*/
576
577static PyObject *
578_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
579/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000580{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000581 int ret;
582 int err;
583 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200584 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200585 _PyTime_t timeout, deadline = 0;
586 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000587
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200588 if (sock) {
589 if (((PyObject*)sock) == Py_None) {
590 _setSSLError("Underlying socket connection gone",
591 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
592 return NULL;
593 }
594 Py_INCREF(sock);
595
596 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100597 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200598 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
599 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000600 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000601
Victor Stinner14690702015-04-06 22:46:13 +0200602 timeout = GET_SOCKET_TIMEOUT(sock);
603 has_timeout = (timeout > 0);
604 if (has_timeout)
605 deadline = _PyTime_GetMonotonicClock() + timeout;
606
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000607 /* Actually negotiate SSL connection */
608 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000609 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000610 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000611 ret = SSL_do_handshake(self->ssl);
612 err = SSL_get_error(self->ssl, ret);
613 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200614
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000615 if (PyErr_CheckSignals())
616 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200617
Victor Stinner14690702015-04-06 22:46:13 +0200618 if (has_timeout)
619 timeout = deadline - _PyTime_GetMonotonicClock();
620
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000621 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200622 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000623 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200624 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000625 } else {
626 sockstate = SOCKET_OPERATION_OK;
627 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200628
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000629 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000630 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000631 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000632 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000633 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
634 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000635 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000636 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000637 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
638 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000639 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000640 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000641 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
642 break;
643 }
644 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200645 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000646 if (ret < 1)
647 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000648
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000649 if (self->peer_cert)
650 X509_free (self->peer_cert);
651 PySSL_BEGIN_ALLOW_THREADS
652 self->peer_cert = SSL_get_peer_certificate(self->ssl);
653 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200654 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000655
656 Py_INCREF(Py_None);
657 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000658
659error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200660 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000661 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000662}
663
Thomas Woutersed03b412007-08-28 21:37:11 +0000664static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000665_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000666
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000667 char namebuf[X509_NAME_MAXLEN];
668 int buflen;
669 PyObject *name_obj;
670 PyObject *value_obj;
671 PyObject *attr;
672 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000673
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000674 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
675 if (buflen < 0) {
676 _setSSLError(NULL, 0, __FILE__, __LINE__);
677 goto fail;
678 }
679 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
680 if (name_obj == NULL)
681 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000682
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000683 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
684 if (buflen < 0) {
685 _setSSLError(NULL, 0, __FILE__, __LINE__);
686 Py_DECREF(name_obj);
687 goto fail;
688 }
689 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000690 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000691 OPENSSL_free(valuebuf);
692 if (value_obj == NULL) {
693 Py_DECREF(name_obj);
694 goto fail;
695 }
696 attr = PyTuple_New(2);
697 if (attr == NULL) {
698 Py_DECREF(name_obj);
699 Py_DECREF(value_obj);
700 goto fail;
701 }
702 PyTuple_SET_ITEM(attr, 0, name_obj);
703 PyTuple_SET_ITEM(attr, 1, value_obj);
704 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000705
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000706 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000708}
709
710static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000711_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000712{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000713 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
714 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
715 PyObject *rdnt;
716 PyObject *attr = NULL; /* tuple to hold an attribute */
717 int entry_count = X509_NAME_entry_count(xname);
718 X509_NAME_ENTRY *entry;
719 ASN1_OBJECT *name;
720 ASN1_STRING *value;
721 int index_counter;
722 int rdn_level = -1;
723 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000724
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000725 dn = PyList_New(0);
726 if (dn == NULL)
727 return NULL;
728 /* now create another tuple to hold the top-level RDN */
729 rdn = PyList_New(0);
730 if (rdn == NULL)
731 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000732
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000733 for (index_counter = 0;
734 index_counter < entry_count;
735 index_counter++)
736 {
737 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000738
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000739 /* check to see if we've gotten to a new RDN */
740 if (rdn_level >= 0) {
741 if (rdn_level != entry->set) {
742 /* yes, new RDN */
743 /* add old RDN to DN */
744 rdnt = PyList_AsTuple(rdn);
745 Py_DECREF(rdn);
746 if (rdnt == NULL)
747 goto fail0;
748 retcode = PyList_Append(dn, rdnt);
749 Py_DECREF(rdnt);
750 if (retcode < 0)
751 goto fail0;
752 /* create new RDN */
753 rdn = PyList_New(0);
754 if (rdn == NULL)
755 goto fail0;
756 }
757 }
758 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000759
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000760 /* now add this attribute to the current RDN */
761 name = X509_NAME_ENTRY_get_object(entry);
762 value = X509_NAME_ENTRY_get_data(entry);
763 attr = _create_tuple_for_attribute(name, value);
764 /*
765 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
766 entry->set,
767 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
768 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
769 */
770 if (attr == NULL)
771 goto fail1;
772 retcode = PyList_Append(rdn, attr);
773 Py_DECREF(attr);
774 if (retcode < 0)
775 goto fail1;
776 }
777 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100778 if (rdn != NULL) {
779 if (PyList_GET_SIZE(rdn) > 0) {
780 rdnt = PyList_AsTuple(rdn);
781 Py_DECREF(rdn);
782 if (rdnt == NULL)
783 goto fail0;
784 retcode = PyList_Append(dn, rdnt);
785 Py_DECREF(rdnt);
786 if (retcode < 0)
787 goto fail0;
788 }
789 else {
790 Py_DECREF(rdn);
791 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000793
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 /* convert list to tuple */
795 rdnt = PyList_AsTuple(dn);
796 Py_DECREF(dn);
797 if (rdnt == NULL)
798 return NULL;
799 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000800
801 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000802 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000803
804 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000805 Py_XDECREF(dn);
806 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807}
808
809static PyObject *
810_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000811
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 /* this code follows the procedure outlined in
813 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
814 function to extract the STACK_OF(GENERAL_NAME),
815 then iterates through the stack to add the
816 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000817
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000818 int i, j;
819 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200820 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000821 X509_EXTENSION *ext = NULL;
822 GENERAL_NAMES *names = NULL;
823 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000824 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 BIO *biobuf = NULL;
826 char buf[2048];
827 char *vptr;
828 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000829 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000830
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000831 if (certificate == NULL)
832 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000833
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 /* get a memory buffer */
835 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000836
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200837 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 while ((i = X509_get_ext_by_NID(
839 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000840
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000841 if (peer_alt_names == Py_None) {
842 peer_alt_names = PyList_New(0);
843 if (peer_alt_names == NULL)
844 goto fail;
845 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000846
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000847 /* now decode the altName */
848 ext = X509_get_ext(certificate, i);
849 if(!(method = X509V3_EXT_get(ext))) {
850 PyErr_SetString
851 (PySSLErrorObject,
852 ERRSTR("No method for internalizing subjectAltName!"));
853 goto fail;
854 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000855
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000856 p = ext->value->data;
857 if (method->it)
858 names = (GENERAL_NAMES*)
859 (ASN1_item_d2i(NULL,
860 &p,
861 ext->value->length,
862 ASN1_ITEM_ptr(method->it)));
863 else
864 names = (GENERAL_NAMES*)
865 (method->d2i(NULL,
866 &p,
867 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000868
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000869 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000870 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200871 int gntype;
872 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000873
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000874 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200875 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200876 switch (gntype) {
877 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000878 /* we special-case DirName as a tuple of
879 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000880
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000881 t = PyTuple_New(2);
882 if (t == NULL) {
883 goto fail;
884 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000885
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000886 v = PyUnicode_FromString("DirName");
887 if (v == NULL) {
888 Py_DECREF(t);
889 goto fail;
890 }
891 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000893 v = _create_tuple_for_X509_NAME (name->d.dirn);
894 if (v == NULL) {
895 Py_DECREF(t);
896 goto fail;
897 }
898 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200899 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000900
Christian Heimes824f7f32013-08-17 00:54:47 +0200901 case GEN_EMAIL:
902 case GEN_DNS:
903 case GEN_URI:
904 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
905 correctly, CVE-2013-4238 */
906 t = PyTuple_New(2);
907 if (t == NULL)
908 goto fail;
909 switch (gntype) {
910 case GEN_EMAIL:
911 v = PyUnicode_FromString("email");
912 as = name->d.rfc822Name;
913 break;
914 case GEN_DNS:
915 v = PyUnicode_FromString("DNS");
916 as = name->d.dNSName;
917 break;
918 case GEN_URI:
919 v = PyUnicode_FromString("URI");
920 as = name->d.uniformResourceIdentifier;
921 break;
922 }
923 if (v == NULL) {
924 Py_DECREF(t);
925 goto fail;
926 }
927 PyTuple_SET_ITEM(t, 0, v);
928 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
929 ASN1_STRING_length(as));
930 if (v == NULL) {
931 Py_DECREF(t);
932 goto fail;
933 }
934 PyTuple_SET_ITEM(t, 1, v);
935 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000936
Christian Heimes824f7f32013-08-17 00:54:47 +0200937 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200939 switch (gntype) {
940 /* check for new general name type */
941 case GEN_OTHERNAME:
942 case GEN_X400:
943 case GEN_EDIPARTY:
944 case GEN_IPADD:
945 case GEN_RID:
946 break;
947 default:
948 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
949 "Unknown general name type %d",
950 gntype) == -1) {
951 goto fail;
952 }
953 break;
954 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 (void) BIO_reset(biobuf);
956 GENERAL_NAME_print(biobuf, name);
957 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
958 if (len < 0) {
959 _setSSLError(NULL, 0, __FILE__, __LINE__);
960 goto fail;
961 }
962 vptr = strchr(buf, ':');
963 if (vptr == NULL)
964 goto fail;
965 t = PyTuple_New(2);
966 if (t == NULL)
967 goto fail;
968 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
969 if (v == NULL) {
970 Py_DECREF(t);
971 goto fail;
972 }
973 PyTuple_SET_ITEM(t, 0, v);
974 v = PyUnicode_FromStringAndSize((vptr + 1),
975 (len - (vptr - buf + 1)));
976 if (v == NULL) {
977 Py_DECREF(t);
978 goto fail;
979 }
980 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200981 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000982 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000983
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000984 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000985
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000986 if (PyList_Append(peer_alt_names, t) < 0) {
987 Py_DECREF(t);
988 goto fail;
989 }
990 Py_DECREF(t);
991 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100992 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000993 }
994 BIO_free(biobuf);
995 if (peer_alt_names != Py_None) {
996 v = PyList_AsTuple(peer_alt_names);
997 Py_DECREF(peer_alt_names);
998 return v;
999 } else {
1000 return peer_alt_names;
1001 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001002
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001003
1004 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001005 if (biobuf != NULL)
1006 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001007
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001008 if (peer_alt_names != Py_None) {
1009 Py_XDECREF(peer_alt_names);
1010 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001011
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001012 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001013}
1014
1015static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001016_get_aia_uri(X509 *certificate, int nid) {
1017 PyObject *lst = NULL, *ostr = NULL;
1018 int i, result;
1019 AUTHORITY_INFO_ACCESS *info;
1020
1021 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001022 if (info == NULL)
1023 return Py_None;
1024 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1025 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001026 return Py_None;
1027 }
1028
1029 if ((lst = PyList_New(0)) == NULL) {
1030 goto fail;
1031 }
1032
1033 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1034 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1035 ASN1_IA5STRING *uri;
1036
1037 if ((OBJ_obj2nid(ad->method) != nid) ||
1038 (ad->location->type != GEN_URI)) {
1039 continue;
1040 }
1041 uri = ad->location->d.uniformResourceIdentifier;
1042 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1043 uri->length);
1044 if (ostr == NULL) {
1045 goto fail;
1046 }
1047 result = PyList_Append(lst, ostr);
1048 Py_DECREF(ostr);
1049 if (result < 0) {
1050 goto fail;
1051 }
1052 }
1053 AUTHORITY_INFO_ACCESS_free(info);
1054
1055 /* convert to tuple or None */
1056 if (PyList_Size(lst) == 0) {
1057 Py_DECREF(lst);
1058 return Py_None;
1059 } else {
1060 PyObject *tup;
1061 tup = PyList_AsTuple(lst);
1062 Py_DECREF(lst);
1063 return tup;
1064 }
1065
1066 fail:
1067 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001068 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001069 return NULL;
1070}
1071
1072static PyObject *
1073_get_crl_dp(X509 *certificate) {
1074 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001075 int i, j;
1076 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001077
Christian Heimes949ec142013-11-21 16:26:51 +01001078#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001079 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001080#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001081 /* Calls x509v3_cache_extensions and sets up crldp */
1082 X509_check_ca(certificate);
1083 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001084#endif
1085
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001086 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001087 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001088
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001089 lst = PyList_New(0);
1090 if (lst == NULL)
1091 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001092
1093 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1094 DIST_POINT *dp;
1095 STACK_OF(GENERAL_NAME) *gns;
1096
1097 dp = sk_DIST_POINT_value(dps, i);
1098 gns = dp->distpoint->name.fullname;
1099
1100 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1101 GENERAL_NAME *gn;
1102 ASN1_IA5STRING *uri;
1103 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001104 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001105
1106 gn = sk_GENERAL_NAME_value(gns, j);
1107 if (gn->type != GEN_URI) {
1108 continue;
1109 }
1110 uri = gn->d.uniformResourceIdentifier;
1111 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1112 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001113 if (ouri == NULL)
1114 goto done;
1115
1116 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001117 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001118 if (err < 0)
1119 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001120 }
1121 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001122
1123 /* Convert to tuple. */
1124 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1125
1126 done:
1127 Py_XDECREF(lst);
1128#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Peterson806fb252015-11-14 00:09:22 -08001129 sk_DIST_POINT_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001130#endif
1131 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001132}
1133
1134static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001135_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 PyObject *retval = NULL;
1138 BIO *biobuf = NULL;
1139 PyObject *peer;
1140 PyObject *peer_alt_names = NULL;
1141 PyObject *issuer;
1142 PyObject *version;
1143 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001144 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 ASN1_INTEGER *serialNumber;
1146 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001147 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 ASN1_TIME *notBefore, *notAfter;
1149 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001150
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001151 retval = PyDict_New();
1152 if (retval == NULL)
1153 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001154
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001155 peer = _create_tuple_for_X509_NAME(
1156 X509_get_subject_name(certificate));
1157 if (peer == NULL)
1158 goto fail0;
1159 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1160 Py_DECREF(peer);
1161 goto fail0;
1162 }
1163 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001164
Antoine Pitroufb046912010-11-09 20:21:19 +00001165 issuer = _create_tuple_for_X509_NAME(
1166 X509_get_issuer_name(certificate));
1167 if (issuer == NULL)
1168 goto fail0;
1169 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001170 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001171 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001172 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001173 Py_DECREF(issuer);
1174
1175 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001176 if (version == NULL)
1177 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001178 if (PyDict_SetItemString(retval, "version", version) < 0) {
1179 Py_DECREF(version);
1180 goto fail0;
1181 }
1182 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001183
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001184 /* get a memory buffer */
1185 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001186
Antoine Pitroufb046912010-11-09 20:21:19 +00001187 (void) BIO_reset(biobuf);
1188 serialNumber = X509_get_serialNumber(certificate);
1189 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1190 i2a_ASN1_INTEGER(biobuf, serialNumber);
1191 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1192 if (len < 0) {
1193 _setSSLError(NULL, 0, __FILE__, __LINE__);
1194 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001195 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001196 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1197 if (sn_obj == NULL)
1198 goto fail1;
1199 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1200 Py_DECREF(sn_obj);
1201 goto fail1;
1202 }
1203 Py_DECREF(sn_obj);
1204
1205 (void) BIO_reset(biobuf);
1206 notBefore = X509_get_notBefore(certificate);
1207 ASN1_TIME_print(biobuf, notBefore);
1208 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1209 if (len < 0) {
1210 _setSSLError(NULL, 0, __FILE__, __LINE__);
1211 goto fail1;
1212 }
1213 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1214 if (pnotBefore == NULL)
1215 goto fail1;
1216 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1217 Py_DECREF(pnotBefore);
1218 goto fail1;
1219 }
1220 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001221
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001222 (void) BIO_reset(biobuf);
1223 notAfter = X509_get_notAfter(certificate);
1224 ASN1_TIME_print(biobuf, notAfter);
1225 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1226 if (len < 0) {
1227 _setSSLError(NULL, 0, __FILE__, __LINE__);
1228 goto fail1;
1229 }
1230 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1231 if (pnotAfter == NULL)
1232 goto fail1;
1233 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1234 Py_DECREF(pnotAfter);
1235 goto fail1;
1236 }
1237 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001238
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001239 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001240
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241 peer_alt_names = _get_peer_alt_names(certificate);
1242 if (peer_alt_names == NULL)
1243 goto fail1;
1244 else if (peer_alt_names != Py_None) {
1245 if (PyDict_SetItemString(retval, "subjectAltName",
1246 peer_alt_names) < 0) {
1247 Py_DECREF(peer_alt_names);
1248 goto fail1;
1249 }
1250 Py_DECREF(peer_alt_names);
1251 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001252
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001253 /* Authority Information Access: OCSP URIs */
1254 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1255 if (obj == NULL) {
1256 goto fail1;
1257 } else if (obj != Py_None) {
1258 result = PyDict_SetItemString(retval, "OCSP", obj);
1259 Py_DECREF(obj);
1260 if (result < 0) {
1261 goto fail1;
1262 }
1263 }
1264
1265 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1266 if (obj == NULL) {
1267 goto fail1;
1268 } else if (obj != Py_None) {
1269 result = PyDict_SetItemString(retval, "caIssuers", obj);
1270 Py_DECREF(obj);
1271 if (result < 0) {
1272 goto fail1;
1273 }
1274 }
1275
1276 /* CDP (CRL distribution points) */
1277 obj = _get_crl_dp(certificate);
1278 if (obj == NULL) {
1279 goto fail1;
1280 } else if (obj != Py_None) {
1281 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1282 Py_DECREF(obj);
1283 if (result < 0) {
1284 goto fail1;
1285 }
1286 }
1287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 BIO_free(biobuf);
1289 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001290
1291 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001292 if (biobuf != NULL)
1293 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001294 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 Py_XDECREF(retval);
1296 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001297}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001298
Christian Heimes9a5395a2013-06-17 15:44:12 +02001299static PyObject *
1300_certificate_to_der(X509 *certificate)
1301{
1302 unsigned char *bytes_buf = NULL;
1303 int len;
1304 PyObject *retval;
1305
1306 bytes_buf = NULL;
1307 len = i2d_X509(certificate, &bytes_buf);
1308 if (len < 0) {
1309 _setSSLError(NULL, 0, __FILE__, __LINE__);
1310 return NULL;
1311 }
1312 /* this is actually an immutable bytes sequence */
1313 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1314 OPENSSL_free(bytes_buf);
1315 return retval;
1316}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001317
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001318/*[clinic input]
1319_ssl._test_decode_cert
1320 path: object(converter="PyUnicode_FSConverter")
1321 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001322
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001323[clinic start generated code]*/
1324
1325static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001326_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1327/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001328{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 X509 *x=NULL;
1331 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001332
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001333 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1334 PyErr_SetString(PySSLErrorObject,
1335 "Can't malloc memory to read file");
1336 goto fail0;
1337 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001338
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001339 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 PyErr_SetString(PySSLErrorObject,
1341 "Can't open file");
1342 goto fail0;
1343 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001344
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001345 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1346 if (x == NULL) {
1347 PyErr_SetString(PySSLErrorObject,
1348 "Error decoding PEM-encoded file");
1349 goto fail0;
1350 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001351
Antoine Pitroufb046912010-11-09 20:21:19 +00001352 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001353 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001354
1355 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001356 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001357 if (cert != NULL) BIO_free(cert);
1358 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001359}
1360
1361
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001362/*[clinic input]
1363_ssl._SSLSocket.peer_certificate
1364 der as binary_mode: bool = False
1365 /
1366
1367Returns the certificate for the peer.
1368
1369If no certificate was provided, returns None. If a certificate was
1370provided, but not validated, returns an empty dictionary. Otherwise
1371returns a dict containing information about the peer certificate.
1372
1373If the optional argument is True, returns a DER-encoded copy of the
1374peer certificate, or None if no certificate was provided. This will
1375return the certificate even if it wasn't validated.
1376[clinic start generated code]*/
1377
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001378static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001379_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1380/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001381{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001382 int verification;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001383
Antoine Pitrou20b85552013-09-29 19:50:53 +02001384 if (!self->handshake_done) {
1385 PyErr_SetString(PyExc_ValueError,
1386 "handshake not done yet");
1387 return NULL;
1388 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001389 if (!self->peer_cert)
1390 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001391
Antoine Pitrou721738f2012-08-15 23:20:39 +02001392 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001393 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001394 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001395 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001396 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 if ((verification & SSL_VERIFY_PEER) == 0)
1398 return PyDict_New();
1399 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001400 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001401 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001402}
1403
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001404static PyObject *
1405cipher_to_tuple(const SSL_CIPHER *cipher)
1406{
1407 const char *cipher_name, *cipher_protocol;
1408 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001409 if (retval == NULL)
1410 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001411
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001412 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001413 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001414 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001415 PyTuple_SET_ITEM(retval, 0, Py_None);
1416 } else {
1417 v = PyUnicode_FromString(cipher_name);
1418 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001419 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001420 PyTuple_SET_ITEM(retval, 0, v);
1421 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001422
1423 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001424 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001425 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001426 PyTuple_SET_ITEM(retval, 1, Py_None);
1427 } else {
1428 v = PyUnicode_FromString(cipher_protocol);
1429 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001430 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001431 PyTuple_SET_ITEM(retval, 1, v);
1432 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001433
1434 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001435 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001436 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001437 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001438
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001439 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001440
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001441 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001442 Py_DECREF(retval);
1443 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001444}
1445
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001446/*[clinic input]
1447_ssl._SSLSocket.shared_ciphers
1448[clinic start generated code]*/
1449
1450static PyObject *
1451_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1452/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001453{
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001454 SSL_SESSION *sess = SSL_get_session(self->ssl);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001455 STACK_OF(SSL_CIPHER) *ciphers;
1456 int i;
1457 PyObject *res;
1458
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001459 if (!sess || !sess->ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001460 Py_RETURN_NONE;
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001461 ciphers = sess->ciphers;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001462 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1463 if (!res)
1464 return NULL;
1465 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1466 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1467 if (!tup) {
1468 Py_DECREF(res);
1469 return NULL;
1470 }
1471 PyList_SET_ITEM(res, i, tup);
1472 }
1473 return res;
1474}
1475
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001476/*[clinic input]
1477_ssl._SSLSocket.cipher
1478[clinic start generated code]*/
1479
1480static PyObject *
1481_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1482/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001483{
1484 const SSL_CIPHER *current;
1485
1486 if (self->ssl == NULL)
1487 Py_RETURN_NONE;
1488 current = SSL_get_current_cipher(self->ssl);
1489 if (current == NULL)
1490 Py_RETURN_NONE;
1491 return cipher_to_tuple(current);
1492}
1493
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001494/*[clinic input]
1495_ssl._SSLSocket.version
1496[clinic start generated code]*/
1497
1498static PyObject *
1499_ssl__SSLSocket_version_impl(PySSLSocket *self)
1500/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001501{
1502 const char *version;
1503
1504 if (self->ssl == NULL)
1505 Py_RETURN_NONE;
1506 version = SSL_get_version(self->ssl);
1507 if (!strcmp(version, "unknown"))
1508 Py_RETURN_NONE;
1509 return PyUnicode_FromString(version);
1510}
1511
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001512#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001513/*[clinic input]
1514_ssl._SSLSocket.selected_npn_protocol
1515[clinic start generated code]*/
1516
1517static PyObject *
1518_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1519/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1520{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001521 const unsigned char *out;
1522 unsigned int outlen;
1523
Victor Stinner4569cd52013-06-23 14:58:43 +02001524 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001525 &out, &outlen);
1526
1527 if (out == NULL)
1528 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001529 return PyUnicode_FromStringAndSize((char *)out, outlen);
1530}
1531#endif
1532
1533#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001534/*[clinic input]
1535_ssl._SSLSocket.selected_alpn_protocol
1536[clinic start generated code]*/
1537
1538static PyObject *
1539_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1540/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1541{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001542 const unsigned char *out;
1543 unsigned int outlen;
1544
1545 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1546
1547 if (out == NULL)
1548 Py_RETURN_NONE;
1549 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001550}
1551#endif
1552
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001553/*[clinic input]
1554_ssl._SSLSocket.compression
1555[clinic start generated code]*/
1556
1557static PyObject *
1558_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1559/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1560{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001561#ifdef OPENSSL_NO_COMP
1562 Py_RETURN_NONE;
1563#else
1564 const COMP_METHOD *comp_method;
1565 const char *short_name;
1566
1567 if (self->ssl == NULL)
1568 Py_RETURN_NONE;
1569 comp_method = SSL_get_current_compression(self->ssl);
1570 if (comp_method == NULL || comp_method->type == NID_undef)
1571 Py_RETURN_NONE;
1572 short_name = OBJ_nid2sn(comp_method->type);
1573 if (short_name == NULL)
1574 Py_RETURN_NONE;
1575 return PyUnicode_DecodeFSDefault(short_name);
1576#endif
1577}
1578
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001579static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1580 Py_INCREF(self->ctx);
1581 return self->ctx;
1582}
1583
1584static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1585 void *closure) {
1586
1587 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001588#if !HAVE_SNI
1589 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1590 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001591 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001592#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001593 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001594 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001595 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{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001651 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001652 if (self->owner == NULL)
1653 return -1;
1654 return 0;
1655}
1656
1657PyDoc_STRVAR(PySSL_get_owner_doc,
1658"The Python-level owner of this object.\
1659Passed as \"self\" in servername callback.");
1660
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001661
Antoine Pitrou152efa22010-05-16 18:19:27 +00001662static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001663{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001664 if (self->peer_cert) /* Possible not to have one? */
1665 X509_free (self->peer_cert);
1666 if (self->ssl)
1667 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001668 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001669 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001670 Py_XDECREF(self->server_hostname);
1671 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001672 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001673}
1674
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001675/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001676 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001677 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001678 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001679
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001680static int
Victor Stinner14690702015-04-06 22:46:13 +02001681PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001682{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001683 int rc;
1684#ifdef HAVE_POLL
1685 struct pollfd pollfd;
1686 _PyTime_t ms;
1687#else
1688 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001689 fd_set fds;
1690 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001691#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001692
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001693 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001694 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001695 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001696 else if (timeout < 0) {
1697 if (s->sock_timeout > 0)
1698 return SOCKET_HAS_TIMED_OUT;
1699 else
1700 return SOCKET_IS_BLOCKING;
1701 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001702
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001703 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001704 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001705 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001706
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001707 /* Prefer poll, if available, since you can poll() any fd
1708 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001709#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001710 pollfd.fd = s->sock_fd;
1711 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001712
Victor Stinner14690702015-04-06 22:46:13 +02001713 /* timeout is in seconds, poll() uses milliseconds */
1714 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001715 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001716
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001717 PySSL_BEGIN_ALLOW_THREADS
1718 rc = poll(&pollfd, 1, (int)ms);
1719 PySSL_END_ALLOW_THREADS
1720#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001721 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001722 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001723 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001724
Victor Stinner14690702015-04-06 22:46:13 +02001725 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001726
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001727 FD_ZERO(&fds);
1728 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001729
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001730 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001731 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001732 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001733 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001734 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001735 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001736 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001738#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001739
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001740 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1741 (when we are able to write or when there's something to read) */
1742 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001743}
1744
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001745/*[clinic input]
1746_ssl._SSLSocket.write
1747 b: Py_buffer
1748 /
1749
1750Writes the bytes-like object b into the SSL object.
1751
1752Returns the number of bytes written.
1753[clinic start generated code]*/
1754
1755static PyObject *
1756_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1757/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001758{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001759 int len;
1760 int sockstate;
1761 int err;
1762 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001763 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001764 _PyTime_t timeout, deadline = 0;
1765 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001766
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001767 if (sock != NULL) {
1768 if (((PyObject*)sock) == Py_None) {
1769 _setSSLError("Underlying socket connection gone",
1770 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1771 return NULL;
1772 }
1773 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001774 }
1775
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001776 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001777 PyErr_Format(PyExc_OverflowError,
1778 "string longer than %d bytes", INT_MAX);
1779 goto error;
1780 }
1781
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001782 if (sock != NULL) {
1783 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001784 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001785 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1786 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1787 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001788
Victor Stinner14690702015-04-06 22:46:13 +02001789 timeout = GET_SOCKET_TIMEOUT(sock);
1790 has_timeout = (timeout > 0);
1791 if (has_timeout)
1792 deadline = _PyTime_GetMonotonicClock() + timeout;
1793
1794 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001795 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001796 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001797 "The write operation timed out");
1798 goto error;
1799 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1800 PyErr_SetString(PySSLErrorObject,
1801 "Underlying socket has been closed.");
1802 goto error;
1803 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1804 PyErr_SetString(PySSLErrorObject,
1805 "Underlying socket too large for select().");
1806 goto error;
1807 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001808
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001809 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001811 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001812 err = SSL_get_error(self->ssl, len);
1813 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001814
1815 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001816 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001817
Victor Stinner14690702015-04-06 22:46:13 +02001818 if (has_timeout)
1819 timeout = deadline - _PyTime_GetMonotonicClock();
1820
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001821 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001822 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001824 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 } else {
1826 sockstate = SOCKET_OPERATION_OK;
1827 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001828
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001829 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001830 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001831 "The write operation timed out");
1832 goto error;
1833 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1834 PyErr_SetString(PySSLErrorObject,
1835 "Underlying socket has been closed.");
1836 goto error;
1837 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1838 break;
1839 }
1840 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001841
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001842 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001843 if (len > 0)
1844 return PyLong_FromLong(len);
1845 else
1846 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001847
1848error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001849 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001850 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001851}
1852
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001853/*[clinic input]
1854_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001855
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001856Returns the number of already decrypted bytes available for read, pending on the connection.
1857[clinic start generated code]*/
1858
1859static PyObject *
1860_ssl__SSLSocket_pending_impl(PySSLSocket *self)
1861/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00001862{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001863 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001864
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001865 PySSL_BEGIN_ALLOW_THREADS
1866 count = SSL_pending(self->ssl);
1867 PySSL_END_ALLOW_THREADS
1868 if (count < 0)
1869 return PySSL_SetError(self, count, __FILE__, __LINE__);
1870 else
1871 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001872}
1873
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001874/*[clinic input]
1875_ssl._SSLSocket.read
1876 size as len: int
1877 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001878 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001879 ]
1880 /
Bill Janssen6e027db2007-11-15 22:23:56 +00001881
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001882Read up to size bytes from the SSL socket.
1883[clinic start generated code]*/
1884
1885static PyObject *
1886_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
1887 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001888/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001889{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001890 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001891 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001892 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001893 int sockstate;
1894 int err;
1895 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001896 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001897 _PyTime_t timeout, deadline = 0;
1898 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001899
Martin Panter5503d472016-03-27 05:35:19 +00001900 if (!group_right_1 && len < 0) {
1901 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1902 return NULL;
1903 }
1904
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001905 if (sock != NULL) {
1906 if (((PyObject*)sock) == Py_None) {
1907 _setSSLError("Underlying socket connection gone",
1908 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1909 return NULL;
1910 }
1911 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001912 }
1913
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001914 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001915 dest = PyBytes_FromStringAndSize(NULL, len);
1916 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001917 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00001918 if (len == 0) {
1919 Py_XDECREF(sock);
1920 return dest;
1921 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001922 mem = PyBytes_AS_STRING(dest);
1923 }
1924 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001925 mem = buffer->buf;
1926 if (len <= 0 || len > buffer->len) {
1927 len = (int) buffer->len;
1928 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001929 PyErr_SetString(PyExc_OverflowError,
1930 "maximum length can't fit in a C 'int'");
1931 goto error;
1932 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00001933 if (len == 0) {
1934 count = 0;
1935 goto done;
1936 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001937 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001938 }
1939
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001940 if (sock != NULL) {
1941 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001942 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001943 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1944 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1945 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001946
Victor Stinner14690702015-04-06 22:46:13 +02001947 timeout = GET_SOCKET_TIMEOUT(sock);
1948 has_timeout = (timeout > 0);
1949 if (has_timeout)
1950 deadline = _PyTime_GetMonotonicClock() + timeout;
1951
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001952 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001953 PySSL_BEGIN_ALLOW_THREADS
1954 count = SSL_read(self->ssl, mem, len);
1955 err = SSL_get_error(self->ssl, count);
1956 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001957
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001958 if (PyErr_CheckSignals())
1959 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001960
Victor Stinner14690702015-04-06 22:46:13 +02001961 if (has_timeout)
1962 timeout = deadline - _PyTime_GetMonotonicClock();
1963
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001964 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001965 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001966 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001967 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001968 } else if (err == SSL_ERROR_ZERO_RETURN &&
1969 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001970 {
1971 count = 0;
1972 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001973 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001974 else
1975 sockstate = SOCKET_OPERATION_OK;
1976
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001977 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001978 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001979 "The read operation timed out");
1980 goto error;
1981 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1982 break;
1983 }
1984 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001985
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001986 if (count <= 0) {
1987 PySSL_SetError(self, count, __FILE__, __LINE__);
1988 goto error;
1989 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001990
1991done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001992 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001993 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001994 _PyBytes_Resize(&dest, count);
1995 return dest;
1996 }
1997 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001998 return PyLong_FromLong(count);
1999 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002000
2001error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002002 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002003 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002004 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002005 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002006}
2007
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002008/*[clinic input]
2009_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002010
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002011Does the SSL shutdown handshake with the remote end.
2012
2013Returns the underlying socket object.
2014[clinic start generated code]*/
2015
2016static PyObject *
2017_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2018/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002019{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002020 int err, ssl_err, sockstate, nonblocking;
2021 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002022 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002023 _PyTime_t timeout, deadline = 0;
2024 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002025
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002026 if (sock != NULL) {
2027 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002028 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002029 _setSSLError("Underlying socket connection gone",
2030 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2031 return NULL;
2032 }
2033 Py_INCREF(sock);
2034
2035 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002036 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002037 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2038 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002039 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002040
Victor Stinner14690702015-04-06 22:46:13 +02002041 timeout = GET_SOCKET_TIMEOUT(sock);
2042 has_timeout = (timeout > 0);
2043 if (has_timeout)
2044 deadline = _PyTime_GetMonotonicClock() + timeout;
2045
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002046 while (1) {
2047 PySSL_BEGIN_ALLOW_THREADS
2048 /* Disable read-ahead so that unwrap can work correctly.
2049 * Otherwise OpenSSL might read in too much data,
2050 * eating clear text data that happens to be
2051 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002052 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002053 * function is used and the shutdown_seen_zero != 0
2054 * condition is met.
2055 */
2056 if (self->shutdown_seen_zero)
2057 SSL_set_read_ahead(self->ssl, 0);
2058 err = SSL_shutdown(self->ssl);
2059 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002060
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002061 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2062 if (err > 0)
2063 break;
2064 if (err == 0) {
2065 /* Don't loop endlessly; instead preserve legacy
2066 behaviour of trying SSL_shutdown() only twice.
2067 This looks necessary for OpenSSL < 0.9.8m */
2068 if (++zeros > 1)
2069 break;
2070 /* Shutdown was sent, now try receiving */
2071 self->shutdown_seen_zero = 1;
2072 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002073 }
2074
Victor Stinner14690702015-04-06 22:46:13 +02002075 if (has_timeout)
2076 timeout = deadline - _PyTime_GetMonotonicClock();
2077
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002078 /* Possibly retry shutdown until timeout or failure */
2079 ssl_err = SSL_get_error(self->ssl, err);
2080 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002081 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002082 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002083 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002084 else
2085 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002086
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002087 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2088 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002089 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002090 "The read operation timed out");
2091 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002092 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002093 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002094 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002095 }
2096 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2097 PyErr_SetString(PySSLErrorObject,
2098 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002099 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002100 }
2101 else if (sockstate != SOCKET_OPERATION_OK)
2102 /* Retain the SSL error code */
2103 break;
2104 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002105
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002106 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002107 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002108 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002109 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002110 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002111 /* It's already INCREF'ed */
2112 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002113 else
2114 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002115
2116error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002117 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002118 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002119}
2120
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002121/*[clinic input]
2122_ssl._SSLSocket.tls_unique_cb
2123
2124Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2125
2126If the TLS handshake is not yet complete, None is returned.
2127[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002128
Antoine Pitroud6494802011-07-21 01:11:30 +02002129static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002130_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2131/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002132{
2133 PyObject *retval = NULL;
2134 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002135 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002136
2137 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2138 /* if session is resumed XOR we are the client */
2139 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2140 }
2141 else {
2142 /* if a new session XOR we are the server */
2143 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2144 }
2145
2146 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002147 if (len == 0)
2148 Py_RETURN_NONE;
2149
2150 retval = PyBytes_FromStringAndSize(buf, len);
2151
2152 return retval;
2153}
2154
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002155static PyGetSetDef ssl_getsetlist[] = {
2156 {"context", (getter) PySSL_get_context,
2157 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002158 {"server_side", (getter) PySSL_get_server_side, NULL,
2159 PySSL_get_server_side_doc},
2160 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2161 PySSL_get_server_hostname_doc},
2162 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2163 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002164 {NULL}, /* sentinel */
2165};
2166
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002167static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002168 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2169 _SSL__SSLSOCKET_WRITE_METHODDEF
2170 _SSL__SSLSOCKET_READ_METHODDEF
2171 _SSL__SSLSOCKET_PENDING_METHODDEF
2172 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2173 _SSL__SSLSOCKET_CIPHER_METHODDEF
2174 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2175 _SSL__SSLSOCKET_VERSION_METHODDEF
2176 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2177 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2178 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2179 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2180 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002181 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002182};
2183
Antoine Pitrou152efa22010-05-16 18:19:27 +00002184static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002185 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002186 "_ssl._SSLSocket", /*tp_name*/
2187 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002188 0, /*tp_itemsize*/
2189 /* methods */
2190 (destructor)PySSL_dealloc, /*tp_dealloc*/
2191 0, /*tp_print*/
2192 0, /*tp_getattr*/
2193 0, /*tp_setattr*/
2194 0, /*tp_reserved*/
2195 0, /*tp_repr*/
2196 0, /*tp_as_number*/
2197 0, /*tp_as_sequence*/
2198 0, /*tp_as_mapping*/
2199 0, /*tp_hash*/
2200 0, /*tp_call*/
2201 0, /*tp_str*/
2202 0, /*tp_getattro*/
2203 0, /*tp_setattro*/
2204 0, /*tp_as_buffer*/
2205 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2206 0, /*tp_doc*/
2207 0, /*tp_traverse*/
2208 0, /*tp_clear*/
2209 0, /*tp_richcompare*/
2210 0, /*tp_weaklistoffset*/
2211 0, /*tp_iter*/
2212 0, /*tp_iternext*/
2213 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002214 0, /*tp_members*/
2215 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002216};
2217
Antoine Pitrou152efa22010-05-16 18:19:27 +00002218
2219/*
2220 * _SSLContext objects
2221 */
2222
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002223/*[clinic input]
2224@classmethod
2225_ssl._SSLContext.__new__
2226 protocol as proto_version: int
2227 /
2228[clinic start generated code]*/
2229
Antoine Pitrou152efa22010-05-16 18:19:27 +00002230static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002231_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2232/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002233{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002234 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002235 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002236 SSL_CTX *ctx = NULL;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002237#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002238 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002239#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002240
Antoine Pitrou152efa22010-05-16 18:19:27 +00002241 PySSL_BEGIN_ALLOW_THREADS
2242 if (proto_version == PY_SSL_VERSION_TLS1)
2243 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002244#if HAVE_TLSv1_2
2245 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2246 ctx = SSL_CTX_new(TLSv1_1_method());
2247 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2248 ctx = SSL_CTX_new(TLSv1_2_method());
2249#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002250#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002251 else if (proto_version == PY_SSL_VERSION_SSL3)
2252 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002253#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002254#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002255 else if (proto_version == PY_SSL_VERSION_SSL2)
2256 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002257#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002258 else if (proto_version == PY_SSL_VERSION_SSL23)
2259 ctx = SSL_CTX_new(SSLv23_method());
2260 else
2261 proto_version = -1;
2262 PySSL_END_ALLOW_THREADS
2263
2264 if (proto_version == -1) {
2265 PyErr_SetString(PyExc_ValueError,
2266 "invalid protocol version");
2267 return NULL;
2268 }
2269 if (ctx == NULL) {
2270 PyErr_SetString(PySSLErrorObject,
2271 "failed to allocate SSL context");
2272 return NULL;
2273 }
2274
2275 assert(type != NULL && type->tp_alloc != NULL);
2276 self = (PySSLContext *) type->tp_alloc(type, 0);
2277 if (self == NULL) {
2278 SSL_CTX_free(ctx);
2279 return NULL;
2280 }
2281 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002282#ifdef OPENSSL_NPN_NEGOTIATED
2283 self->npn_protocols = NULL;
2284#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002285#ifdef HAVE_ALPN
2286 self->alpn_protocols = NULL;
2287#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002288#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002289 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002290#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002291 /* Don't check host name by default */
2292 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002293 /* Defaults */
2294 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002295 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2296 if (proto_version != PY_SSL_VERSION_SSL2)
2297 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002298 if (proto_version != PY_SSL_VERSION_SSL3)
2299 options |= SSL_OP_NO_SSLv3;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002300 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002301
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002302#if defined(SSL_MODE_RELEASE_BUFFERS)
2303 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2304 usage for no cost at all. However, don't do this for OpenSSL versions
2305 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2306 2014-0198. I can't find exactly which beta fixed this CVE, so be
2307 conservative and assume it wasn't fixed until release. We do this check
2308 at runtime to avoid problems from the dynamic linker.
2309 See #25672 for more on this. */
2310 libver = SSLeay();
2311 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2312 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2313 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2314 }
2315#endif
2316
2317
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002318#ifndef OPENSSL_NO_ECDH
2319 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2320 prime256v1 by default. This is Apache mod_ssl's initialization
2321 policy, so we should be safe. */
2322#if defined(SSL_CTX_set_ecdh_auto)
2323 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2324#else
2325 {
2326 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2327 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2328 EC_KEY_free(key);
2329 }
2330#endif
2331#endif
2332
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002333#define SID_CTX "Python"
2334 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2335 sizeof(SID_CTX));
2336#undef SID_CTX
2337
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002338#ifdef X509_V_FLAG_TRUSTED_FIRST
2339 {
2340 /* Improve trust chain building when cross-signed intermediate
2341 certificates are present. See https://bugs.python.org/issue23476. */
2342 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2343 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2344 }
2345#endif
2346
Antoine Pitrou152efa22010-05-16 18:19:27 +00002347 return (PyObject *)self;
2348}
2349
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002350static int
2351context_traverse(PySSLContext *self, visitproc visit, void *arg)
2352{
2353#ifndef OPENSSL_NO_TLSEXT
2354 Py_VISIT(self->set_hostname);
2355#endif
2356 return 0;
2357}
2358
2359static int
2360context_clear(PySSLContext *self)
2361{
2362#ifndef OPENSSL_NO_TLSEXT
2363 Py_CLEAR(self->set_hostname);
2364#endif
2365 return 0;
2366}
2367
Antoine Pitrou152efa22010-05-16 18:19:27 +00002368static void
2369context_dealloc(PySSLContext *self)
2370{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002371 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002372 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002373#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002374 PyMem_FREE(self->npn_protocols);
2375#endif
2376#ifdef HAVE_ALPN
2377 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002378#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002379 Py_TYPE(self)->tp_free(self);
2380}
2381
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002382/*[clinic input]
2383_ssl._SSLContext.set_ciphers
2384 cipherlist: str
2385 /
2386[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002387
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002388static PyObject *
2389_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2390/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2391{
2392 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002393 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002394 /* Clearing the error queue is necessary on some OpenSSL versions,
2395 otherwise the error will be reported again when another SSL call
2396 is done. */
2397 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002398 PyErr_SetString(PySSLErrorObject,
2399 "No cipher can be selected.");
2400 return NULL;
2401 }
2402 Py_RETURN_NONE;
2403}
2404
Benjamin Petersonc54de472015-01-28 12:06:39 -05002405#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002406static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002407do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2408 const unsigned char *server_protocols, unsigned int server_protocols_len,
2409 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002410{
Benjamin Peterson88615022015-01-23 17:30:26 -05002411 int ret;
2412 if (client_protocols == NULL) {
2413 client_protocols = (unsigned char *)"";
2414 client_protocols_len = 0;
2415 }
2416 if (server_protocols == NULL) {
2417 server_protocols = (unsigned char *)"";
2418 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002419 }
2420
Benjamin Peterson88615022015-01-23 17:30:26 -05002421 ret = SSL_select_next_proto(out, outlen,
2422 server_protocols, server_protocols_len,
2423 client_protocols, client_protocols_len);
2424 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2425 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002426
2427 return SSL_TLSEXT_ERR_OK;
2428}
2429
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002430/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2431static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002432_advertiseNPN_cb(SSL *s,
2433 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002434 void *args)
2435{
2436 PySSLContext *ssl_ctx = (PySSLContext *) args;
2437
2438 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002439 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002440 *len = 0;
2441 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002442 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002443 *len = ssl_ctx->npn_protocols_len;
2444 }
2445
2446 return SSL_TLSEXT_ERR_OK;
2447}
2448/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2449static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002450_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002451 unsigned char **out, unsigned char *outlen,
2452 const unsigned char *server, unsigned int server_len,
2453 void *args)
2454{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002455 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002456 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002457 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002458}
2459#endif
2460
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002461/*[clinic input]
2462_ssl._SSLContext._set_npn_protocols
2463 protos: Py_buffer
2464 /
2465[clinic start generated code]*/
2466
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002467static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002468_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2469 Py_buffer *protos)
2470/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002471{
2472#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002473 PyMem_Free(self->npn_protocols);
2474 self->npn_protocols = PyMem_Malloc(protos->len);
2475 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002476 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002477 memcpy(self->npn_protocols, protos->buf, protos->len);
2478 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002479
2480 /* set both server and client callbacks, because the context can
2481 * be used to create both types of sockets */
2482 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2483 _advertiseNPN_cb,
2484 self);
2485 SSL_CTX_set_next_proto_select_cb(self->ctx,
2486 _selectNPN_cb,
2487 self);
2488
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002489 Py_RETURN_NONE;
2490#else
2491 PyErr_SetString(PyExc_NotImplementedError,
2492 "The NPN extension requires OpenSSL 1.0.1 or later.");
2493 return NULL;
2494#endif
2495}
2496
Benjamin Petersoncca27322015-01-23 16:35:37 -05002497#ifdef HAVE_ALPN
2498static int
2499_selectALPN_cb(SSL *s,
2500 const unsigned char **out, unsigned char *outlen,
2501 const unsigned char *client_protocols, unsigned int client_protocols_len,
2502 void *args)
2503{
2504 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002505 return do_protocol_selection(1, (unsigned char **)out, outlen,
2506 ctx->alpn_protocols, ctx->alpn_protocols_len,
2507 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002508}
2509#endif
2510
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002511/*[clinic input]
2512_ssl._SSLContext._set_alpn_protocols
2513 protos: Py_buffer
2514 /
2515[clinic start generated code]*/
2516
Benjamin Petersoncca27322015-01-23 16:35:37 -05002517static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002518_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2519 Py_buffer *protos)
2520/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002521{
2522#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002523 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002524 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002525 if (!self->alpn_protocols)
2526 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002527 memcpy(self->alpn_protocols, protos->buf, protos->len);
2528 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002529
2530 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2531 return PyErr_NoMemory();
2532 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2533
Benjamin Petersoncca27322015-01-23 16:35:37 -05002534 Py_RETURN_NONE;
2535#else
2536 PyErr_SetString(PyExc_NotImplementedError,
2537 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2538 return NULL;
2539#endif
2540}
2541
Antoine Pitrou152efa22010-05-16 18:19:27 +00002542static PyObject *
2543get_verify_mode(PySSLContext *self, void *c)
2544{
2545 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2546 case SSL_VERIFY_NONE:
2547 return PyLong_FromLong(PY_SSL_CERT_NONE);
2548 case SSL_VERIFY_PEER:
2549 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2550 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2551 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2552 }
2553 PyErr_SetString(PySSLErrorObject,
2554 "invalid return value from SSL_CTX_get_verify_mode");
2555 return NULL;
2556}
2557
2558static int
2559set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2560{
2561 int n, mode;
2562 if (!PyArg_Parse(arg, "i", &n))
2563 return -1;
2564 if (n == PY_SSL_CERT_NONE)
2565 mode = SSL_VERIFY_NONE;
2566 else if (n == PY_SSL_CERT_OPTIONAL)
2567 mode = SSL_VERIFY_PEER;
2568 else if (n == PY_SSL_CERT_REQUIRED)
2569 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2570 else {
2571 PyErr_SetString(PyExc_ValueError,
2572 "invalid value for verify_mode");
2573 return -1;
2574 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002575 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2576 PyErr_SetString(PyExc_ValueError,
2577 "Cannot set verify_mode to CERT_NONE when "
2578 "check_hostname is enabled.");
2579 return -1;
2580 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002581 SSL_CTX_set_verify(self->ctx, mode, NULL);
2582 return 0;
2583}
2584
2585static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002586get_verify_flags(PySSLContext *self, void *c)
2587{
2588 X509_STORE *store;
2589 unsigned long flags;
2590
2591 store = SSL_CTX_get_cert_store(self->ctx);
2592 flags = X509_VERIFY_PARAM_get_flags(store->param);
2593 return PyLong_FromUnsignedLong(flags);
2594}
2595
2596static int
2597set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2598{
2599 X509_STORE *store;
2600 unsigned long new_flags, flags, set, clear;
2601
2602 if (!PyArg_Parse(arg, "k", &new_flags))
2603 return -1;
2604 store = SSL_CTX_get_cert_store(self->ctx);
2605 flags = X509_VERIFY_PARAM_get_flags(store->param);
2606 clear = flags & ~new_flags;
2607 set = ~flags & new_flags;
2608 if (clear) {
2609 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2610 _setSSLError(NULL, 0, __FILE__, __LINE__);
2611 return -1;
2612 }
2613 }
2614 if (set) {
2615 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2616 _setSSLError(NULL, 0, __FILE__, __LINE__);
2617 return -1;
2618 }
2619 }
2620 return 0;
2621}
2622
2623static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002624get_options(PySSLContext *self, void *c)
2625{
2626 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2627}
2628
2629static int
2630set_options(PySSLContext *self, PyObject *arg, void *c)
2631{
2632 long new_opts, opts, set, clear;
2633 if (!PyArg_Parse(arg, "l", &new_opts))
2634 return -1;
2635 opts = SSL_CTX_get_options(self->ctx);
2636 clear = opts & ~new_opts;
2637 set = ~opts & new_opts;
2638 if (clear) {
2639#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2640 SSL_CTX_clear_options(self->ctx, clear);
2641#else
2642 PyErr_SetString(PyExc_ValueError,
2643 "can't clear options before OpenSSL 0.9.8m");
2644 return -1;
2645#endif
2646 }
2647 if (set)
2648 SSL_CTX_set_options(self->ctx, set);
2649 return 0;
2650}
2651
Christian Heimes1aa9a752013-12-02 02:41:19 +01002652static PyObject *
2653get_check_hostname(PySSLContext *self, void *c)
2654{
2655 return PyBool_FromLong(self->check_hostname);
2656}
2657
2658static int
2659set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2660{
2661 int check_hostname;
2662 if (!PyArg_Parse(arg, "p", &check_hostname))
2663 return -1;
2664 if (check_hostname &&
2665 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2666 PyErr_SetString(PyExc_ValueError,
2667 "check_hostname needs a SSL context with either "
2668 "CERT_OPTIONAL or CERT_REQUIRED");
2669 return -1;
2670 }
2671 self->check_hostname = check_hostname;
2672 return 0;
2673}
2674
2675
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002676typedef struct {
2677 PyThreadState *thread_state;
2678 PyObject *callable;
2679 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002680 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002681 int error;
2682} _PySSLPasswordInfo;
2683
2684static int
2685_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2686 const char *bad_type_error)
2687{
2688 /* Set the password and size fields of a _PySSLPasswordInfo struct
2689 from a unicode, bytes, or byte array object.
2690 The password field will be dynamically allocated and must be freed
2691 by the caller */
2692 PyObject *password_bytes = NULL;
2693 const char *data = NULL;
2694 Py_ssize_t size;
2695
2696 if (PyUnicode_Check(password)) {
2697 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2698 if (!password_bytes) {
2699 goto error;
2700 }
2701 data = PyBytes_AS_STRING(password_bytes);
2702 size = PyBytes_GET_SIZE(password_bytes);
2703 } else if (PyBytes_Check(password)) {
2704 data = PyBytes_AS_STRING(password);
2705 size = PyBytes_GET_SIZE(password);
2706 } else if (PyByteArray_Check(password)) {
2707 data = PyByteArray_AS_STRING(password);
2708 size = PyByteArray_GET_SIZE(password);
2709 } else {
2710 PyErr_SetString(PyExc_TypeError, bad_type_error);
2711 goto error;
2712 }
2713
Victor Stinner9ee02032013-06-23 15:08:23 +02002714 if (size > (Py_ssize_t)INT_MAX) {
2715 PyErr_Format(PyExc_ValueError,
2716 "password cannot be longer than %d bytes", INT_MAX);
2717 goto error;
2718 }
2719
Victor Stinner11ebff22013-07-07 17:07:52 +02002720 PyMem_Free(pw_info->password);
2721 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002722 if (!pw_info->password) {
2723 PyErr_SetString(PyExc_MemoryError,
2724 "unable to allocate password buffer");
2725 goto error;
2726 }
2727 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002728 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002729
2730 Py_XDECREF(password_bytes);
2731 return 1;
2732
2733error:
2734 Py_XDECREF(password_bytes);
2735 return 0;
2736}
2737
2738static int
2739_password_callback(char *buf, int size, int rwflag, void *userdata)
2740{
2741 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2742 PyObject *fn_ret = NULL;
2743
2744 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2745
2746 if (pw_info->callable) {
2747 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2748 if (!fn_ret) {
2749 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2750 core python API, so we could use it to add a frame here */
2751 goto error;
2752 }
2753
2754 if (!_pwinfo_set(pw_info, fn_ret,
2755 "password callback must return a string")) {
2756 goto error;
2757 }
2758 Py_CLEAR(fn_ret);
2759 }
2760
2761 if (pw_info->size > size) {
2762 PyErr_Format(PyExc_ValueError,
2763 "password cannot be longer than %d bytes", size);
2764 goto error;
2765 }
2766
2767 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2768 memcpy(buf, pw_info->password, pw_info->size);
2769 return pw_info->size;
2770
2771error:
2772 Py_XDECREF(fn_ret);
2773 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2774 pw_info->error = 1;
2775 return -1;
2776}
2777
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002778/*[clinic input]
2779_ssl._SSLContext.load_cert_chain
2780 certfile: object
2781 keyfile: object = NULL
2782 password: object = NULL
2783
2784[clinic start generated code]*/
2785
Antoine Pitroub5218772010-05-21 09:56:06 +00002786static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002787_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
2788 PyObject *keyfile, PyObject *password)
2789/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002790{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002791 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002792 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2793 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2794 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002795 int r;
2796
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002797 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002798 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002799 if (keyfile == Py_None)
2800 keyfile = NULL;
2801 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2802 PyErr_SetString(PyExc_TypeError,
2803 "certfile should be a valid filesystem path");
2804 return NULL;
2805 }
2806 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2807 PyErr_SetString(PyExc_TypeError,
2808 "keyfile should be a valid filesystem path");
2809 goto error;
2810 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002811 if (password && password != Py_None) {
2812 if (PyCallable_Check(password)) {
2813 pw_info.callable = password;
2814 } else if (!_pwinfo_set(&pw_info, password,
2815 "password should be a string or callable")) {
2816 goto error;
2817 }
2818 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2819 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2820 }
2821 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002822 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2823 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002824 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002825 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002826 if (pw_info.error) {
2827 ERR_clear_error();
2828 /* the password callback has already set the error information */
2829 }
2830 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002831 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002832 PyErr_SetFromErrno(PyExc_IOError);
2833 }
2834 else {
2835 _setSSLError(NULL, 0, __FILE__, __LINE__);
2836 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002837 goto error;
2838 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002839 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002840 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002841 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2842 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002843 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2844 Py_CLEAR(keyfile_bytes);
2845 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002846 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002847 if (pw_info.error) {
2848 ERR_clear_error();
2849 /* the password callback has already set the error information */
2850 }
2851 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002852 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002853 PyErr_SetFromErrno(PyExc_IOError);
2854 }
2855 else {
2856 _setSSLError(NULL, 0, __FILE__, __LINE__);
2857 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002858 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002859 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002860 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002861 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002862 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002863 if (r != 1) {
2864 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002865 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002866 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002867 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2868 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002869 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002870 Py_RETURN_NONE;
2871
2872error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002873 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2874 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002875 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002876 Py_XDECREF(keyfile_bytes);
2877 Py_XDECREF(certfile_bytes);
2878 return NULL;
2879}
2880
Christian Heimesefff7062013-11-21 03:35:02 +01002881/* internal helper function, returns -1 on error
2882 */
2883static int
2884_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2885 int filetype)
2886{
2887 BIO *biobuf = NULL;
2888 X509_STORE *store;
2889 int retval = 0, err, loaded = 0;
2890
2891 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2892
2893 if (len <= 0) {
2894 PyErr_SetString(PyExc_ValueError,
2895 "Empty certificate data");
2896 return -1;
2897 } else if (len > INT_MAX) {
2898 PyErr_SetString(PyExc_OverflowError,
2899 "Certificate data is too long.");
2900 return -1;
2901 }
2902
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002903 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002904 if (biobuf == NULL) {
2905 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2906 return -1;
2907 }
2908
2909 store = SSL_CTX_get_cert_store(self->ctx);
2910 assert(store != NULL);
2911
2912 while (1) {
2913 X509 *cert = NULL;
2914 int r;
2915
2916 if (filetype == SSL_FILETYPE_ASN1) {
2917 cert = d2i_X509_bio(biobuf, NULL);
2918 } else {
2919 cert = PEM_read_bio_X509(biobuf, NULL,
2920 self->ctx->default_passwd_callback,
2921 self->ctx->default_passwd_callback_userdata);
2922 }
2923 if (cert == NULL) {
2924 break;
2925 }
2926 r = X509_STORE_add_cert(store, cert);
2927 X509_free(cert);
2928 if (!r) {
2929 err = ERR_peek_last_error();
2930 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2931 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2932 /* cert already in hash table, not an error */
2933 ERR_clear_error();
2934 } else {
2935 break;
2936 }
2937 }
2938 loaded++;
2939 }
2940
2941 err = ERR_peek_last_error();
2942 if ((filetype == SSL_FILETYPE_ASN1) &&
2943 (loaded > 0) &&
2944 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2945 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2946 /* EOF ASN1 file, not an error */
2947 ERR_clear_error();
2948 retval = 0;
2949 } else if ((filetype == SSL_FILETYPE_PEM) &&
2950 (loaded > 0) &&
2951 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2952 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2953 /* EOF PEM file, not an error */
2954 ERR_clear_error();
2955 retval = 0;
2956 } else {
2957 _setSSLError(NULL, 0, __FILE__, __LINE__);
2958 retval = -1;
2959 }
2960
2961 BIO_free(biobuf);
2962 return retval;
2963}
2964
2965
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002966/*[clinic input]
2967_ssl._SSLContext.load_verify_locations
2968 cafile: object = NULL
2969 capath: object = NULL
2970 cadata: object = NULL
2971
2972[clinic start generated code]*/
2973
Antoine Pitrou152efa22010-05-16 18:19:27 +00002974static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002975_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
2976 PyObject *cafile,
2977 PyObject *capath,
2978 PyObject *cadata)
2979/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002980{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002981 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2982 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002983 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002984
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002985 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002986 if (cafile == Py_None)
2987 cafile = NULL;
2988 if (capath == Py_None)
2989 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002990 if (cadata == Py_None)
2991 cadata = NULL;
2992
2993 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002994 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002995 "cafile, capath and cadata cannot be all omitted");
2996 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002997 }
2998 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2999 PyErr_SetString(PyExc_TypeError,
3000 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003001 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003002 }
3003 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003004 PyErr_SetString(PyExc_TypeError,
3005 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003006 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003007 }
Christian Heimesefff7062013-11-21 03:35:02 +01003008
3009 /* validata cadata type and load cadata */
3010 if (cadata) {
3011 Py_buffer buf;
3012 PyObject *cadata_ascii = NULL;
3013
3014 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3015 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3016 PyBuffer_Release(&buf);
3017 PyErr_SetString(PyExc_TypeError,
3018 "cadata should be a contiguous buffer with "
3019 "a single dimension");
3020 goto error;
3021 }
3022 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3023 PyBuffer_Release(&buf);
3024 if (r == -1) {
3025 goto error;
3026 }
3027 } else {
3028 PyErr_Clear();
3029 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3030 if (cadata_ascii == NULL) {
3031 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003032 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003033 "bytes-like object");
3034 goto error;
3035 }
3036 r = _add_ca_certs(self,
3037 PyBytes_AS_STRING(cadata_ascii),
3038 PyBytes_GET_SIZE(cadata_ascii),
3039 SSL_FILETYPE_PEM);
3040 Py_DECREF(cadata_ascii);
3041 if (r == -1) {
3042 goto error;
3043 }
3044 }
3045 }
3046
3047 /* load cafile or capath */
3048 if (cafile || capath) {
3049 if (cafile)
3050 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3051 if (capath)
3052 capath_buf = PyBytes_AS_STRING(capath_bytes);
3053 PySSL_BEGIN_ALLOW_THREADS
3054 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3055 PySSL_END_ALLOW_THREADS
3056 if (r != 1) {
3057 ok = 0;
3058 if (errno != 0) {
3059 ERR_clear_error();
3060 PyErr_SetFromErrno(PyExc_IOError);
3061 }
3062 else {
3063 _setSSLError(NULL, 0, __FILE__, __LINE__);
3064 }
3065 goto error;
3066 }
3067 }
3068 goto end;
3069
3070 error:
3071 ok = 0;
3072 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003073 Py_XDECREF(cafile_bytes);
3074 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003075 if (ok) {
3076 Py_RETURN_NONE;
3077 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003078 return NULL;
3079 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003080}
3081
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003082/*[clinic input]
3083_ssl._SSLContext.load_dh_params
3084 path as filepath: object
3085 /
3086
3087[clinic start generated code]*/
3088
Antoine Pitrou152efa22010-05-16 18:19:27 +00003089static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003090_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3091/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003092{
3093 FILE *f;
3094 DH *dh;
3095
Victor Stinnerdaf45552013-08-28 00:53:59 +02003096 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003097 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003098 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003099
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003100 errno = 0;
3101 PySSL_BEGIN_ALLOW_THREADS
3102 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003103 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003104 PySSL_END_ALLOW_THREADS
3105 if (dh == NULL) {
3106 if (errno != 0) {
3107 ERR_clear_error();
3108 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3109 }
3110 else {
3111 _setSSLError(NULL, 0, __FILE__, __LINE__);
3112 }
3113 return NULL;
3114 }
3115 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3116 _setSSLError(NULL, 0, __FILE__, __LINE__);
3117 DH_free(dh);
3118 Py_RETURN_NONE;
3119}
3120
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003121/*[clinic input]
3122_ssl._SSLContext._wrap_socket
3123 sock: object(subclass_of="PySocketModule.Sock_Type")
3124 server_side: int
3125 server_hostname as hostname_obj: object = None
3126
3127[clinic start generated code]*/
3128
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003129static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003130_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3131 int server_side, PyObject *hostname_obj)
3132/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003133{
Antoine Pitroud5323212010-10-22 18:19:07 +00003134 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003135 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003136
Antoine Pitroud5323212010-10-22 18:19:07 +00003137 /* server_hostname is either None (or absent), or to be encoded
3138 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003139 if (hostname_obj != Py_None) {
3140 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003141 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003142 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003143
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003144 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3145 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003146 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003147 if (hostname != NULL)
3148 PyMem_Free(hostname);
3149 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003150}
3151
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003152/*[clinic input]
3153_ssl._SSLContext._wrap_bio
3154 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3155 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3156 server_side: int
3157 server_hostname as hostname_obj: object = None
3158
3159[clinic start generated code]*/
3160
Antoine Pitroub0182c82010-10-12 20:09:02 +00003161static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003162_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3163 PySSLMemoryBIO *outgoing, int server_side,
3164 PyObject *hostname_obj)
3165/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003166{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003167 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003168 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003169
3170 /* server_hostname is either None (or absent), or to be encoded
3171 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003172 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003173 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3174 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003175 }
3176
3177 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3178 incoming, outgoing);
3179
3180 PyMem_Free(hostname);
3181 return res;
3182}
3183
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003184/*[clinic input]
3185_ssl._SSLContext.session_stats
3186[clinic start generated code]*/
3187
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003188static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003189_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3190/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003191{
3192 int r;
3193 PyObject *value, *stats = PyDict_New();
3194 if (!stats)
3195 return NULL;
3196
3197#define ADD_STATS(SSL_NAME, KEY_NAME) \
3198 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3199 if (value == NULL) \
3200 goto error; \
3201 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3202 Py_DECREF(value); \
3203 if (r < 0) \
3204 goto error;
3205
3206 ADD_STATS(number, "number");
3207 ADD_STATS(connect, "connect");
3208 ADD_STATS(connect_good, "connect_good");
3209 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3210 ADD_STATS(accept, "accept");
3211 ADD_STATS(accept_good, "accept_good");
3212 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3213 ADD_STATS(accept, "accept");
3214 ADD_STATS(hits, "hits");
3215 ADD_STATS(misses, "misses");
3216 ADD_STATS(timeouts, "timeouts");
3217 ADD_STATS(cache_full, "cache_full");
3218
3219#undef ADD_STATS
3220
3221 return stats;
3222
3223error:
3224 Py_DECREF(stats);
3225 return NULL;
3226}
3227
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003228/*[clinic input]
3229_ssl._SSLContext.set_default_verify_paths
3230[clinic start generated code]*/
3231
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003232static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003233_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3234/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003235{
3236 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3237 _setSSLError(NULL, 0, __FILE__, __LINE__);
3238 return NULL;
3239 }
3240 Py_RETURN_NONE;
3241}
3242
Antoine Pitrou501da612011-12-21 09:27:41 +01003243#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003244/*[clinic input]
3245_ssl._SSLContext.set_ecdh_curve
3246 name: object
3247 /
3248
3249[clinic start generated code]*/
3250
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003251static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003252_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3253/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003254{
3255 PyObject *name_bytes;
3256 int nid;
3257 EC_KEY *key;
3258
3259 if (!PyUnicode_FSConverter(name, &name_bytes))
3260 return NULL;
3261 assert(PyBytes_Check(name_bytes));
3262 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3263 Py_DECREF(name_bytes);
3264 if (nid == 0) {
3265 PyErr_Format(PyExc_ValueError,
3266 "unknown elliptic curve name %R", name);
3267 return NULL;
3268 }
3269 key = EC_KEY_new_by_curve_name(nid);
3270 if (key == NULL) {
3271 _setSSLError(NULL, 0, __FILE__, __LINE__);
3272 return NULL;
3273 }
3274 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3275 EC_KEY_free(key);
3276 Py_RETURN_NONE;
3277}
Antoine Pitrou501da612011-12-21 09:27:41 +01003278#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003279
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003280#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003281static int
3282_servername_callback(SSL *s, int *al, void *args)
3283{
3284 int ret;
3285 PySSLContext *ssl_ctx = (PySSLContext *) args;
3286 PySSLSocket *ssl;
3287 PyObject *servername_o;
3288 PyObject *servername_idna;
3289 PyObject *result;
3290 /* The high-level ssl.SSLSocket object */
3291 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003292 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003293#ifdef WITH_THREAD
3294 PyGILState_STATE gstate = PyGILState_Ensure();
3295#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003296
3297 if (ssl_ctx->set_hostname == NULL) {
3298 /* remove race condition in this the call back while if removing the
3299 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003300#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003301 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003302#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003303 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003304 }
3305
3306 ssl = SSL_get_app_data(s);
3307 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003308
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003309 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003310 * SSL connection and that has a .context attribute that can be changed to
3311 * identify the requested hostname. Since the official API is the Python
3312 * level API we want to pass the callback a Python level object rather than
3313 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3314 * SSLObject) that will be passed. Otherwise if there's a socket then that
3315 * will be passed. If both do not exist only then the C-level object is
3316 * passed. */
3317 if (ssl->owner)
3318 ssl_socket = PyWeakref_GetObject(ssl->owner);
3319 else if (ssl->Socket)
3320 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3321 else
3322 ssl_socket = (PyObject *) ssl;
3323
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003324 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003325 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003326 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003327
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003328 if (servername == NULL) {
3329 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3330 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003331 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003332 else {
3333 servername_o = PyBytes_FromString(servername);
3334 if (servername_o == NULL) {
3335 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3336 goto error;
3337 }
3338 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3339 if (servername_idna == NULL) {
3340 PyErr_WriteUnraisable(servername_o);
3341 Py_DECREF(servername_o);
3342 goto error;
3343 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003344 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003345 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3346 servername_idna, ssl_ctx, NULL);
3347 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003348 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003349 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003350
3351 if (result == NULL) {
3352 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3353 *al = SSL_AD_HANDSHAKE_FAILURE;
3354 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3355 }
3356 else {
3357 if (result != Py_None) {
3358 *al = (int) PyLong_AsLong(result);
3359 if (PyErr_Occurred()) {
3360 PyErr_WriteUnraisable(result);
3361 *al = SSL_AD_INTERNAL_ERROR;
3362 }
3363 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3364 }
3365 else {
3366 ret = SSL_TLSEXT_ERR_OK;
3367 }
3368 Py_DECREF(result);
3369 }
3370
Stefan Krah20d60802013-01-17 17:07:17 +01003371#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003372 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003373#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003374 return ret;
3375
3376error:
3377 Py_DECREF(ssl_socket);
3378 *al = SSL_AD_INTERNAL_ERROR;
3379 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003380#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003381 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003382#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003383 return ret;
3384}
Antoine Pitroua5963382013-03-30 16:39:00 +01003385#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003386
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003387/*[clinic input]
3388_ssl._SSLContext.set_servername_callback
3389 method as cb: object
3390 /
3391
3392Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3393
3394If the argument is None then the callback is disabled. The method is called
3395with the SSLSocket, the server name as a string, and the SSLContext object.
3396See RFC 6066 for details of the SNI extension.
3397[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003398
3399static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003400_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3401/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003402{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003403#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003404 Py_CLEAR(self->set_hostname);
3405 if (cb == Py_None) {
3406 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3407 }
3408 else {
3409 if (!PyCallable_Check(cb)) {
3410 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3411 PyErr_SetString(PyExc_TypeError,
3412 "not a callable object");
3413 return NULL;
3414 }
3415 Py_INCREF(cb);
3416 self->set_hostname = cb;
3417 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3418 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3419 }
3420 Py_RETURN_NONE;
3421#else
3422 PyErr_SetString(PyExc_NotImplementedError,
3423 "The TLS extension servername callback, "
3424 "SSL_CTX_set_tlsext_servername_callback, "
3425 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003426 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003427#endif
3428}
3429
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003430/*[clinic input]
3431_ssl._SSLContext.cert_store_stats
3432
3433Returns quantities of loaded X.509 certificates.
3434
3435X.509 certificates with a CA extension and certificate revocation lists
3436inside the context's cert store.
3437
3438NOTE: Certificates in a capath directory aren't loaded unless they have
3439been used at least once.
3440[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003441
3442static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003443_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3444/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003445{
3446 X509_STORE *store;
3447 X509_OBJECT *obj;
3448 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3449
3450 store = SSL_CTX_get_cert_store(self->ctx);
3451 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3452 obj = sk_X509_OBJECT_value(store->objs, i);
3453 switch (obj->type) {
3454 case X509_LU_X509:
3455 x509++;
3456 if (X509_check_ca(obj->data.x509)) {
3457 ca++;
3458 }
3459 break;
3460 case X509_LU_CRL:
3461 crl++;
3462 break;
3463 case X509_LU_PKEY:
3464 pkey++;
3465 break;
3466 default:
3467 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3468 * As far as I can tell they are internal states and never
3469 * stored in a cert store */
3470 break;
3471 }
3472 }
3473 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3474 "x509_ca", ca);
3475}
3476
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003477/*[clinic input]
3478_ssl._SSLContext.get_ca_certs
3479 binary_form: bool = False
3480
3481Returns a list of dicts with information of loaded CA certs.
3482
3483If the optional argument is True, returns a DER-encoded copy of the CA
3484certificate.
3485
3486NOTE: Certificates in a capath directory aren't loaded unless they have
3487been used at least once.
3488[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003489
3490static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003491_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3492/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003493{
3494 X509_STORE *store;
3495 PyObject *ci = NULL, *rlist = NULL;
3496 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003497
3498 if ((rlist = PyList_New(0)) == NULL) {
3499 return NULL;
3500 }
3501
3502 store = SSL_CTX_get_cert_store(self->ctx);
3503 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3504 X509_OBJECT *obj;
3505 X509 *cert;
3506
3507 obj = sk_X509_OBJECT_value(store->objs, i);
3508 if (obj->type != X509_LU_X509) {
3509 /* not a x509 cert */
3510 continue;
3511 }
3512 /* CA for any purpose */
3513 cert = obj->data.x509;
3514 if (!X509_check_ca(cert)) {
3515 continue;
3516 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003517 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003518 ci = _certificate_to_der(cert);
3519 } else {
3520 ci = _decode_certificate(cert);
3521 }
3522 if (ci == NULL) {
3523 goto error;
3524 }
3525 if (PyList_Append(rlist, ci) == -1) {
3526 goto error;
3527 }
3528 Py_CLEAR(ci);
3529 }
3530 return rlist;
3531
3532 error:
3533 Py_XDECREF(ci);
3534 Py_XDECREF(rlist);
3535 return NULL;
3536}
3537
3538
Antoine Pitrou152efa22010-05-16 18:19:27 +00003539static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003540 {"check_hostname", (getter) get_check_hostname,
3541 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003542 {"options", (getter) get_options,
3543 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003544 {"verify_flags", (getter) get_verify_flags,
3545 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003546 {"verify_mode", (getter) get_verify_mode,
3547 (setter) set_verify_mode, NULL},
3548 {NULL}, /* sentinel */
3549};
3550
3551static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003552 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
3553 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
3554 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
3555 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
3556 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
3557 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
3558 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
3559 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
3560 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
3561 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
3562 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
3563 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
3564 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
3565 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00003566 {NULL, NULL} /* sentinel */
3567};
3568
3569static PyTypeObject PySSLContext_Type = {
3570 PyVarObject_HEAD_INIT(NULL, 0)
3571 "_ssl._SSLContext", /*tp_name*/
3572 sizeof(PySSLContext), /*tp_basicsize*/
3573 0, /*tp_itemsize*/
3574 (destructor)context_dealloc, /*tp_dealloc*/
3575 0, /*tp_print*/
3576 0, /*tp_getattr*/
3577 0, /*tp_setattr*/
3578 0, /*tp_reserved*/
3579 0, /*tp_repr*/
3580 0, /*tp_as_number*/
3581 0, /*tp_as_sequence*/
3582 0, /*tp_as_mapping*/
3583 0, /*tp_hash*/
3584 0, /*tp_call*/
3585 0, /*tp_str*/
3586 0, /*tp_getattro*/
3587 0, /*tp_setattro*/
3588 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003589 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003590 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003591 (traverseproc) context_traverse, /*tp_traverse*/
3592 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003593 0, /*tp_richcompare*/
3594 0, /*tp_weaklistoffset*/
3595 0, /*tp_iter*/
3596 0, /*tp_iternext*/
3597 context_methods, /*tp_methods*/
3598 0, /*tp_members*/
3599 context_getsetlist, /*tp_getset*/
3600 0, /*tp_base*/
3601 0, /*tp_dict*/
3602 0, /*tp_descr_get*/
3603 0, /*tp_descr_set*/
3604 0, /*tp_dictoffset*/
3605 0, /*tp_init*/
3606 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003607 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003608};
3609
3610
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003611/*
3612 * MemoryBIO objects
3613 */
3614
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003615/*[clinic input]
3616@classmethod
3617_ssl.MemoryBIO.__new__
3618
3619[clinic start generated code]*/
3620
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003621static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003622_ssl_MemoryBIO_impl(PyTypeObject *type)
3623/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003624{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003625 BIO *bio;
3626 PySSLMemoryBIO *self;
3627
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003628 bio = BIO_new(BIO_s_mem());
3629 if (bio == NULL) {
3630 PyErr_SetString(PySSLErrorObject,
3631 "failed to allocate BIO");
3632 return NULL;
3633 }
3634 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3635 * just that no data is currently available. The SSL routines should retry
3636 * the read, which we can achieve by calling BIO_set_retry_read(). */
3637 BIO_set_retry_read(bio);
3638 BIO_set_mem_eof_return(bio, -1);
3639
3640 assert(type != NULL && type->tp_alloc != NULL);
3641 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3642 if (self == NULL) {
3643 BIO_free(bio);
3644 return NULL;
3645 }
3646 self->bio = bio;
3647 self->eof_written = 0;
3648
3649 return (PyObject *) self;
3650}
3651
3652static void
3653memory_bio_dealloc(PySSLMemoryBIO *self)
3654{
3655 BIO_free(self->bio);
3656 Py_TYPE(self)->tp_free(self);
3657}
3658
3659static PyObject *
3660memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3661{
3662 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3663}
3664
3665PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3666"The number of bytes pending in the memory BIO.");
3667
3668static PyObject *
3669memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3670{
3671 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3672 && self->eof_written);
3673}
3674
3675PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3676"Whether the memory BIO is at EOF.");
3677
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003678/*[clinic input]
3679_ssl.MemoryBIO.read
3680 size as len: int = -1
3681 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003682
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003683Read up to size bytes from the memory BIO.
3684
3685If size is not specified, read the entire buffer.
3686If the return value is an empty bytes instance, this means either
3687EOF or that no data is available. Use the "eof" property to
3688distinguish between the two.
3689[clinic start generated code]*/
3690
3691static PyObject *
3692_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
3693/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
3694{
3695 int avail, nbytes;
3696 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003697
3698 avail = BIO_ctrl_pending(self->bio);
3699 if ((len < 0) || (len > avail))
3700 len = avail;
3701
3702 result = PyBytes_FromStringAndSize(NULL, len);
3703 if ((result == NULL) || (len == 0))
3704 return result;
3705
3706 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3707 /* There should never be any short reads but check anyway. */
3708 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3709 Py_DECREF(result);
3710 return NULL;
3711 }
3712
3713 return result;
3714}
3715
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003716/*[clinic input]
3717_ssl.MemoryBIO.write
3718 b: Py_buffer
3719 /
3720
3721Writes the bytes b into the memory BIO.
3722
3723Returns the number of bytes written.
3724[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003725
3726static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003727_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
3728/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003729{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003730 int nbytes;
3731
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003732 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003733 PyErr_Format(PyExc_OverflowError,
3734 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003735 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003736 }
3737
3738 if (self->eof_written) {
3739 PyErr_SetString(PySSLErrorObject,
3740 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003741 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003742 }
3743
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003744 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003745 if (nbytes < 0) {
3746 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003747 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003748 }
3749
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003750 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003751}
3752
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003753/*[clinic input]
3754_ssl.MemoryBIO.write_eof
3755
3756Write an EOF marker to the memory BIO.
3757
3758When all data has been read, the "eof" property will be True.
3759[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003760
3761static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003762_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
3763/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003764{
3765 self->eof_written = 1;
3766 /* After an EOF is written, a zero return from read() should be a real EOF
3767 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3768 BIO_clear_retry_flags(self->bio);
3769 BIO_set_mem_eof_return(self->bio, 0);
3770
3771 Py_RETURN_NONE;
3772}
3773
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003774static PyGetSetDef memory_bio_getsetlist[] = {
3775 {"pending", (getter) memory_bio_get_pending, NULL,
3776 PySSL_memory_bio_pending_doc},
3777 {"eof", (getter) memory_bio_get_eof, NULL,
3778 PySSL_memory_bio_eof_doc},
3779 {NULL}, /* sentinel */
3780};
3781
3782static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003783 _SSL_MEMORYBIO_READ_METHODDEF
3784 _SSL_MEMORYBIO_WRITE_METHODDEF
3785 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003786 {NULL, NULL} /* sentinel */
3787};
3788
3789static PyTypeObject PySSLMemoryBIO_Type = {
3790 PyVarObject_HEAD_INIT(NULL, 0)
3791 "_ssl.MemoryBIO", /*tp_name*/
3792 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3793 0, /*tp_itemsize*/
3794 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3795 0, /*tp_print*/
3796 0, /*tp_getattr*/
3797 0, /*tp_setattr*/
3798 0, /*tp_reserved*/
3799 0, /*tp_repr*/
3800 0, /*tp_as_number*/
3801 0, /*tp_as_sequence*/
3802 0, /*tp_as_mapping*/
3803 0, /*tp_hash*/
3804 0, /*tp_call*/
3805 0, /*tp_str*/
3806 0, /*tp_getattro*/
3807 0, /*tp_setattro*/
3808 0, /*tp_as_buffer*/
3809 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3810 0, /*tp_doc*/
3811 0, /*tp_traverse*/
3812 0, /*tp_clear*/
3813 0, /*tp_richcompare*/
3814 0, /*tp_weaklistoffset*/
3815 0, /*tp_iter*/
3816 0, /*tp_iternext*/
3817 memory_bio_methods, /*tp_methods*/
3818 0, /*tp_members*/
3819 memory_bio_getsetlist, /*tp_getset*/
3820 0, /*tp_base*/
3821 0, /*tp_dict*/
3822 0, /*tp_descr_get*/
3823 0, /*tp_descr_set*/
3824 0, /*tp_dictoffset*/
3825 0, /*tp_init*/
3826 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003827 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003828};
3829
Antoine Pitrou152efa22010-05-16 18:19:27 +00003830
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003831/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003832/*[clinic input]
3833_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07003834 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003835 entropy: double
3836 /
3837
3838Mix string into the OpenSSL PRNG state.
3839
3840entropy (a float) is a lower bound on the entropy contained in
3841string. See RFC 1750.
3842[clinic start generated code]*/
3843
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003844static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003845_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
3846/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003847{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02003848 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003849 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003850
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003851 buf = (const char *)view->buf;
3852 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003853 do {
3854 written = Py_MIN(len, INT_MAX);
3855 RAND_add(buf, (int)written, entropy);
3856 buf += written;
3857 len -= written;
3858 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003859 Py_INCREF(Py_None);
3860 return Py_None;
3861}
3862
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003863static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003864PySSL_RAND(int len, int pseudo)
3865{
3866 int ok;
3867 PyObject *bytes;
3868 unsigned long err;
3869 const char *errstr;
3870 PyObject *v;
3871
Victor Stinner1e81a392013-12-19 16:47:04 +01003872 if (len < 0) {
3873 PyErr_SetString(PyExc_ValueError, "num must be positive");
3874 return NULL;
3875 }
3876
Victor Stinner99c8b162011-05-24 12:05:19 +02003877 bytes = PyBytes_FromStringAndSize(NULL, len);
3878 if (bytes == NULL)
3879 return NULL;
3880 if (pseudo) {
3881 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3882 if (ok == 0 || ok == 1)
3883 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3884 }
3885 else {
3886 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3887 if (ok == 1)
3888 return bytes;
3889 }
3890 Py_DECREF(bytes);
3891
3892 err = ERR_get_error();
3893 errstr = ERR_reason_error_string(err);
3894 v = Py_BuildValue("(ks)", err, errstr);
3895 if (v != NULL) {
3896 PyErr_SetObject(PySSLErrorObject, v);
3897 Py_DECREF(v);
3898 }
3899 return NULL;
3900}
3901
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003902/*[clinic input]
3903_ssl.RAND_bytes
3904 n: int
3905 /
3906
3907Generate n cryptographically strong pseudo-random bytes.
3908[clinic start generated code]*/
3909
Victor Stinner99c8b162011-05-24 12:05:19 +02003910static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003911_ssl_RAND_bytes_impl(PyObject *module, int n)
3912/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003913{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003914 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02003915}
3916
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003917/*[clinic input]
3918_ssl.RAND_pseudo_bytes
3919 n: int
3920 /
3921
3922Generate n pseudo-random bytes.
3923
3924Return a pair (bytes, is_cryptographic). is_cryptographic is True
3925if the bytes generated are cryptographically strong.
3926[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003927
3928static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003929_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
3930/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003931{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003932 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02003933}
3934
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003935/*[clinic input]
3936_ssl.RAND_status
3937
3938Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
3939
3940It is necessary to seed the PRNG with RAND_add() on some platforms before
3941using the ssl() function.
3942[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003943
3944static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003945_ssl_RAND_status_impl(PyObject *module)
3946/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003947{
Christian Heimes217cfd12007-12-02 14:31:20 +00003948 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003949}
3950
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07003951#ifndef OPENSSL_NO_EGD
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003952/*[clinic input]
3953_ssl.RAND_egd
3954 path: object(converter="PyUnicode_FSConverter")
3955 /
3956
3957Queries the entropy gather daemon (EGD) on the socket named by 'path'.
3958
3959Returns number of bytes read. Raises SSLError if connection to EGD
3960fails or if it does not provide enough data to seed PRNG.
3961[clinic start generated code]*/
3962
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003963static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003964_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
3965/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003966{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003967 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003968 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003969 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003970 PyErr_SetString(PySSLErrorObject,
3971 "EGD connection failed or EGD did not return "
3972 "enough data to seed the PRNG");
3973 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003974 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003975 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003976}
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07003977#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003978
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003979
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003980
3981/*[clinic input]
3982_ssl.get_default_verify_paths
3983
3984Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
3985
3986The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
3987[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02003988
3989static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003990_ssl_get_default_verify_paths_impl(PyObject *module)
3991/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02003992{
3993 PyObject *ofile_env = NULL;
3994 PyObject *ofile = NULL;
3995 PyObject *odir_env = NULL;
3996 PyObject *odir = NULL;
3997
Benjamin Petersond113c962015-07-18 10:59:13 -07003998#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02003999 const char *tmp = (info); \
4000 target = NULL; \
4001 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4002 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4003 target = PyBytes_FromString(tmp); } \
4004 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004005 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004006
Benjamin Petersond113c962015-07-18 10:59:13 -07004007 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4008 CONVERT(X509_get_default_cert_file(), ofile);
4009 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4010 CONVERT(X509_get_default_cert_dir(), odir);
4011#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004012
Christian Heimes200bb1b2013-06-14 15:14:29 +02004013 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004014
4015 error:
4016 Py_XDECREF(ofile_env);
4017 Py_XDECREF(ofile);
4018 Py_XDECREF(odir_env);
4019 Py_XDECREF(odir);
4020 return NULL;
4021}
4022
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004023static PyObject*
4024asn1obj2py(ASN1_OBJECT *obj)
4025{
4026 int nid;
4027 const char *ln, *sn;
4028 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004029 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004030
4031 nid = OBJ_obj2nid(obj);
4032 if (nid == NID_undef) {
4033 PyErr_Format(PyExc_ValueError, "Unknown object");
4034 return NULL;
4035 }
4036 sn = OBJ_nid2sn(nid);
4037 ln = OBJ_nid2ln(nid);
4038 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4039 if (buflen < 0) {
4040 _setSSLError(NULL, 0, __FILE__, __LINE__);
4041 return NULL;
4042 }
4043 if (buflen) {
4044 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4045 } else {
4046 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4047 }
4048}
4049
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004050/*[clinic input]
4051_ssl.txt2obj
4052 txt: str
4053 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004054
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004055Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4056
4057By default objects are looked up by OID. With name=True short and
4058long name are also matched.
4059[clinic start generated code]*/
4060
4061static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004062_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4063/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004064{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004065 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004066 ASN1_OBJECT *obj;
4067
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004068 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4069 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004070 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004071 return NULL;
4072 }
4073 result = asn1obj2py(obj);
4074 ASN1_OBJECT_free(obj);
4075 return result;
4076}
4077
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004078/*[clinic input]
4079_ssl.nid2obj
4080 nid: int
4081 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004082
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004083Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4084[clinic start generated code]*/
4085
4086static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004087_ssl_nid2obj_impl(PyObject *module, int nid)
4088/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004089{
4090 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004091 ASN1_OBJECT *obj;
4092
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004093 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004094 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004095 return NULL;
4096 }
4097 obj = OBJ_nid2obj(nid);
4098 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004099 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004100 return NULL;
4101 }
4102 result = asn1obj2py(obj);
4103 ASN1_OBJECT_free(obj);
4104 return result;
4105}
4106
Christian Heimes46bebee2013-06-09 19:03:31 +02004107#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004108
4109static PyObject*
4110certEncodingType(DWORD encodingType)
4111{
4112 static PyObject *x509_asn = NULL;
4113 static PyObject *pkcs_7_asn = NULL;
4114
4115 if (x509_asn == NULL) {
4116 x509_asn = PyUnicode_InternFromString("x509_asn");
4117 if (x509_asn == NULL)
4118 return NULL;
4119 }
4120 if (pkcs_7_asn == NULL) {
4121 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4122 if (pkcs_7_asn == NULL)
4123 return NULL;
4124 }
4125 switch(encodingType) {
4126 case X509_ASN_ENCODING:
4127 Py_INCREF(x509_asn);
4128 return x509_asn;
4129 case PKCS_7_ASN_ENCODING:
4130 Py_INCREF(pkcs_7_asn);
4131 return pkcs_7_asn;
4132 default:
4133 return PyLong_FromLong(encodingType);
4134 }
4135}
4136
4137static PyObject*
4138parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4139{
4140 CERT_ENHKEY_USAGE *usage;
4141 DWORD size, error, i;
4142 PyObject *retval;
4143
4144 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4145 error = GetLastError();
4146 if (error == CRYPT_E_NOT_FOUND) {
4147 Py_RETURN_TRUE;
4148 }
4149 return PyErr_SetFromWindowsErr(error);
4150 }
4151
4152 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4153 if (usage == NULL) {
4154 return PyErr_NoMemory();
4155 }
4156
4157 /* Now get the actual enhanced usage property */
4158 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4159 PyMem_Free(usage);
4160 error = GetLastError();
4161 if (error == CRYPT_E_NOT_FOUND) {
4162 Py_RETURN_TRUE;
4163 }
4164 return PyErr_SetFromWindowsErr(error);
4165 }
4166 retval = PySet_New(NULL);
4167 if (retval == NULL) {
4168 goto error;
4169 }
4170 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4171 if (usage->rgpszUsageIdentifier[i]) {
4172 PyObject *oid;
4173 int err;
4174 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4175 if (oid == NULL) {
4176 Py_CLEAR(retval);
4177 goto error;
4178 }
4179 err = PySet_Add(retval, oid);
4180 Py_DECREF(oid);
4181 if (err == -1) {
4182 Py_CLEAR(retval);
4183 goto error;
4184 }
4185 }
4186 }
4187 error:
4188 PyMem_Free(usage);
4189 return retval;
4190}
4191
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004192/*[clinic input]
4193_ssl.enum_certificates
4194 store_name: str
4195
4196Retrieve certificates from Windows' cert store.
4197
4198store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4199more cert storages, too. The function returns a list of (bytes,
4200encoding_type, trust) tuples. The encoding_type flag can be interpreted
4201with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4202a set of OIDs or the boolean True.
4203[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004204
Christian Heimes46bebee2013-06-09 19:03:31 +02004205static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004206_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4207/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004208{
Christian Heimes46bebee2013-06-09 19:03:31 +02004209 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004210 PCCERT_CONTEXT pCertCtx = NULL;
4211 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004212 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004213
Christian Heimes44109d72013-11-22 01:51:30 +01004214 result = PyList_New(0);
4215 if (result == NULL) {
4216 return NULL;
4217 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004218 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4219 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4220 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004221 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004222 Py_DECREF(result);
4223 return PyErr_SetFromWindowsErr(GetLastError());
4224 }
4225
Christian Heimes44109d72013-11-22 01:51:30 +01004226 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4227 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4228 pCertCtx->cbCertEncoded);
4229 if (!cert) {
4230 Py_CLEAR(result);
4231 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004232 }
Christian Heimes44109d72013-11-22 01:51:30 +01004233 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4234 Py_CLEAR(result);
4235 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004236 }
Christian Heimes44109d72013-11-22 01:51:30 +01004237 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4238 if (keyusage == Py_True) {
4239 Py_DECREF(keyusage);
4240 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004241 }
Christian Heimes44109d72013-11-22 01:51:30 +01004242 if (keyusage == NULL) {
4243 Py_CLEAR(result);
4244 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004245 }
Christian Heimes44109d72013-11-22 01:51:30 +01004246 if ((tup = PyTuple_New(3)) == NULL) {
4247 Py_CLEAR(result);
4248 break;
4249 }
4250 PyTuple_SET_ITEM(tup, 0, cert);
4251 cert = NULL;
4252 PyTuple_SET_ITEM(tup, 1, enc);
4253 enc = NULL;
4254 PyTuple_SET_ITEM(tup, 2, keyusage);
4255 keyusage = NULL;
4256 if (PyList_Append(result, tup) < 0) {
4257 Py_CLEAR(result);
4258 break;
4259 }
4260 Py_CLEAR(tup);
4261 }
4262 if (pCertCtx) {
4263 /* loop ended with an error, need to clean up context manually */
4264 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004265 }
4266
4267 /* In error cases cert, enc and tup may not be NULL */
4268 Py_XDECREF(cert);
4269 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004270 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004271 Py_XDECREF(tup);
4272
4273 if (!CertCloseStore(hStore, 0)) {
4274 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004275 Py_XDECREF(result);
4276 return PyErr_SetFromWindowsErr(GetLastError());
4277 }
4278 return result;
4279}
4280
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004281/*[clinic input]
4282_ssl.enum_crls
4283 store_name: str
4284
4285Retrieve CRLs from Windows' cert store.
4286
4287store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4288more cert storages, too. The function returns a list of (bytes,
4289encoding_type) tuples. The encoding_type flag can be interpreted with
4290X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4291[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004292
4293static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004294_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4295/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004296{
Christian Heimes44109d72013-11-22 01:51:30 +01004297 HCERTSTORE hStore = NULL;
4298 PCCRL_CONTEXT pCrlCtx = NULL;
4299 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4300 PyObject *result = NULL;
4301
Christian Heimes44109d72013-11-22 01:51:30 +01004302 result = PyList_New(0);
4303 if (result == NULL) {
4304 return NULL;
4305 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004306 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4307 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4308 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004309 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004310 Py_DECREF(result);
4311 return PyErr_SetFromWindowsErr(GetLastError());
4312 }
Christian Heimes44109d72013-11-22 01:51:30 +01004313
4314 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4315 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4316 pCrlCtx->cbCrlEncoded);
4317 if (!crl) {
4318 Py_CLEAR(result);
4319 break;
4320 }
4321 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4322 Py_CLEAR(result);
4323 break;
4324 }
4325 if ((tup = PyTuple_New(2)) == NULL) {
4326 Py_CLEAR(result);
4327 break;
4328 }
4329 PyTuple_SET_ITEM(tup, 0, crl);
4330 crl = NULL;
4331 PyTuple_SET_ITEM(tup, 1, enc);
4332 enc = NULL;
4333
4334 if (PyList_Append(result, tup) < 0) {
4335 Py_CLEAR(result);
4336 break;
4337 }
4338 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004339 }
Christian Heimes44109d72013-11-22 01:51:30 +01004340 if (pCrlCtx) {
4341 /* loop ended with an error, need to clean up context manually */
4342 CertFreeCRLContext(pCrlCtx);
4343 }
4344
4345 /* In error cases cert, enc and tup may not be NULL */
4346 Py_XDECREF(crl);
4347 Py_XDECREF(enc);
4348 Py_XDECREF(tup);
4349
4350 if (!CertCloseStore(hStore, 0)) {
4351 /* This error case might shadow another exception.*/
4352 Py_XDECREF(result);
4353 return PyErr_SetFromWindowsErr(GetLastError());
4354 }
4355 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004356}
Christian Heimes44109d72013-11-22 01:51:30 +01004357
4358#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004359
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004360/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004361static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004362 _SSL__TEST_DECODE_CERT_METHODDEF
4363 _SSL_RAND_ADD_METHODDEF
4364 _SSL_RAND_BYTES_METHODDEF
4365 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4366 _SSL_RAND_EGD_METHODDEF
4367 _SSL_RAND_STATUS_METHODDEF
4368 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
4369 _SSL_ENUM_CERTIFICATES_METHODDEF
4370 _SSL_ENUM_CRLS_METHODDEF
4371 _SSL_TXT2OBJ_METHODDEF
4372 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004373 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004374};
4375
4376
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004377#ifdef WITH_THREAD
4378
4379/* an implementation of OpenSSL threading operations in terms
4380 of the Python C thread library */
4381
4382static PyThread_type_lock *_ssl_locks = NULL;
4383
Christian Heimes4d98ca92013-08-19 17:36:29 +02004384#if OPENSSL_VERSION_NUMBER >= 0x10000000
4385/* use new CRYPTO_THREADID API. */
4386static void
4387_ssl_threadid_callback(CRYPTO_THREADID *id)
4388{
4389 CRYPTO_THREADID_set_numeric(id,
4390 (unsigned long)PyThread_get_thread_ident());
4391}
4392#else
4393/* deprecated CRYPTO_set_id_callback() API. */
4394static unsigned long
4395_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004396 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004397}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004398#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004399
Bill Janssen6e027db2007-11-15 22:23:56 +00004400static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004401 (int mode, int n, const char *file, int line) {
4402 /* this function is needed to perform locking on shared data
4403 structures. (Note that OpenSSL uses a number of global data
4404 structures that will be implicitly shared whenever multiple
4405 threads use OpenSSL.) Multi-threaded applications will
4406 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004407
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004408 locking_function() must be able to handle up to
4409 CRYPTO_num_locks() different mutex locks. It sets the n-th
4410 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004411
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004412 file and line are the file number of the function setting the
4413 lock. They can be useful for debugging.
4414 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004415
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004416 if ((_ssl_locks == NULL) ||
4417 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4418 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004419
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004420 if (mode & CRYPTO_LOCK) {
4421 PyThread_acquire_lock(_ssl_locks[n], 1);
4422 } else {
4423 PyThread_release_lock(_ssl_locks[n]);
4424 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004425}
4426
4427static int _setup_ssl_threads(void) {
4428
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004429 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004430
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004431 if (_ssl_locks == NULL) {
4432 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004433 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4434 if (_ssl_locks == NULL) {
4435 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004436 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004437 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004438 memset(_ssl_locks, 0,
4439 sizeof(PyThread_type_lock) * _ssl_locks_count);
4440 for (i = 0; i < _ssl_locks_count; i++) {
4441 _ssl_locks[i] = PyThread_allocate_lock();
4442 if (_ssl_locks[i] == NULL) {
4443 unsigned int j;
4444 for (j = 0; j < i; j++) {
4445 PyThread_free_lock(_ssl_locks[j]);
4446 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004447 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004448 return 0;
4449 }
4450 }
4451 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004452#if OPENSSL_VERSION_NUMBER >= 0x10000000
4453 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4454#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004455 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004456#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004457 }
4458 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004459}
4460
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004461#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004462
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004463PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004464"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004465for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004466
Martin v. Löwis1a214512008-06-11 05:26:20 +00004467
4468static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004469 PyModuleDef_HEAD_INIT,
4470 "_ssl",
4471 module_doc,
4472 -1,
4473 PySSL_methods,
4474 NULL,
4475 NULL,
4476 NULL,
4477 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004478};
4479
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004480
4481static void
4482parse_openssl_version(unsigned long libver,
4483 unsigned int *major, unsigned int *minor,
4484 unsigned int *fix, unsigned int *patch,
4485 unsigned int *status)
4486{
4487 *status = libver & 0xF;
4488 libver >>= 4;
4489 *patch = libver & 0xFF;
4490 libver >>= 8;
4491 *fix = libver & 0xFF;
4492 libver >>= 8;
4493 *minor = libver & 0xFF;
4494 libver >>= 8;
4495 *major = libver & 0xFF;
4496}
4497
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004498PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004499PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004500{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004501 PyObject *m, *d, *r;
4502 unsigned long libver;
4503 unsigned int major, minor, fix, patch, status;
4504 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004505 struct py_ssl_error_code *errcode;
4506 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004507
Antoine Pitrou152efa22010-05-16 18:19:27 +00004508 if (PyType_Ready(&PySSLContext_Type) < 0)
4509 return NULL;
4510 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004511 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004512 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4513 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004514
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004515 m = PyModule_Create(&_sslmodule);
4516 if (m == NULL)
4517 return NULL;
4518 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004519
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004520 /* Load _socket module and its C API */
4521 socket_api = PySocketModule_ImportModuleAndAPI();
4522 if (!socket_api)
4523 return NULL;
4524 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004526 /* Init OpenSSL */
4527 SSL_load_error_strings();
4528 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004529#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004530 /* note that this will start threading if not already started */
4531 if (!_setup_ssl_threads()) {
4532 return NULL;
4533 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004534#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004535 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004536
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004537 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004538 sslerror_type_slots[0].pfunc = PyExc_OSError;
4539 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004540 if (PySSLErrorObject == NULL)
4541 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004542
Antoine Pitrou41032a62011-10-27 23:56:55 +02004543 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4544 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4545 PySSLErrorObject, NULL);
4546 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4547 "ssl.SSLWantReadError", SSLWantReadError_doc,
4548 PySSLErrorObject, NULL);
4549 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4550 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4551 PySSLErrorObject, NULL);
4552 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4553 "ssl.SSLSyscallError", SSLSyscallError_doc,
4554 PySSLErrorObject, NULL);
4555 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4556 "ssl.SSLEOFError", SSLEOFError_doc,
4557 PySSLErrorObject, NULL);
4558 if (PySSLZeroReturnErrorObject == NULL
4559 || PySSLWantReadErrorObject == NULL
4560 || PySSLWantWriteErrorObject == NULL
4561 || PySSLSyscallErrorObject == NULL
4562 || PySSLEOFErrorObject == NULL)
4563 return NULL;
4564 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4565 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4566 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4567 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4568 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4569 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004570 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004571 if (PyDict_SetItemString(d, "_SSLContext",
4572 (PyObject *)&PySSLContext_Type) != 0)
4573 return NULL;
4574 if (PyDict_SetItemString(d, "_SSLSocket",
4575 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004576 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004577 if (PyDict_SetItemString(d, "MemoryBIO",
4578 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4579 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004580 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4581 PY_SSL_ERROR_ZERO_RETURN);
4582 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4583 PY_SSL_ERROR_WANT_READ);
4584 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4585 PY_SSL_ERROR_WANT_WRITE);
4586 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4587 PY_SSL_ERROR_WANT_X509_LOOKUP);
4588 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4589 PY_SSL_ERROR_SYSCALL);
4590 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4591 PY_SSL_ERROR_SSL);
4592 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4593 PY_SSL_ERROR_WANT_CONNECT);
4594 /* non ssl.h errorcodes */
4595 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4596 PY_SSL_ERROR_EOF);
4597 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4598 PY_SSL_ERROR_INVALID_ERROR_CODE);
4599 /* cert requirements */
4600 PyModule_AddIntConstant(m, "CERT_NONE",
4601 PY_SSL_CERT_NONE);
4602 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4603 PY_SSL_CERT_OPTIONAL);
4604 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4605 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004606 /* CRL verification for verification_flags */
4607 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4608 0);
4609 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4610 X509_V_FLAG_CRL_CHECK);
4611 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4612 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4613 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4614 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05004615#ifdef X509_V_FLAG_TRUSTED_FIRST
4616 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4617 X509_V_FLAG_TRUSTED_FIRST);
4618#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004619
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004620 /* Alert Descriptions from ssl.h */
4621 /* note RESERVED constants no longer intended for use have been removed */
4622 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4623
4624#define ADD_AD_CONSTANT(s) \
4625 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4626 SSL_AD_##s)
4627
4628 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4629 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4630 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4631 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4632 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4633 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4634 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4635 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4636 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4637 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4638 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4639 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4640 ADD_AD_CONSTANT(UNKNOWN_CA);
4641 ADD_AD_CONSTANT(ACCESS_DENIED);
4642 ADD_AD_CONSTANT(DECODE_ERROR);
4643 ADD_AD_CONSTANT(DECRYPT_ERROR);
4644 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4645 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4646 ADD_AD_CONSTANT(INTERNAL_ERROR);
4647 ADD_AD_CONSTANT(USER_CANCELLED);
4648 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004649 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004650#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4651 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4652#endif
4653#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4654 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4655#endif
4656#ifdef SSL_AD_UNRECOGNIZED_NAME
4657 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4658#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004659#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4660 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4661#endif
4662#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4663 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4664#endif
4665#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4666 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4667#endif
4668
4669#undef ADD_AD_CONSTANT
4670
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004671 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004672#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004673 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4674 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004675#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004676#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004677 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4678 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004679#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004680 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4681 PY_SSL_VERSION_SSL23);
4682 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4683 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004684#if HAVE_TLSv1_2
4685 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4686 PY_SSL_VERSION_TLS1_1);
4687 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4688 PY_SSL_VERSION_TLS1_2);
4689#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004690
Antoine Pitroub5218772010-05-21 09:56:06 +00004691 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004692 PyModule_AddIntConstant(m, "OP_ALL",
4693 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004694 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4695 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4696 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004697#if HAVE_TLSv1_2
4698 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4699 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4700#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004701 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4702 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004703 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004704#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004705 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004706#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004707#ifdef SSL_OP_NO_COMPRESSION
4708 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4709 SSL_OP_NO_COMPRESSION);
4710#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004711
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004712#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004713 r = Py_True;
4714#else
4715 r = Py_False;
4716#endif
4717 Py_INCREF(r);
4718 PyModule_AddObject(m, "HAS_SNI", r);
4719
Antoine Pitroud6494802011-07-21 01:11:30 +02004720 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004721 Py_INCREF(r);
4722 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4723
Antoine Pitrou501da612011-12-21 09:27:41 +01004724#ifdef OPENSSL_NO_ECDH
4725 r = Py_False;
4726#else
4727 r = Py_True;
4728#endif
4729 Py_INCREF(r);
4730 PyModule_AddObject(m, "HAS_ECDH", r);
4731
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004732#ifdef OPENSSL_NPN_NEGOTIATED
4733 r = Py_True;
4734#else
4735 r = Py_False;
4736#endif
4737 Py_INCREF(r);
4738 PyModule_AddObject(m, "HAS_NPN", r);
4739
Benjamin Petersoncca27322015-01-23 16:35:37 -05004740#ifdef HAVE_ALPN
4741 r = Py_True;
4742#else
4743 r = Py_False;
4744#endif
4745 Py_INCREF(r);
4746 PyModule_AddObject(m, "HAS_ALPN", r);
4747
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004748 /* Mappings for error codes */
4749 err_codes_to_names = PyDict_New();
4750 err_names_to_codes = PyDict_New();
4751 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4752 return NULL;
4753 errcode = error_codes;
4754 while (errcode->mnemonic != NULL) {
4755 PyObject *mnemo, *key;
4756 mnemo = PyUnicode_FromString(errcode->mnemonic);
4757 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4758 if (mnemo == NULL || key == NULL)
4759 return NULL;
4760 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4761 return NULL;
4762 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4763 return NULL;
4764 Py_DECREF(key);
4765 Py_DECREF(mnemo);
4766 errcode++;
4767 }
4768 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4769 return NULL;
4770 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4771 return NULL;
4772
4773 lib_codes_to_names = PyDict_New();
4774 if (lib_codes_to_names == NULL)
4775 return NULL;
4776 libcode = library_codes;
4777 while (libcode->library != NULL) {
4778 PyObject *mnemo, *key;
4779 key = PyLong_FromLong(libcode->code);
4780 mnemo = PyUnicode_FromString(libcode->library);
4781 if (key == NULL || mnemo == NULL)
4782 return NULL;
4783 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4784 return NULL;
4785 Py_DECREF(key);
4786 Py_DECREF(mnemo);
4787 libcode++;
4788 }
4789 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4790 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004791
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004792 /* OpenSSL version */
4793 /* SSLeay() gives us the version of the library linked against,
4794 which could be different from the headers version.
4795 */
4796 libver = SSLeay();
4797 r = PyLong_FromUnsignedLong(libver);
4798 if (r == NULL)
4799 return NULL;
4800 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4801 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004802 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004803 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4804 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4805 return NULL;
4806 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4807 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4808 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004809
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004810 libver = OPENSSL_VERSION_NUMBER;
4811 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4812 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4813 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4814 return NULL;
4815
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004816 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004817}