blob: 8a4654a7be5c405bb612b36208e6c152c9c88453 [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 Pitroub1fdf472014-10-05 20:41:53 +0200490 PyObject *hostname;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200491 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000492
Antoine Pitrou152efa22010-05-16 18:19:27 +0000493 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000494 if (self == NULL)
495 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000496
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000497 self->peer_cert = NULL;
498 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000499 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100500 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200501 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200502 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200503 self->owner = NULL;
504 if (server_hostname != NULL) {
505 hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
506 "idna", "strict");
507 if (hostname == NULL) {
508 Py_DECREF(self);
509 return NULL;
510 }
511 self->server_hostname = hostname;
512 } else
513 self->server_hostname = NULL;
514
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100515 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000516
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000517 /* Make sure the SSL error state is initialized */
518 (void) ERR_get_state();
519 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000520
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000521 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000522 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000523 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200524 SSL_set_app_data(self->ssl, self);
525 if (sock) {
526 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
527 } else {
528 /* BIOs are reference counted and SSL_set_bio borrows our reference.
529 * To prevent a double free in memory_bio_dealloc() we need to take an
530 * extra reference here. */
531 CRYPTO_add(&inbio->bio->references, 1, CRYPTO_LOCK_BIO);
532 CRYPTO_add(&outbio->bio->references, 1, CRYPTO_LOCK_BIO);
533 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
534 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200535 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000536#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200537 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000538#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200539 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000540
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100541#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000542 if (server_hostname != NULL)
543 SSL_set_tlsext_host_name(self->ssl, server_hostname);
544#endif
545
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000546 /* If the socket is in non-blocking mode or timeout mode, set the BIO
547 * to non-blocking mode (blocking is the default)
548 */
Victor Stinnere2452312015-03-28 03:00:46 +0100549 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000550 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
551 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
552 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000553
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000554 PySSL_BEGIN_ALLOW_THREADS
555 if (socket_type == PY_SSL_CLIENT)
556 SSL_set_connect_state(self->ssl);
557 else
558 SSL_set_accept_state(self->ssl);
559 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000560
Antoine Pitroud6494802011-07-21 01:11:30 +0200561 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200562 if (sock != NULL) {
563 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
564 if (self->Socket == NULL) {
565 Py_DECREF(self);
566 Py_XDECREF(self->server_hostname);
567 return NULL;
568 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100569 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000570 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000571}
572
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000573/* SSL object methods */
574
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300575/*[clinic input]
576_ssl._SSLSocket.do_handshake
577[clinic start generated code]*/
578
579static PyObject *
580_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
581/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000582{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000583 int ret;
584 int err;
585 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200586 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200587 _PyTime_t timeout, deadline = 0;
588 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000589
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200590 if (sock) {
591 if (((PyObject*)sock) == Py_None) {
592 _setSSLError("Underlying socket connection gone",
593 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
594 return NULL;
595 }
596 Py_INCREF(sock);
597
598 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100599 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200600 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
601 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000602 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000603
Victor Stinner14690702015-04-06 22:46:13 +0200604 timeout = GET_SOCKET_TIMEOUT(sock);
605 has_timeout = (timeout > 0);
606 if (has_timeout)
607 deadline = _PyTime_GetMonotonicClock() + timeout;
608
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000609 /* Actually negotiate SSL connection */
610 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000611 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000612 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000613 ret = SSL_do_handshake(self->ssl);
614 err = SSL_get_error(self->ssl, ret);
615 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200616
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000617 if (PyErr_CheckSignals())
618 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200619
Victor Stinner14690702015-04-06 22:46:13 +0200620 if (has_timeout)
621 timeout = deadline - _PyTime_GetMonotonicClock();
622
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000623 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200624 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000625 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200626 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000627 } else {
628 sockstate = SOCKET_OPERATION_OK;
629 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200630
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000631 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000632 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000633 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000634 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000635 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
636 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000637 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000638 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000639 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
640 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000641 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000642 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000643 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
644 break;
645 }
646 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200647 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000648 if (ret < 1)
649 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000650
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000651 if (self->peer_cert)
652 X509_free (self->peer_cert);
653 PySSL_BEGIN_ALLOW_THREADS
654 self->peer_cert = SSL_get_peer_certificate(self->ssl);
655 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200656 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000657
658 Py_INCREF(Py_None);
659 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000660
661error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200662 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000663 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000664}
665
Thomas Woutersed03b412007-08-28 21:37:11 +0000666static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000667_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000668
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000669 char namebuf[X509_NAME_MAXLEN];
670 int buflen;
671 PyObject *name_obj;
672 PyObject *value_obj;
673 PyObject *attr;
674 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000675
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000676 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
677 if (buflen < 0) {
678 _setSSLError(NULL, 0, __FILE__, __LINE__);
679 goto fail;
680 }
681 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
682 if (name_obj == NULL)
683 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000684
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000685 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
686 if (buflen < 0) {
687 _setSSLError(NULL, 0, __FILE__, __LINE__);
688 Py_DECREF(name_obj);
689 goto fail;
690 }
691 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000692 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000693 OPENSSL_free(valuebuf);
694 if (value_obj == NULL) {
695 Py_DECREF(name_obj);
696 goto fail;
697 }
698 attr = PyTuple_New(2);
699 if (attr == NULL) {
700 Py_DECREF(name_obj);
701 Py_DECREF(value_obj);
702 goto fail;
703 }
704 PyTuple_SET_ITEM(attr, 0, name_obj);
705 PyTuple_SET_ITEM(attr, 1, value_obj);
706 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000707
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000708 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000709 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000710}
711
712static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000713_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000714{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000715 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
716 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
717 PyObject *rdnt;
718 PyObject *attr = NULL; /* tuple to hold an attribute */
719 int entry_count = X509_NAME_entry_count(xname);
720 X509_NAME_ENTRY *entry;
721 ASN1_OBJECT *name;
722 ASN1_STRING *value;
723 int index_counter;
724 int rdn_level = -1;
725 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000726
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000727 dn = PyList_New(0);
728 if (dn == NULL)
729 return NULL;
730 /* now create another tuple to hold the top-level RDN */
731 rdn = PyList_New(0);
732 if (rdn == NULL)
733 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000734
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 for (index_counter = 0;
736 index_counter < entry_count;
737 index_counter++)
738 {
739 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000740
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 /* check to see if we've gotten to a new RDN */
742 if (rdn_level >= 0) {
743 if (rdn_level != entry->set) {
744 /* yes, new RDN */
745 /* add old RDN to DN */
746 rdnt = PyList_AsTuple(rdn);
747 Py_DECREF(rdn);
748 if (rdnt == NULL)
749 goto fail0;
750 retcode = PyList_Append(dn, rdnt);
751 Py_DECREF(rdnt);
752 if (retcode < 0)
753 goto fail0;
754 /* create new RDN */
755 rdn = PyList_New(0);
756 if (rdn == NULL)
757 goto fail0;
758 }
759 }
760 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000761
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000762 /* now add this attribute to the current RDN */
763 name = X509_NAME_ENTRY_get_object(entry);
764 value = X509_NAME_ENTRY_get_data(entry);
765 attr = _create_tuple_for_attribute(name, value);
766 /*
767 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
768 entry->set,
769 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
770 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
771 */
772 if (attr == NULL)
773 goto fail1;
774 retcode = PyList_Append(rdn, attr);
775 Py_DECREF(attr);
776 if (retcode < 0)
777 goto fail1;
778 }
779 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100780 if (rdn != NULL) {
781 if (PyList_GET_SIZE(rdn) > 0) {
782 rdnt = PyList_AsTuple(rdn);
783 Py_DECREF(rdn);
784 if (rdnt == NULL)
785 goto fail0;
786 retcode = PyList_Append(dn, rdnt);
787 Py_DECREF(rdnt);
788 if (retcode < 0)
789 goto fail0;
790 }
791 else {
792 Py_DECREF(rdn);
793 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000795
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 /* convert list to tuple */
797 rdnt = PyList_AsTuple(dn);
798 Py_DECREF(dn);
799 if (rdnt == NULL)
800 return NULL;
801 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802
803 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000804 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805
806 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000807 Py_XDECREF(dn);
808 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000809}
810
811static PyObject *
812_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000813
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000814 /* this code follows the procedure outlined in
815 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
816 function to extract the STACK_OF(GENERAL_NAME),
817 then iterates through the stack to add the
818 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000819
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000820 int i, j;
821 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200822 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000823 X509_EXTENSION *ext = NULL;
824 GENERAL_NAMES *names = NULL;
825 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000826 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000827 BIO *biobuf = NULL;
828 char buf[2048];
829 char *vptr;
830 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000831 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000832
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 if (certificate == NULL)
834 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000835
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000836 /* get a memory buffer */
837 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000838
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200839 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 while ((i = X509_get_ext_by_NID(
841 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000842
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000843 if (peer_alt_names == Py_None) {
844 peer_alt_names = PyList_New(0);
845 if (peer_alt_names == NULL)
846 goto fail;
847 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000848
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000849 /* now decode the altName */
850 ext = X509_get_ext(certificate, i);
851 if(!(method = X509V3_EXT_get(ext))) {
852 PyErr_SetString
853 (PySSLErrorObject,
854 ERRSTR("No method for internalizing subjectAltName!"));
855 goto fail;
856 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000857
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000858 p = ext->value->data;
859 if (method->it)
860 names = (GENERAL_NAMES*)
861 (ASN1_item_d2i(NULL,
862 &p,
863 ext->value->length,
864 ASN1_ITEM_ptr(method->it)));
865 else
866 names = (GENERAL_NAMES*)
867 (method->d2i(NULL,
868 &p,
869 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000870
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000871 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000872 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200873 int gntype;
874 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000875
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000876 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200877 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200878 switch (gntype) {
879 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000880 /* we special-case DirName as a tuple of
881 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000882
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000883 t = PyTuple_New(2);
884 if (t == NULL) {
885 goto fail;
886 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000887
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000888 v = PyUnicode_FromString("DirName");
889 if (v == NULL) {
890 Py_DECREF(t);
891 goto fail;
892 }
893 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000894
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000895 v = _create_tuple_for_X509_NAME (name->d.dirn);
896 if (v == NULL) {
897 Py_DECREF(t);
898 goto fail;
899 }
900 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200901 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000902
Christian Heimes824f7f32013-08-17 00:54:47 +0200903 case GEN_EMAIL:
904 case GEN_DNS:
905 case GEN_URI:
906 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
907 correctly, CVE-2013-4238 */
908 t = PyTuple_New(2);
909 if (t == NULL)
910 goto fail;
911 switch (gntype) {
912 case GEN_EMAIL:
913 v = PyUnicode_FromString("email");
914 as = name->d.rfc822Name;
915 break;
916 case GEN_DNS:
917 v = PyUnicode_FromString("DNS");
918 as = name->d.dNSName;
919 break;
920 case GEN_URI:
921 v = PyUnicode_FromString("URI");
922 as = name->d.uniformResourceIdentifier;
923 break;
924 }
925 if (v == NULL) {
926 Py_DECREF(t);
927 goto fail;
928 }
929 PyTuple_SET_ITEM(t, 0, v);
930 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
931 ASN1_STRING_length(as));
932 if (v == NULL) {
933 Py_DECREF(t);
934 goto fail;
935 }
936 PyTuple_SET_ITEM(t, 1, v);
937 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000938
Christian Heimes824f7f32013-08-17 00:54:47 +0200939 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200941 switch (gntype) {
942 /* check for new general name type */
943 case GEN_OTHERNAME:
944 case GEN_X400:
945 case GEN_EDIPARTY:
946 case GEN_IPADD:
947 case GEN_RID:
948 break;
949 default:
950 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
951 "Unknown general name type %d",
952 gntype) == -1) {
953 goto fail;
954 }
955 break;
956 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 (void) BIO_reset(biobuf);
958 GENERAL_NAME_print(biobuf, name);
959 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
960 if (len < 0) {
961 _setSSLError(NULL, 0, __FILE__, __LINE__);
962 goto fail;
963 }
964 vptr = strchr(buf, ':');
965 if (vptr == NULL)
966 goto fail;
967 t = PyTuple_New(2);
968 if (t == NULL)
969 goto fail;
970 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
971 if (v == NULL) {
972 Py_DECREF(t);
973 goto fail;
974 }
975 PyTuple_SET_ITEM(t, 0, v);
976 v = PyUnicode_FromStringAndSize((vptr + 1),
977 (len - (vptr - buf + 1)));
978 if (v == NULL) {
979 Py_DECREF(t);
980 goto fail;
981 }
982 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200983 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000984 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000985
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000986 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000987
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000988 if (PyList_Append(peer_alt_names, t) < 0) {
989 Py_DECREF(t);
990 goto fail;
991 }
992 Py_DECREF(t);
993 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100994 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000995 }
996 BIO_free(biobuf);
997 if (peer_alt_names != Py_None) {
998 v = PyList_AsTuple(peer_alt_names);
999 Py_DECREF(peer_alt_names);
1000 return v;
1001 } else {
1002 return peer_alt_names;
1003 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001004
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001005
1006 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 if (biobuf != NULL)
1008 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001009
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001010 if (peer_alt_names != Py_None) {
1011 Py_XDECREF(peer_alt_names);
1012 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001013
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001014 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001015}
1016
1017static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001018_get_aia_uri(X509 *certificate, int nid) {
1019 PyObject *lst = NULL, *ostr = NULL;
1020 int i, result;
1021 AUTHORITY_INFO_ACCESS *info;
1022
1023 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001024 if (info == NULL)
1025 return Py_None;
1026 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1027 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001028 return Py_None;
1029 }
1030
1031 if ((lst = PyList_New(0)) == NULL) {
1032 goto fail;
1033 }
1034
1035 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1036 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1037 ASN1_IA5STRING *uri;
1038
1039 if ((OBJ_obj2nid(ad->method) != nid) ||
1040 (ad->location->type != GEN_URI)) {
1041 continue;
1042 }
1043 uri = ad->location->d.uniformResourceIdentifier;
1044 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1045 uri->length);
1046 if (ostr == NULL) {
1047 goto fail;
1048 }
1049 result = PyList_Append(lst, ostr);
1050 Py_DECREF(ostr);
1051 if (result < 0) {
1052 goto fail;
1053 }
1054 }
1055 AUTHORITY_INFO_ACCESS_free(info);
1056
1057 /* convert to tuple or None */
1058 if (PyList_Size(lst) == 0) {
1059 Py_DECREF(lst);
1060 return Py_None;
1061 } else {
1062 PyObject *tup;
1063 tup = PyList_AsTuple(lst);
1064 Py_DECREF(lst);
1065 return tup;
1066 }
1067
1068 fail:
1069 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001070 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001071 return NULL;
1072}
1073
1074static PyObject *
1075_get_crl_dp(X509 *certificate) {
1076 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001077 int i, j;
1078 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001079
Christian Heimes949ec142013-11-21 16:26:51 +01001080#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001081 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001082#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001083 /* Calls x509v3_cache_extensions and sets up crldp */
1084 X509_check_ca(certificate);
1085 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001086#endif
1087
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001088 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001089 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001090
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001091 lst = PyList_New(0);
1092 if (lst == NULL)
1093 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001094
1095 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1096 DIST_POINT *dp;
1097 STACK_OF(GENERAL_NAME) *gns;
1098
1099 dp = sk_DIST_POINT_value(dps, i);
1100 gns = dp->distpoint->name.fullname;
1101
1102 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1103 GENERAL_NAME *gn;
1104 ASN1_IA5STRING *uri;
1105 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001106 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001107
1108 gn = sk_GENERAL_NAME_value(gns, j);
1109 if (gn->type != GEN_URI) {
1110 continue;
1111 }
1112 uri = gn->d.uniformResourceIdentifier;
1113 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1114 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001115 if (ouri == NULL)
1116 goto done;
1117
1118 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001119 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001120 if (err < 0)
1121 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001122 }
1123 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001124
1125 /* Convert to tuple. */
1126 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1127
1128 done:
1129 Py_XDECREF(lst);
1130#if OPENSSL_VERSION_NUMBER < 0x10001000L
Benjamin Peterson806fb252015-11-14 00:09:22 -08001131 sk_DIST_POINT_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001132#endif
1133 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001134}
1135
1136static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001137_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001138
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001139 PyObject *retval = NULL;
1140 BIO *biobuf = NULL;
1141 PyObject *peer;
1142 PyObject *peer_alt_names = NULL;
1143 PyObject *issuer;
1144 PyObject *version;
1145 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001146 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 ASN1_INTEGER *serialNumber;
1148 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001149 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 ASN1_TIME *notBefore, *notAfter;
1151 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001152
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001153 retval = PyDict_New();
1154 if (retval == NULL)
1155 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001156
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001157 peer = _create_tuple_for_X509_NAME(
1158 X509_get_subject_name(certificate));
1159 if (peer == NULL)
1160 goto fail0;
1161 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1162 Py_DECREF(peer);
1163 goto fail0;
1164 }
1165 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001166
Antoine Pitroufb046912010-11-09 20:21:19 +00001167 issuer = _create_tuple_for_X509_NAME(
1168 X509_get_issuer_name(certificate));
1169 if (issuer == NULL)
1170 goto fail0;
1171 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001172 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001173 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001175 Py_DECREF(issuer);
1176
1177 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001178 if (version == NULL)
1179 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001180 if (PyDict_SetItemString(retval, "version", version) < 0) {
1181 Py_DECREF(version);
1182 goto fail0;
1183 }
1184 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001185
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001186 /* get a memory buffer */
1187 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001188
Antoine Pitroufb046912010-11-09 20:21:19 +00001189 (void) BIO_reset(biobuf);
1190 serialNumber = X509_get_serialNumber(certificate);
1191 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1192 i2a_ASN1_INTEGER(biobuf, serialNumber);
1193 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1194 if (len < 0) {
1195 _setSSLError(NULL, 0, __FILE__, __LINE__);
1196 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001197 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001198 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1199 if (sn_obj == NULL)
1200 goto fail1;
1201 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1202 Py_DECREF(sn_obj);
1203 goto fail1;
1204 }
1205 Py_DECREF(sn_obj);
1206
1207 (void) BIO_reset(biobuf);
1208 notBefore = X509_get_notBefore(certificate);
1209 ASN1_TIME_print(biobuf, notBefore);
1210 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1211 if (len < 0) {
1212 _setSSLError(NULL, 0, __FILE__, __LINE__);
1213 goto fail1;
1214 }
1215 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1216 if (pnotBefore == NULL)
1217 goto fail1;
1218 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1219 Py_DECREF(pnotBefore);
1220 goto fail1;
1221 }
1222 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001223
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001224 (void) BIO_reset(biobuf);
1225 notAfter = X509_get_notAfter(certificate);
1226 ASN1_TIME_print(biobuf, notAfter);
1227 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1228 if (len < 0) {
1229 _setSSLError(NULL, 0, __FILE__, __LINE__);
1230 goto fail1;
1231 }
1232 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1233 if (pnotAfter == NULL)
1234 goto fail1;
1235 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1236 Py_DECREF(pnotAfter);
1237 goto fail1;
1238 }
1239 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001240
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001242
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 peer_alt_names = _get_peer_alt_names(certificate);
1244 if (peer_alt_names == NULL)
1245 goto fail1;
1246 else if (peer_alt_names != Py_None) {
1247 if (PyDict_SetItemString(retval, "subjectAltName",
1248 peer_alt_names) < 0) {
1249 Py_DECREF(peer_alt_names);
1250 goto fail1;
1251 }
1252 Py_DECREF(peer_alt_names);
1253 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001254
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001255 /* Authority Information Access: OCSP URIs */
1256 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1257 if (obj == NULL) {
1258 goto fail1;
1259 } else if (obj != Py_None) {
1260 result = PyDict_SetItemString(retval, "OCSP", obj);
1261 Py_DECREF(obj);
1262 if (result < 0) {
1263 goto fail1;
1264 }
1265 }
1266
1267 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1268 if (obj == NULL) {
1269 goto fail1;
1270 } else if (obj != Py_None) {
1271 result = PyDict_SetItemString(retval, "caIssuers", obj);
1272 Py_DECREF(obj);
1273 if (result < 0) {
1274 goto fail1;
1275 }
1276 }
1277
1278 /* CDP (CRL distribution points) */
1279 obj = _get_crl_dp(certificate);
1280 if (obj == NULL) {
1281 goto fail1;
1282 } else if (obj != Py_None) {
1283 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1284 Py_DECREF(obj);
1285 if (result < 0) {
1286 goto fail1;
1287 }
1288 }
1289
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 BIO_free(biobuf);
1291 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001292
1293 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001294 if (biobuf != NULL)
1295 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001296 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001297 Py_XDECREF(retval);
1298 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001299}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001300
Christian Heimes9a5395a2013-06-17 15:44:12 +02001301static PyObject *
1302_certificate_to_der(X509 *certificate)
1303{
1304 unsigned char *bytes_buf = NULL;
1305 int len;
1306 PyObject *retval;
1307
1308 bytes_buf = NULL;
1309 len = i2d_X509(certificate, &bytes_buf);
1310 if (len < 0) {
1311 _setSSLError(NULL, 0, __FILE__, __LINE__);
1312 return NULL;
1313 }
1314 /* this is actually an immutable bytes sequence */
1315 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1316 OPENSSL_free(bytes_buf);
1317 return retval;
1318}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001319
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001320/*[clinic input]
1321_ssl._test_decode_cert
1322 path: object(converter="PyUnicode_FSConverter")
1323 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001324
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001325[clinic start generated code]*/
1326
1327static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001328_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1329/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001330{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001331 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001332 X509 *x=NULL;
1333 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001334
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001335 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1336 PyErr_SetString(PySSLErrorObject,
1337 "Can't malloc memory to read file");
1338 goto fail0;
1339 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001340
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001341 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001342 PyErr_SetString(PySSLErrorObject,
1343 "Can't open file");
1344 goto fail0;
1345 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001346
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001347 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1348 if (x == NULL) {
1349 PyErr_SetString(PySSLErrorObject,
1350 "Error decoding PEM-encoded file");
1351 goto fail0;
1352 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001353
Antoine Pitroufb046912010-11-09 20:21:19 +00001354 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001355 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001356
1357 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001358 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 if (cert != NULL) BIO_free(cert);
1360 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001361}
1362
1363
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001364/*[clinic input]
1365_ssl._SSLSocket.peer_certificate
1366 der as binary_mode: bool = False
1367 /
1368
1369Returns the certificate for the peer.
1370
1371If no certificate was provided, returns None. If a certificate was
1372provided, but not validated, returns an empty dictionary. Otherwise
1373returns a dict containing information about the peer certificate.
1374
1375If the optional argument is True, returns a DER-encoded copy of the
1376peer certificate, or None if no certificate was provided. This will
1377return the certificate even if it wasn't validated.
1378[clinic start generated code]*/
1379
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001380static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001381_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1382/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001383{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001384 int verification;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001385
Antoine Pitrou20b85552013-09-29 19:50:53 +02001386 if (!self->handshake_done) {
1387 PyErr_SetString(PyExc_ValueError,
1388 "handshake not done yet");
1389 return NULL;
1390 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001391 if (!self->peer_cert)
1392 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001393
Antoine Pitrou721738f2012-08-15 23:20:39 +02001394 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001395 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001396 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001398 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001399 if ((verification & SSL_VERIFY_PEER) == 0)
1400 return PyDict_New();
1401 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001402 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001403 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001404}
1405
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001406static PyObject *
1407cipher_to_tuple(const SSL_CIPHER *cipher)
1408{
1409 const char *cipher_name, *cipher_protocol;
1410 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411 if (retval == NULL)
1412 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001413
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001414 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001415 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001416 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001417 PyTuple_SET_ITEM(retval, 0, Py_None);
1418 } else {
1419 v = PyUnicode_FromString(cipher_name);
1420 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001421 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001422 PyTuple_SET_ITEM(retval, 0, v);
1423 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001424
1425 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001426 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001427 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001428 PyTuple_SET_ITEM(retval, 1, Py_None);
1429 } else {
1430 v = PyUnicode_FromString(cipher_protocol);
1431 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001432 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001433 PyTuple_SET_ITEM(retval, 1, v);
1434 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001435
1436 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001437 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001438 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001439 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001440
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001441 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001442
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001443 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001444 Py_DECREF(retval);
1445 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001446}
1447
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001448/*[clinic input]
1449_ssl._SSLSocket.shared_ciphers
1450[clinic start generated code]*/
1451
1452static PyObject *
1453_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1454/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001455{
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001456 SSL_SESSION *sess = SSL_get_session(self->ssl);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001457 STACK_OF(SSL_CIPHER) *ciphers;
1458 int i;
1459 PyObject *res;
1460
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001461 if (!sess || !sess->ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001462 Py_RETURN_NONE;
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001463 ciphers = sess->ciphers;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001464 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1465 if (!res)
1466 return NULL;
1467 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1468 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1469 if (!tup) {
1470 Py_DECREF(res);
1471 return NULL;
1472 }
1473 PyList_SET_ITEM(res, i, tup);
1474 }
1475 return res;
1476}
1477
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001478/*[clinic input]
1479_ssl._SSLSocket.cipher
1480[clinic start generated code]*/
1481
1482static PyObject *
1483_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1484/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001485{
1486 const SSL_CIPHER *current;
1487
1488 if (self->ssl == NULL)
1489 Py_RETURN_NONE;
1490 current = SSL_get_current_cipher(self->ssl);
1491 if (current == NULL)
1492 Py_RETURN_NONE;
1493 return cipher_to_tuple(current);
1494}
1495
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001496/*[clinic input]
1497_ssl._SSLSocket.version
1498[clinic start generated code]*/
1499
1500static PyObject *
1501_ssl__SSLSocket_version_impl(PySSLSocket *self)
1502/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001503{
1504 const char *version;
1505
1506 if (self->ssl == NULL)
1507 Py_RETURN_NONE;
1508 version = SSL_get_version(self->ssl);
1509 if (!strcmp(version, "unknown"))
1510 Py_RETURN_NONE;
1511 return PyUnicode_FromString(version);
1512}
1513
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001514#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001515/*[clinic input]
1516_ssl._SSLSocket.selected_npn_protocol
1517[clinic start generated code]*/
1518
1519static PyObject *
1520_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1521/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1522{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001523 const unsigned char *out;
1524 unsigned int outlen;
1525
Victor Stinner4569cd52013-06-23 14:58:43 +02001526 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001527 &out, &outlen);
1528
1529 if (out == NULL)
1530 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001531 return PyUnicode_FromStringAndSize((char *)out, outlen);
1532}
1533#endif
1534
1535#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001536/*[clinic input]
1537_ssl._SSLSocket.selected_alpn_protocol
1538[clinic start generated code]*/
1539
1540static PyObject *
1541_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1542/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1543{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001544 const unsigned char *out;
1545 unsigned int outlen;
1546
1547 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1548
1549 if (out == NULL)
1550 Py_RETURN_NONE;
1551 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001552}
1553#endif
1554
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001555/*[clinic input]
1556_ssl._SSLSocket.compression
1557[clinic start generated code]*/
1558
1559static PyObject *
1560_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1561/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1562{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001563#ifdef OPENSSL_NO_COMP
1564 Py_RETURN_NONE;
1565#else
1566 const COMP_METHOD *comp_method;
1567 const char *short_name;
1568
1569 if (self->ssl == NULL)
1570 Py_RETURN_NONE;
1571 comp_method = SSL_get_current_compression(self->ssl);
1572 if (comp_method == NULL || comp_method->type == NID_undef)
1573 Py_RETURN_NONE;
1574 short_name = OBJ_nid2sn(comp_method->type);
1575 if (short_name == NULL)
1576 Py_RETURN_NONE;
1577 return PyUnicode_DecodeFSDefault(short_name);
1578#endif
1579}
1580
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001581static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1582 Py_INCREF(self->ctx);
1583 return self->ctx;
1584}
1585
1586static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1587 void *closure) {
1588
1589 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001590#if !HAVE_SNI
1591 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1592 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001593 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001594#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001595 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001596 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001597 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001598#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001599 } else {
1600 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1601 return -1;
1602 }
1603
1604 return 0;
1605}
1606
1607PyDoc_STRVAR(PySSL_set_context_doc,
1608"_setter_context(ctx)\n\
1609\
1610This changes the context associated with the SSLSocket. This is typically\n\
1611used from within a callback function set by the set_servername_callback\n\
1612on the SSLContext to change the certificate information associated with the\n\
1613SSLSocket before the cryptographic exchange handshake messages\n");
1614
1615
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001616static PyObject *
1617PySSL_get_server_side(PySSLSocket *self, void *c)
1618{
1619 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1620}
1621
1622PyDoc_STRVAR(PySSL_get_server_side_doc,
1623"Whether this is a server-side socket.");
1624
1625static PyObject *
1626PySSL_get_server_hostname(PySSLSocket *self, void *c)
1627{
1628 if (self->server_hostname == NULL)
1629 Py_RETURN_NONE;
1630 Py_INCREF(self->server_hostname);
1631 return self->server_hostname;
1632}
1633
1634PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1635"The currently set server hostname (for SNI).");
1636
1637static PyObject *
1638PySSL_get_owner(PySSLSocket *self, void *c)
1639{
1640 PyObject *owner;
1641
1642 if (self->owner == NULL)
1643 Py_RETURN_NONE;
1644
1645 owner = PyWeakref_GetObject(self->owner);
1646 Py_INCREF(owner);
1647 return owner;
1648}
1649
1650static int
1651PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1652{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001653 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001654 if (self->owner == NULL)
1655 return -1;
1656 return 0;
1657}
1658
1659PyDoc_STRVAR(PySSL_get_owner_doc,
1660"The Python-level owner of this object.\
1661Passed as \"self\" in servername callback.");
1662
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001663
Antoine Pitrou152efa22010-05-16 18:19:27 +00001664static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001665{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001666 if (self->peer_cert) /* Possible not to have one? */
1667 X509_free (self->peer_cert);
1668 if (self->ssl)
1669 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001670 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001671 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001672 Py_XDECREF(self->server_hostname);
1673 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001674 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001675}
1676
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001677/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001678 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001679 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001680 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001681
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001682static int
Victor Stinner14690702015-04-06 22:46:13 +02001683PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001684{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001685 int rc;
1686#ifdef HAVE_POLL
1687 struct pollfd pollfd;
1688 _PyTime_t ms;
1689#else
1690 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001691 fd_set fds;
1692 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001693#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001694
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001695 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001696 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001697 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001698 else if (timeout < 0) {
1699 if (s->sock_timeout > 0)
1700 return SOCKET_HAS_TIMED_OUT;
1701 else
1702 return SOCKET_IS_BLOCKING;
1703 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001704
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001705 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001706 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001707 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001708
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001709 /* Prefer poll, if available, since you can poll() any fd
1710 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001711#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001712 pollfd.fd = s->sock_fd;
1713 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001714
Victor Stinner14690702015-04-06 22:46:13 +02001715 /* timeout is in seconds, poll() uses milliseconds */
1716 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001717 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001718
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001719 PySSL_BEGIN_ALLOW_THREADS
1720 rc = poll(&pollfd, 1, (int)ms);
1721 PySSL_END_ALLOW_THREADS
1722#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001723 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001724 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001725 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001726
Victor Stinner14690702015-04-06 22:46:13 +02001727 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001728
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001729 FD_ZERO(&fds);
1730 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001731
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001732 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001733 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001734 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001735 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001736 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001738 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001739 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001740#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001741
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001742 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1743 (when we are able to write or when there's something to read) */
1744 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001745}
1746
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001747/*[clinic input]
1748_ssl._SSLSocket.write
1749 b: Py_buffer
1750 /
1751
1752Writes the bytes-like object b into the SSL object.
1753
1754Returns the number of bytes written.
1755[clinic start generated code]*/
1756
1757static PyObject *
1758_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1759/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001760{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001761 int len;
1762 int sockstate;
1763 int err;
1764 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001765 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001766 _PyTime_t timeout, deadline = 0;
1767 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001768
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001769 if (sock != NULL) {
1770 if (((PyObject*)sock) == Py_None) {
1771 _setSSLError("Underlying socket connection gone",
1772 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1773 return NULL;
1774 }
1775 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001776 }
1777
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001778 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001779 PyErr_Format(PyExc_OverflowError,
1780 "string longer than %d bytes", INT_MAX);
1781 goto error;
1782 }
1783
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001784 if (sock != NULL) {
1785 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001786 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001787 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1788 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1789 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001790
Victor Stinner14690702015-04-06 22:46:13 +02001791 timeout = GET_SOCKET_TIMEOUT(sock);
1792 has_timeout = (timeout > 0);
1793 if (has_timeout)
1794 deadline = _PyTime_GetMonotonicClock() + timeout;
1795
1796 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001797 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001798 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001799 "The write operation timed out");
1800 goto error;
1801 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1802 PyErr_SetString(PySSLErrorObject,
1803 "Underlying socket has been closed.");
1804 goto error;
1805 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1806 PyErr_SetString(PySSLErrorObject,
1807 "Underlying socket too large for select().");
1808 goto error;
1809 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001810
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001811 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001812 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001813 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001814 err = SSL_get_error(self->ssl, len);
1815 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001816
1817 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001818 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001819
Victor Stinner14690702015-04-06 22:46:13 +02001820 if (has_timeout)
1821 timeout = deadline - _PyTime_GetMonotonicClock();
1822
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001824 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001826 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001827 } else {
1828 sockstate = SOCKET_OPERATION_OK;
1829 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001830
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001831 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001832 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001833 "The write operation timed out");
1834 goto error;
1835 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1836 PyErr_SetString(PySSLErrorObject,
1837 "Underlying socket has been closed.");
1838 goto error;
1839 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1840 break;
1841 }
1842 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001843
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001844 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001845 if (len > 0)
1846 return PyLong_FromLong(len);
1847 else
1848 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001849
1850error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001851 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001852 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001853}
1854
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001855/*[clinic input]
1856_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001857
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001858Returns the number of already decrypted bytes available for read, pending on the connection.
1859[clinic start generated code]*/
1860
1861static PyObject *
1862_ssl__SSLSocket_pending_impl(PySSLSocket *self)
1863/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00001864{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001865 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001866
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001867 PySSL_BEGIN_ALLOW_THREADS
1868 count = SSL_pending(self->ssl);
1869 PySSL_END_ALLOW_THREADS
1870 if (count < 0)
1871 return PySSL_SetError(self, count, __FILE__, __LINE__);
1872 else
1873 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001874}
1875
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001876/*[clinic input]
1877_ssl._SSLSocket.read
1878 size as len: int
1879 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001880 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001881 ]
1882 /
Bill Janssen6e027db2007-11-15 22:23:56 +00001883
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001884Read up to size bytes from the SSL socket.
1885[clinic start generated code]*/
1886
1887static PyObject *
1888_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
1889 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07001890/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001891{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001892 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001893 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001894 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001895 int sockstate;
1896 int err;
1897 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001898 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001899 _PyTime_t timeout, deadline = 0;
1900 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001901
Martin Panter5503d472016-03-27 05:35:19 +00001902 if (!group_right_1 && len < 0) {
1903 PyErr_SetString(PyExc_ValueError, "size should not be negative");
1904 return NULL;
1905 }
1906
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001907 if (sock != NULL) {
1908 if (((PyObject*)sock) == Py_None) {
1909 _setSSLError("Underlying socket connection gone",
1910 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1911 return NULL;
1912 }
1913 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001914 }
1915
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001916 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001917 dest = PyBytes_FromStringAndSize(NULL, len);
1918 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001919 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00001920 if (len == 0) {
1921 Py_XDECREF(sock);
1922 return dest;
1923 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001924 mem = PyBytes_AS_STRING(dest);
1925 }
1926 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001927 mem = buffer->buf;
1928 if (len <= 0 || len > buffer->len) {
1929 len = (int) buffer->len;
1930 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001931 PyErr_SetString(PyExc_OverflowError,
1932 "maximum length can't fit in a C 'int'");
1933 goto error;
1934 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00001935 if (len == 0) {
1936 count = 0;
1937 goto done;
1938 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001939 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001940 }
1941
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001942 if (sock != NULL) {
1943 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001944 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001945 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1946 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1947 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001948
Victor Stinner14690702015-04-06 22:46:13 +02001949 timeout = GET_SOCKET_TIMEOUT(sock);
1950 has_timeout = (timeout > 0);
1951 if (has_timeout)
1952 deadline = _PyTime_GetMonotonicClock() + timeout;
1953
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001954 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001955 PySSL_BEGIN_ALLOW_THREADS
1956 count = SSL_read(self->ssl, mem, len);
1957 err = SSL_get_error(self->ssl, count);
1958 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001959
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001960 if (PyErr_CheckSignals())
1961 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001962
Victor Stinner14690702015-04-06 22:46:13 +02001963 if (has_timeout)
1964 timeout = deadline - _PyTime_GetMonotonicClock();
1965
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001966 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001967 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001968 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001969 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001970 } else if (err == SSL_ERROR_ZERO_RETURN &&
1971 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001972 {
1973 count = 0;
1974 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001975 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001976 else
1977 sockstate = SOCKET_OPERATION_OK;
1978
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001979 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001980 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001981 "The read operation timed out");
1982 goto error;
1983 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1984 break;
1985 }
1986 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001987
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001988 if (count <= 0) {
1989 PySSL_SetError(self, count, __FILE__, __LINE__);
1990 goto error;
1991 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001992
1993done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001994 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001995 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001996 _PyBytes_Resize(&dest, count);
1997 return dest;
1998 }
1999 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002000 return PyLong_FromLong(count);
2001 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002002
2003error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002004 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002005 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002006 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002007 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002008}
2009
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002010/*[clinic input]
2011_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002012
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002013Does the SSL shutdown handshake with the remote end.
2014
2015Returns the underlying socket object.
2016[clinic start generated code]*/
2017
2018static PyObject *
2019_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2020/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002021{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002022 int err, ssl_err, sockstate, nonblocking;
2023 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002024 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002025 _PyTime_t timeout, deadline = 0;
2026 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002027
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002028 if (sock != NULL) {
2029 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002030 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002031 _setSSLError("Underlying socket connection gone",
2032 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2033 return NULL;
2034 }
2035 Py_INCREF(sock);
2036
2037 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002038 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002039 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2040 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002041 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002042
Victor Stinner14690702015-04-06 22:46:13 +02002043 timeout = GET_SOCKET_TIMEOUT(sock);
2044 has_timeout = (timeout > 0);
2045 if (has_timeout)
2046 deadline = _PyTime_GetMonotonicClock() + timeout;
2047
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002048 while (1) {
2049 PySSL_BEGIN_ALLOW_THREADS
2050 /* Disable read-ahead so that unwrap can work correctly.
2051 * Otherwise OpenSSL might read in too much data,
2052 * eating clear text data that happens to be
2053 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002054 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002055 * function is used and the shutdown_seen_zero != 0
2056 * condition is met.
2057 */
2058 if (self->shutdown_seen_zero)
2059 SSL_set_read_ahead(self->ssl, 0);
2060 err = SSL_shutdown(self->ssl);
2061 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002062
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002063 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2064 if (err > 0)
2065 break;
2066 if (err == 0) {
2067 /* Don't loop endlessly; instead preserve legacy
2068 behaviour of trying SSL_shutdown() only twice.
2069 This looks necessary for OpenSSL < 0.9.8m */
2070 if (++zeros > 1)
2071 break;
2072 /* Shutdown was sent, now try receiving */
2073 self->shutdown_seen_zero = 1;
2074 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002075 }
2076
Victor Stinner14690702015-04-06 22:46:13 +02002077 if (has_timeout)
2078 timeout = deadline - _PyTime_GetMonotonicClock();
2079
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002080 /* Possibly retry shutdown until timeout or failure */
2081 ssl_err = SSL_get_error(self->ssl, err);
2082 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002083 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002084 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002085 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002086 else
2087 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002088
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002089 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2090 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002091 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002092 "The read operation timed out");
2093 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002094 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002095 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002096 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002097 }
2098 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2099 PyErr_SetString(PySSLErrorObject,
2100 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002101 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002102 }
2103 else if (sockstate != SOCKET_OPERATION_OK)
2104 /* Retain the SSL error code */
2105 break;
2106 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002107
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002108 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002109 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002110 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002111 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002112 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002113 /* It's already INCREF'ed */
2114 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002115 else
2116 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002117
2118error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002119 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002120 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002121}
2122
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002123/*[clinic input]
2124_ssl._SSLSocket.tls_unique_cb
2125
2126Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2127
2128If the TLS handshake is not yet complete, None is returned.
2129[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002130
Antoine Pitroud6494802011-07-21 01:11:30 +02002131static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002132_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2133/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002134{
2135 PyObject *retval = NULL;
2136 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002137 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002138
2139 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2140 /* if session is resumed XOR we are the client */
2141 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2142 }
2143 else {
2144 /* if a new session XOR we are the server */
2145 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2146 }
2147
2148 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002149 if (len == 0)
2150 Py_RETURN_NONE;
2151
2152 retval = PyBytes_FromStringAndSize(buf, len);
2153
2154 return retval;
2155}
2156
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002157static PyGetSetDef ssl_getsetlist[] = {
2158 {"context", (getter) PySSL_get_context,
2159 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002160 {"server_side", (getter) PySSL_get_server_side, NULL,
2161 PySSL_get_server_side_doc},
2162 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2163 PySSL_get_server_hostname_doc},
2164 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2165 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002166 {NULL}, /* sentinel */
2167};
2168
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002169static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002170 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2171 _SSL__SSLSOCKET_WRITE_METHODDEF
2172 _SSL__SSLSOCKET_READ_METHODDEF
2173 _SSL__SSLSOCKET_PENDING_METHODDEF
2174 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2175 _SSL__SSLSOCKET_CIPHER_METHODDEF
2176 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2177 _SSL__SSLSOCKET_VERSION_METHODDEF
2178 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2179 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2180 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2181 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2182 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002183 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002184};
2185
Antoine Pitrou152efa22010-05-16 18:19:27 +00002186static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002187 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002188 "_ssl._SSLSocket", /*tp_name*/
2189 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002190 0, /*tp_itemsize*/
2191 /* methods */
2192 (destructor)PySSL_dealloc, /*tp_dealloc*/
2193 0, /*tp_print*/
2194 0, /*tp_getattr*/
2195 0, /*tp_setattr*/
2196 0, /*tp_reserved*/
2197 0, /*tp_repr*/
2198 0, /*tp_as_number*/
2199 0, /*tp_as_sequence*/
2200 0, /*tp_as_mapping*/
2201 0, /*tp_hash*/
2202 0, /*tp_call*/
2203 0, /*tp_str*/
2204 0, /*tp_getattro*/
2205 0, /*tp_setattro*/
2206 0, /*tp_as_buffer*/
2207 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2208 0, /*tp_doc*/
2209 0, /*tp_traverse*/
2210 0, /*tp_clear*/
2211 0, /*tp_richcompare*/
2212 0, /*tp_weaklistoffset*/
2213 0, /*tp_iter*/
2214 0, /*tp_iternext*/
2215 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002216 0, /*tp_members*/
2217 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002218};
2219
Antoine Pitrou152efa22010-05-16 18:19:27 +00002220
2221/*
2222 * _SSLContext objects
2223 */
2224
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002225/*[clinic input]
2226@classmethod
2227_ssl._SSLContext.__new__
2228 protocol as proto_version: int
2229 /
2230[clinic start generated code]*/
2231
Antoine Pitrou152efa22010-05-16 18:19:27 +00002232static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002233_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2234/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002235{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002236 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002237 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002238 SSL_CTX *ctx = NULL;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002239#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002240 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002241#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002242
Antoine Pitrou152efa22010-05-16 18:19:27 +00002243 PySSL_BEGIN_ALLOW_THREADS
2244 if (proto_version == PY_SSL_VERSION_TLS1)
2245 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002246#if HAVE_TLSv1_2
2247 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2248 ctx = SSL_CTX_new(TLSv1_1_method());
2249 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2250 ctx = SSL_CTX_new(TLSv1_2_method());
2251#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002252#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002253 else if (proto_version == PY_SSL_VERSION_SSL3)
2254 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002255#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002256#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002257 else if (proto_version == PY_SSL_VERSION_SSL2)
2258 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002259#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002260 else if (proto_version == PY_SSL_VERSION_SSL23)
2261 ctx = SSL_CTX_new(SSLv23_method());
2262 else
2263 proto_version = -1;
2264 PySSL_END_ALLOW_THREADS
2265
2266 if (proto_version == -1) {
2267 PyErr_SetString(PyExc_ValueError,
2268 "invalid protocol version");
2269 return NULL;
2270 }
2271 if (ctx == NULL) {
2272 PyErr_SetString(PySSLErrorObject,
2273 "failed to allocate SSL context");
2274 return NULL;
2275 }
2276
2277 assert(type != NULL && type->tp_alloc != NULL);
2278 self = (PySSLContext *) type->tp_alloc(type, 0);
2279 if (self == NULL) {
2280 SSL_CTX_free(ctx);
2281 return NULL;
2282 }
2283 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002284#ifdef OPENSSL_NPN_NEGOTIATED
2285 self->npn_protocols = NULL;
2286#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002287#ifdef HAVE_ALPN
2288 self->alpn_protocols = NULL;
2289#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002290#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002291 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002292#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002293 /* Don't check host name by default */
2294 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002295 /* Defaults */
2296 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002297 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2298 if (proto_version != PY_SSL_VERSION_SSL2)
2299 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002300 if (proto_version != PY_SSL_VERSION_SSL3)
2301 options |= SSL_OP_NO_SSLv3;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002302 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002303
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002304#if defined(SSL_MODE_RELEASE_BUFFERS)
2305 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2306 usage for no cost at all. However, don't do this for OpenSSL versions
2307 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2308 2014-0198. I can't find exactly which beta fixed this CVE, so be
2309 conservative and assume it wasn't fixed until release. We do this check
2310 at runtime to avoid problems from the dynamic linker.
2311 See #25672 for more on this. */
2312 libver = SSLeay();
2313 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2314 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2315 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2316 }
2317#endif
2318
2319
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002320#ifndef OPENSSL_NO_ECDH
2321 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2322 prime256v1 by default. This is Apache mod_ssl's initialization
2323 policy, so we should be safe. */
2324#if defined(SSL_CTX_set_ecdh_auto)
2325 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2326#else
2327 {
2328 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2329 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2330 EC_KEY_free(key);
2331 }
2332#endif
2333#endif
2334
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002335#define SID_CTX "Python"
2336 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2337 sizeof(SID_CTX));
2338#undef SID_CTX
2339
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002340#ifdef X509_V_FLAG_TRUSTED_FIRST
2341 {
2342 /* Improve trust chain building when cross-signed intermediate
2343 certificates are present. See https://bugs.python.org/issue23476. */
2344 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2345 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2346 }
2347#endif
2348
Antoine Pitrou152efa22010-05-16 18:19:27 +00002349 return (PyObject *)self;
2350}
2351
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002352static int
2353context_traverse(PySSLContext *self, visitproc visit, void *arg)
2354{
2355#ifndef OPENSSL_NO_TLSEXT
2356 Py_VISIT(self->set_hostname);
2357#endif
2358 return 0;
2359}
2360
2361static int
2362context_clear(PySSLContext *self)
2363{
2364#ifndef OPENSSL_NO_TLSEXT
2365 Py_CLEAR(self->set_hostname);
2366#endif
2367 return 0;
2368}
2369
Antoine Pitrou152efa22010-05-16 18:19:27 +00002370static void
2371context_dealloc(PySSLContext *self)
2372{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002373 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002374 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002375#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002376 PyMem_FREE(self->npn_protocols);
2377#endif
2378#ifdef HAVE_ALPN
2379 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002380#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002381 Py_TYPE(self)->tp_free(self);
2382}
2383
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002384/*[clinic input]
2385_ssl._SSLContext.set_ciphers
2386 cipherlist: str
2387 /
2388[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002389
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002390static PyObject *
2391_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2392/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2393{
2394 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002395 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002396 /* Clearing the error queue is necessary on some OpenSSL versions,
2397 otherwise the error will be reported again when another SSL call
2398 is done. */
2399 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002400 PyErr_SetString(PySSLErrorObject,
2401 "No cipher can be selected.");
2402 return NULL;
2403 }
2404 Py_RETURN_NONE;
2405}
2406
Benjamin Petersonc54de472015-01-28 12:06:39 -05002407#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002408static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002409do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2410 const unsigned char *server_protocols, unsigned int server_protocols_len,
2411 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002412{
Benjamin Peterson88615022015-01-23 17:30:26 -05002413 int ret;
2414 if (client_protocols == NULL) {
2415 client_protocols = (unsigned char *)"";
2416 client_protocols_len = 0;
2417 }
2418 if (server_protocols == NULL) {
2419 server_protocols = (unsigned char *)"";
2420 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002421 }
2422
Benjamin Peterson88615022015-01-23 17:30:26 -05002423 ret = SSL_select_next_proto(out, outlen,
2424 server_protocols, server_protocols_len,
2425 client_protocols, client_protocols_len);
2426 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2427 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002428
2429 return SSL_TLSEXT_ERR_OK;
2430}
2431
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002432/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2433static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002434_advertiseNPN_cb(SSL *s,
2435 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002436 void *args)
2437{
2438 PySSLContext *ssl_ctx = (PySSLContext *) args;
2439
2440 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002441 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002442 *len = 0;
2443 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002444 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002445 *len = ssl_ctx->npn_protocols_len;
2446 }
2447
2448 return SSL_TLSEXT_ERR_OK;
2449}
2450/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2451static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002452_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002453 unsigned char **out, unsigned char *outlen,
2454 const unsigned char *server, unsigned int server_len,
2455 void *args)
2456{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002457 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002458 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002459 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002460}
2461#endif
2462
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002463/*[clinic input]
2464_ssl._SSLContext._set_npn_protocols
2465 protos: Py_buffer
2466 /
2467[clinic start generated code]*/
2468
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002469static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002470_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2471 Py_buffer *protos)
2472/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002473{
2474#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002475 PyMem_Free(self->npn_protocols);
2476 self->npn_protocols = PyMem_Malloc(protos->len);
2477 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002478 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002479 memcpy(self->npn_protocols, protos->buf, protos->len);
2480 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002481
2482 /* set both server and client callbacks, because the context can
2483 * be used to create both types of sockets */
2484 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2485 _advertiseNPN_cb,
2486 self);
2487 SSL_CTX_set_next_proto_select_cb(self->ctx,
2488 _selectNPN_cb,
2489 self);
2490
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002491 Py_RETURN_NONE;
2492#else
2493 PyErr_SetString(PyExc_NotImplementedError,
2494 "The NPN extension requires OpenSSL 1.0.1 or later.");
2495 return NULL;
2496#endif
2497}
2498
Benjamin Petersoncca27322015-01-23 16:35:37 -05002499#ifdef HAVE_ALPN
2500static int
2501_selectALPN_cb(SSL *s,
2502 const unsigned char **out, unsigned char *outlen,
2503 const unsigned char *client_protocols, unsigned int client_protocols_len,
2504 void *args)
2505{
2506 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002507 return do_protocol_selection(1, (unsigned char **)out, outlen,
2508 ctx->alpn_protocols, ctx->alpn_protocols_len,
2509 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002510}
2511#endif
2512
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002513/*[clinic input]
2514_ssl._SSLContext._set_alpn_protocols
2515 protos: Py_buffer
2516 /
2517[clinic start generated code]*/
2518
Benjamin Petersoncca27322015-01-23 16:35:37 -05002519static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002520_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2521 Py_buffer *protos)
2522/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002523{
2524#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002525 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002526 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002527 if (!self->alpn_protocols)
2528 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002529 memcpy(self->alpn_protocols, protos->buf, protos->len);
2530 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002531
2532 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2533 return PyErr_NoMemory();
2534 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2535
Benjamin Petersoncca27322015-01-23 16:35:37 -05002536 Py_RETURN_NONE;
2537#else
2538 PyErr_SetString(PyExc_NotImplementedError,
2539 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2540 return NULL;
2541#endif
2542}
2543
Antoine Pitrou152efa22010-05-16 18:19:27 +00002544static PyObject *
2545get_verify_mode(PySSLContext *self, void *c)
2546{
2547 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2548 case SSL_VERIFY_NONE:
2549 return PyLong_FromLong(PY_SSL_CERT_NONE);
2550 case SSL_VERIFY_PEER:
2551 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2552 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2553 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2554 }
2555 PyErr_SetString(PySSLErrorObject,
2556 "invalid return value from SSL_CTX_get_verify_mode");
2557 return NULL;
2558}
2559
2560static int
2561set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2562{
2563 int n, mode;
2564 if (!PyArg_Parse(arg, "i", &n))
2565 return -1;
2566 if (n == PY_SSL_CERT_NONE)
2567 mode = SSL_VERIFY_NONE;
2568 else if (n == PY_SSL_CERT_OPTIONAL)
2569 mode = SSL_VERIFY_PEER;
2570 else if (n == PY_SSL_CERT_REQUIRED)
2571 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2572 else {
2573 PyErr_SetString(PyExc_ValueError,
2574 "invalid value for verify_mode");
2575 return -1;
2576 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002577 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2578 PyErr_SetString(PyExc_ValueError,
2579 "Cannot set verify_mode to CERT_NONE when "
2580 "check_hostname is enabled.");
2581 return -1;
2582 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002583 SSL_CTX_set_verify(self->ctx, mode, NULL);
2584 return 0;
2585}
2586
2587static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002588get_verify_flags(PySSLContext *self, void *c)
2589{
2590 X509_STORE *store;
2591 unsigned long flags;
2592
2593 store = SSL_CTX_get_cert_store(self->ctx);
2594 flags = X509_VERIFY_PARAM_get_flags(store->param);
2595 return PyLong_FromUnsignedLong(flags);
2596}
2597
2598static int
2599set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2600{
2601 X509_STORE *store;
2602 unsigned long new_flags, flags, set, clear;
2603
2604 if (!PyArg_Parse(arg, "k", &new_flags))
2605 return -1;
2606 store = SSL_CTX_get_cert_store(self->ctx);
2607 flags = X509_VERIFY_PARAM_get_flags(store->param);
2608 clear = flags & ~new_flags;
2609 set = ~flags & new_flags;
2610 if (clear) {
2611 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2612 _setSSLError(NULL, 0, __FILE__, __LINE__);
2613 return -1;
2614 }
2615 }
2616 if (set) {
2617 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2618 _setSSLError(NULL, 0, __FILE__, __LINE__);
2619 return -1;
2620 }
2621 }
2622 return 0;
2623}
2624
2625static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002626get_options(PySSLContext *self, void *c)
2627{
2628 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2629}
2630
2631static int
2632set_options(PySSLContext *self, PyObject *arg, void *c)
2633{
2634 long new_opts, opts, set, clear;
2635 if (!PyArg_Parse(arg, "l", &new_opts))
2636 return -1;
2637 opts = SSL_CTX_get_options(self->ctx);
2638 clear = opts & ~new_opts;
2639 set = ~opts & new_opts;
2640 if (clear) {
2641#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2642 SSL_CTX_clear_options(self->ctx, clear);
2643#else
2644 PyErr_SetString(PyExc_ValueError,
2645 "can't clear options before OpenSSL 0.9.8m");
2646 return -1;
2647#endif
2648 }
2649 if (set)
2650 SSL_CTX_set_options(self->ctx, set);
2651 return 0;
2652}
2653
Christian Heimes1aa9a752013-12-02 02:41:19 +01002654static PyObject *
2655get_check_hostname(PySSLContext *self, void *c)
2656{
2657 return PyBool_FromLong(self->check_hostname);
2658}
2659
2660static int
2661set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2662{
2663 int check_hostname;
2664 if (!PyArg_Parse(arg, "p", &check_hostname))
2665 return -1;
2666 if (check_hostname &&
2667 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2668 PyErr_SetString(PyExc_ValueError,
2669 "check_hostname needs a SSL context with either "
2670 "CERT_OPTIONAL or CERT_REQUIRED");
2671 return -1;
2672 }
2673 self->check_hostname = check_hostname;
2674 return 0;
2675}
2676
2677
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002678typedef struct {
2679 PyThreadState *thread_state;
2680 PyObject *callable;
2681 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002682 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002683 int error;
2684} _PySSLPasswordInfo;
2685
2686static int
2687_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2688 const char *bad_type_error)
2689{
2690 /* Set the password and size fields of a _PySSLPasswordInfo struct
2691 from a unicode, bytes, or byte array object.
2692 The password field will be dynamically allocated and must be freed
2693 by the caller */
2694 PyObject *password_bytes = NULL;
2695 const char *data = NULL;
2696 Py_ssize_t size;
2697
2698 if (PyUnicode_Check(password)) {
2699 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2700 if (!password_bytes) {
2701 goto error;
2702 }
2703 data = PyBytes_AS_STRING(password_bytes);
2704 size = PyBytes_GET_SIZE(password_bytes);
2705 } else if (PyBytes_Check(password)) {
2706 data = PyBytes_AS_STRING(password);
2707 size = PyBytes_GET_SIZE(password);
2708 } else if (PyByteArray_Check(password)) {
2709 data = PyByteArray_AS_STRING(password);
2710 size = PyByteArray_GET_SIZE(password);
2711 } else {
2712 PyErr_SetString(PyExc_TypeError, bad_type_error);
2713 goto error;
2714 }
2715
Victor Stinner9ee02032013-06-23 15:08:23 +02002716 if (size > (Py_ssize_t)INT_MAX) {
2717 PyErr_Format(PyExc_ValueError,
2718 "password cannot be longer than %d bytes", INT_MAX);
2719 goto error;
2720 }
2721
Victor Stinner11ebff22013-07-07 17:07:52 +02002722 PyMem_Free(pw_info->password);
2723 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002724 if (!pw_info->password) {
2725 PyErr_SetString(PyExc_MemoryError,
2726 "unable to allocate password buffer");
2727 goto error;
2728 }
2729 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002730 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002731
2732 Py_XDECREF(password_bytes);
2733 return 1;
2734
2735error:
2736 Py_XDECREF(password_bytes);
2737 return 0;
2738}
2739
2740static int
2741_password_callback(char *buf, int size, int rwflag, void *userdata)
2742{
2743 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2744 PyObject *fn_ret = NULL;
2745
2746 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2747
2748 if (pw_info->callable) {
2749 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2750 if (!fn_ret) {
2751 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2752 core python API, so we could use it to add a frame here */
2753 goto error;
2754 }
2755
2756 if (!_pwinfo_set(pw_info, fn_ret,
2757 "password callback must return a string")) {
2758 goto error;
2759 }
2760 Py_CLEAR(fn_ret);
2761 }
2762
2763 if (pw_info->size > size) {
2764 PyErr_Format(PyExc_ValueError,
2765 "password cannot be longer than %d bytes", size);
2766 goto error;
2767 }
2768
2769 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2770 memcpy(buf, pw_info->password, pw_info->size);
2771 return pw_info->size;
2772
2773error:
2774 Py_XDECREF(fn_ret);
2775 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2776 pw_info->error = 1;
2777 return -1;
2778}
2779
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002780/*[clinic input]
2781_ssl._SSLContext.load_cert_chain
2782 certfile: object
2783 keyfile: object = NULL
2784 password: object = NULL
2785
2786[clinic start generated code]*/
2787
Antoine Pitroub5218772010-05-21 09:56:06 +00002788static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002789_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
2790 PyObject *keyfile, PyObject *password)
2791/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002792{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002793 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002794 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2795 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2796 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002797 int r;
2798
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002799 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002800 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002801 if (keyfile == Py_None)
2802 keyfile = NULL;
2803 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2804 PyErr_SetString(PyExc_TypeError,
2805 "certfile should be a valid filesystem path");
2806 return NULL;
2807 }
2808 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2809 PyErr_SetString(PyExc_TypeError,
2810 "keyfile should be a valid filesystem path");
2811 goto error;
2812 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002813 if (password && password != Py_None) {
2814 if (PyCallable_Check(password)) {
2815 pw_info.callable = password;
2816 } else if (!_pwinfo_set(&pw_info, password,
2817 "password should be a string or callable")) {
2818 goto error;
2819 }
2820 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2821 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2822 }
2823 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002824 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2825 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002826 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002827 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002828 if (pw_info.error) {
2829 ERR_clear_error();
2830 /* the password callback has already set the error information */
2831 }
2832 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002833 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002834 PyErr_SetFromErrno(PyExc_IOError);
2835 }
2836 else {
2837 _setSSLError(NULL, 0, __FILE__, __LINE__);
2838 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002839 goto error;
2840 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002841 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002842 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002843 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2844 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002845 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2846 Py_CLEAR(keyfile_bytes);
2847 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002848 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002849 if (pw_info.error) {
2850 ERR_clear_error();
2851 /* the password callback has already set the error information */
2852 }
2853 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002854 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002855 PyErr_SetFromErrno(PyExc_IOError);
2856 }
2857 else {
2858 _setSSLError(NULL, 0, __FILE__, __LINE__);
2859 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002860 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002861 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002862 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002863 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002864 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002865 if (r != 1) {
2866 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002867 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002868 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002869 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2870 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002871 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002872 Py_RETURN_NONE;
2873
2874error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002875 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2876 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002877 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002878 Py_XDECREF(keyfile_bytes);
2879 Py_XDECREF(certfile_bytes);
2880 return NULL;
2881}
2882
Christian Heimesefff7062013-11-21 03:35:02 +01002883/* internal helper function, returns -1 on error
2884 */
2885static int
2886_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2887 int filetype)
2888{
2889 BIO *biobuf = NULL;
2890 X509_STORE *store;
2891 int retval = 0, err, loaded = 0;
2892
2893 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2894
2895 if (len <= 0) {
2896 PyErr_SetString(PyExc_ValueError,
2897 "Empty certificate data");
2898 return -1;
2899 } else if (len > INT_MAX) {
2900 PyErr_SetString(PyExc_OverflowError,
2901 "Certificate data is too long.");
2902 return -1;
2903 }
2904
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002905 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002906 if (biobuf == NULL) {
2907 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2908 return -1;
2909 }
2910
2911 store = SSL_CTX_get_cert_store(self->ctx);
2912 assert(store != NULL);
2913
2914 while (1) {
2915 X509 *cert = NULL;
2916 int r;
2917
2918 if (filetype == SSL_FILETYPE_ASN1) {
2919 cert = d2i_X509_bio(biobuf, NULL);
2920 } else {
2921 cert = PEM_read_bio_X509(biobuf, NULL,
2922 self->ctx->default_passwd_callback,
2923 self->ctx->default_passwd_callback_userdata);
2924 }
2925 if (cert == NULL) {
2926 break;
2927 }
2928 r = X509_STORE_add_cert(store, cert);
2929 X509_free(cert);
2930 if (!r) {
2931 err = ERR_peek_last_error();
2932 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2933 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2934 /* cert already in hash table, not an error */
2935 ERR_clear_error();
2936 } else {
2937 break;
2938 }
2939 }
2940 loaded++;
2941 }
2942
2943 err = ERR_peek_last_error();
2944 if ((filetype == SSL_FILETYPE_ASN1) &&
2945 (loaded > 0) &&
2946 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2947 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2948 /* EOF ASN1 file, not an error */
2949 ERR_clear_error();
2950 retval = 0;
2951 } else if ((filetype == SSL_FILETYPE_PEM) &&
2952 (loaded > 0) &&
2953 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2954 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2955 /* EOF PEM file, not an error */
2956 ERR_clear_error();
2957 retval = 0;
2958 } else {
2959 _setSSLError(NULL, 0, __FILE__, __LINE__);
2960 retval = -1;
2961 }
2962
2963 BIO_free(biobuf);
2964 return retval;
2965}
2966
2967
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002968/*[clinic input]
2969_ssl._SSLContext.load_verify_locations
2970 cafile: object = NULL
2971 capath: object = NULL
2972 cadata: object = NULL
2973
2974[clinic start generated code]*/
2975
Antoine Pitrou152efa22010-05-16 18:19:27 +00002976static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002977_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
2978 PyObject *cafile,
2979 PyObject *capath,
2980 PyObject *cadata)
2981/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002982{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002983 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2984 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002985 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002986
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002987 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002988 if (cafile == Py_None)
2989 cafile = NULL;
2990 if (capath == Py_None)
2991 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002992 if (cadata == Py_None)
2993 cadata = NULL;
2994
2995 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002996 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002997 "cafile, capath and cadata cannot be all omitted");
2998 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002999 }
3000 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3001 PyErr_SetString(PyExc_TypeError,
3002 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003003 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003004 }
3005 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003006 PyErr_SetString(PyExc_TypeError,
3007 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003008 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003009 }
Christian Heimesefff7062013-11-21 03:35:02 +01003010
3011 /* validata cadata type and load cadata */
3012 if (cadata) {
3013 Py_buffer buf;
3014 PyObject *cadata_ascii = NULL;
3015
3016 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3017 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3018 PyBuffer_Release(&buf);
3019 PyErr_SetString(PyExc_TypeError,
3020 "cadata should be a contiguous buffer with "
3021 "a single dimension");
3022 goto error;
3023 }
3024 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3025 PyBuffer_Release(&buf);
3026 if (r == -1) {
3027 goto error;
3028 }
3029 } else {
3030 PyErr_Clear();
3031 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3032 if (cadata_ascii == NULL) {
3033 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003034 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003035 "bytes-like object");
3036 goto error;
3037 }
3038 r = _add_ca_certs(self,
3039 PyBytes_AS_STRING(cadata_ascii),
3040 PyBytes_GET_SIZE(cadata_ascii),
3041 SSL_FILETYPE_PEM);
3042 Py_DECREF(cadata_ascii);
3043 if (r == -1) {
3044 goto error;
3045 }
3046 }
3047 }
3048
3049 /* load cafile or capath */
3050 if (cafile || capath) {
3051 if (cafile)
3052 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3053 if (capath)
3054 capath_buf = PyBytes_AS_STRING(capath_bytes);
3055 PySSL_BEGIN_ALLOW_THREADS
3056 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3057 PySSL_END_ALLOW_THREADS
3058 if (r != 1) {
3059 ok = 0;
3060 if (errno != 0) {
3061 ERR_clear_error();
3062 PyErr_SetFromErrno(PyExc_IOError);
3063 }
3064 else {
3065 _setSSLError(NULL, 0, __FILE__, __LINE__);
3066 }
3067 goto error;
3068 }
3069 }
3070 goto end;
3071
3072 error:
3073 ok = 0;
3074 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003075 Py_XDECREF(cafile_bytes);
3076 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003077 if (ok) {
3078 Py_RETURN_NONE;
3079 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003080 return NULL;
3081 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003082}
3083
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003084/*[clinic input]
3085_ssl._SSLContext.load_dh_params
3086 path as filepath: object
3087 /
3088
3089[clinic start generated code]*/
3090
Antoine Pitrou152efa22010-05-16 18:19:27 +00003091static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003092_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3093/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003094{
3095 FILE *f;
3096 DH *dh;
3097
Victor Stinnerdaf45552013-08-28 00:53:59 +02003098 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003099 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003100 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003101
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003102 errno = 0;
3103 PySSL_BEGIN_ALLOW_THREADS
3104 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003105 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003106 PySSL_END_ALLOW_THREADS
3107 if (dh == NULL) {
3108 if (errno != 0) {
3109 ERR_clear_error();
3110 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3111 }
3112 else {
3113 _setSSLError(NULL, 0, __FILE__, __LINE__);
3114 }
3115 return NULL;
3116 }
3117 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3118 _setSSLError(NULL, 0, __FILE__, __LINE__);
3119 DH_free(dh);
3120 Py_RETURN_NONE;
3121}
3122
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003123/*[clinic input]
3124_ssl._SSLContext._wrap_socket
3125 sock: object(subclass_of="PySocketModule.Sock_Type")
3126 server_side: int
3127 server_hostname as hostname_obj: object = None
3128
3129[clinic start generated code]*/
3130
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003131static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003132_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3133 int server_side, PyObject *hostname_obj)
3134/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003135{
Antoine Pitroud5323212010-10-22 18:19:07 +00003136 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003137 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003138
Antoine Pitroud5323212010-10-22 18:19:07 +00003139 /* server_hostname is either None (or absent), or to be encoded
3140 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003141 if (hostname_obj != Py_None) {
3142 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003143 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003144 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003145
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003146 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3147 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003148 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003149 if (hostname != NULL)
3150 PyMem_Free(hostname);
3151 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003152}
3153
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003154/*[clinic input]
3155_ssl._SSLContext._wrap_bio
3156 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3157 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3158 server_side: int
3159 server_hostname as hostname_obj: object = None
3160
3161[clinic start generated code]*/
3162
Antoine Pitroub0182c82010-10-12 20:09:02 +00003163static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003164_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3165 PySSLMemoryBIO *outgoing, int server_side,
3166 PyObject *hostname_obj)
3167/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003168{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003169 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003170 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003171
3172 /* server_hostname is either None (or absent), or to be encoded
3173 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003174 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003175 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3176 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003177 }
3178
3179 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3180 incoming, outgoing);
3181
3182 PyMem_Free(hostname);
3183 return res;
3184}
3185
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003186/*[clinic input]
3187_ssl._SSLContext.session_stats
3188[clinic start generated code]*/
3189
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003190static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003191_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3192/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003193{
3194 int r;
3195 PyObject *value, *stats = PyDict_New();
3196 if (!stats)
3197 return NULL;
3198
3199#define ADD_STATS(SSL_NAME, KEY_NAME) \
3200 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3201 if (value == NULL) \
3202 goto error; \
3203 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3204 Py_DECREF(value); \
3205 if (r < 0) \
3206 goto error;
3207
3208 ADD_STATS(number, "number");
3209 ADD_STATS(connect, "connect");
3210 ADD_STATS(connect_good, "connect_good");
3211 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3212 ADD_STATS(accept, "accept");
3213 ADD_STATS(accept_good, "accept_good");
3214 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3215 ADD_STATS(accept, "accept");
3216 ADD_STATS(hits, "hits");
3217 ADD_STATS(misses, "misses");
3218 ADD_STATS(timeouts, "timeouts");
3219 ADD_STATS(cache_full, "cache_full");
3220
3221#undef ADD_STATS
3222
3223 return stats;
3224
3225error:
3226 Py_DECREF(stats);
3227 return NULL;
3228}
3229
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003230/*[clinic input]
3231_ssl._SSLContext.set_default_verify_paths
3232[clinic start generated code]*/
3233
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003234static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003235_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3236/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003237{
3238 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3239 _setSSLError(NULL, 0, __FILE__, __LINE__);
3240 return NULL;
3241 }
3242 Py_RETURN_NONE;
3243}
3244
Antoine Pitrou501da612011-12-21 09:27:41 +01003245#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003246/*[clinic input]
3247_ssl._SSLContext.set_ecdh_curve
3248 name: object
3249 /
3250
3251[clinic start generated code]*/
3252
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003253static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003254_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3255/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003256{
3257 PyObject *name_bytes;
3258 int nid;
3259 EC_KEY *key;
3260
3261 if (!PyUnicode_FSConverter(name, &name_bytes))
3262 return NULL;
3263 assert(PyBytes_Check(name_bytes));
3264 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3265 Py_DECREF(name_bytes);
3266 if (nid == 0) {
3267 PyErr_Format(PyExc_ValueError,
3268 "unknown elliptic curve name %R", name);
3269 return NULL;
3270 }
3271 key = EC_KEY_new_by_curve_name(nid);
3272 if (key == NULL) {
3273 _setSSLError(NULL, 0, __FILE__, __LINE__);
3274 return NULL;
3275 }
3276 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3277 EC_KEY_free(key);
3278 Py_RETURN_NONE;
3279}
Antoine Pitrou501da612011-12-21 09:27:41 +01003280#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003281
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003282#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003283static int
3284_servername_callback(SSL *s, int *al, void *args)
3285{
3286 int ret;
3287 PySSLContext *ssl_ctx = (PySSLContext *) args;
3288 PySSLSocket *ssl;
3289 PyObject *servername_o;
3290 PyObject *servername_idna;
3291 PyObject *result;
3292 /* The high-level ssl.SSLSocket object */
3293 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003294 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003295#ifdef WITH_THREAD
3296 PyGILState_STATE gstate = PyGILState_Ensure();
3297#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003298
3299 if (ssl_ctx->set_hostname == NULL) {
3300 /* remove race condition in this the call back while if removing the
3301 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003302#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003303 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003304#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003305 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003306 }
3307
3308 ssl = SSL_get_app_data(s);
3309 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003310
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003311 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003312 * SSL connection and that has a .context attribute that can be changed to
3313 * identify the requested hostname. Since the official API is the Python
3314 * level API we want to pass the callback a Python level object rather than
3315 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3316 * SSLObject) that will be passed. Otherwise if there's a socket then that
3317 * will be passed. If both do not exist only then the C-level object is
3318 * passed. */
3319 if (ssl->owner)
3320 ssl_socket = PyWeakref_GetObject(ssl->owner);
3321 else if (ssl->Socket)
3322 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3323 else
3324 ssl_socket = (PyObject *) ssl;
3325
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003326 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003327 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003328 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003329
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003330 if (servername == NULL) {
3331 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3332 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003333 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003334 else {
3335 servername_o = PyBytes_FromString(servername);
3336 if (servername_o == NULL) {
3337 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3338 goto error;
3339 }
3340 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3341 if (servername_idna == NULL) {
3342 PyErr_WriteUnraisable(servername_o);
3343 Py_DECREF(servername_o);
3344 goto error;
3345 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003346 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003347 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3348 servername_idna, ssl_ctx, NULL);
3349 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003350 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003351 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003352
3353 if (result == NULL) {
3354 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3355 *al = SSL_AD_HANDSHAKE_FAILURE;
3356 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3357 }
3358 else {
3359 if (result != Py_None) {
3360 *al = (int) PyLong_AsLong(result);
3361 if (PyErr_Occurred()) {
3362 PyErr_WriteUnraisable(result);
3363 *al = SSL_AD_INTERNAL_ERROR;
3364 }
3365 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3366 }
3367 else {
3368 ret = SSL_TLSEXT_ERR_OK;
3369 }
3370 Py_DECREF(result);
3371 }
3372
Stefan Krah20d60802013-01-17 17:07:17 +01003373#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003374 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003375#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003376 return ret;
3377
3378error:
3379 Py_DECREF(ssl_socket);
3380 *al = SSL_AD_INTERNAL_ERROR;
3381 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003382#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003383 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003384#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003385 return ret;
3386}
Antoine Pitroua5963382013-03-30 16:39:00 +01003387#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003388
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003389/*[clinic input]
3390_ssl._SSLContext.set_servername_callback
3391 method as cb: object
3392 /
3393
3394Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3395
3396If the argument is None then the callback is disabled. The method is called
3397with the SSLSocket, the server name as a string, and the SSLContext object.
3398See RFC 6066 for details of the SNI extension.
3399[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003400
3401static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003402_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3403/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003404{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003405#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003406 Py_CLEAR(self->set_hostname);
3407 if (cb == Py_None) {
3408 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3409 }
3410 else {
3411 if (!PyCallable_Check(cb)) {
3412 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3413 PyErr_SetString(PyExc_TypeError,
3414 "not a callable object");
3415 return NULL;
3416 }
3417 Py_INCREF(cb);
3418 self->set_hostname = cb;
3419 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3420 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3421 }
3422 Py_RETURN_NONE;
3423#else
3424 PyErr_SetString(PyExc_NotImplementedError,
3425 "The TLS extension servername callback, "
3426 "SSL_CTX_set_tlsext_servername_callback, "
3427 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003428 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003429#endif
3430}
3431
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003432/*[clinic input]
3433_ssl._SSLContext.cert_store_stats
3434
3435Returns quantities of loaded X.509 certificates.
3436
3437X.509 certificates with a CA extension and certificate revocation lists
3438inside the context's cert store.
3439
3440NOTE: Certificates in a capath directory aren't loaded unless they have
3441been used at least once.
3442[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003443
3444static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003445_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3446/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003447{
3448 X509_STORE *store;
3449 X509_OBJECT *obj;
3450 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3451
3452 store = SSL_CTX_get_cert_store(self->ctx);
3453 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3454 obj = sk_X509_OBJECT_value(store->objs, i);
3455 switch (obj->type) {
3456 case X509_LU_X509:
3457 x509++;
3458 if (X509_check_ca(obj->data.x509)) {
3459 ca++;
3460 }
3461 break;
3462 case X509_LU_CRL:
3463 crl++;
3464 break;
3465 case X509_LU_PKEY:
3466 pkey++;
3467 break;
3468 default:
3469 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3470 * As far as I can tell they are internal states and never
3471 * stored in a cert store */
3472 break;
3473 }
3474 }
3475 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3476 "x509_ca", ca);
3477}
3478
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003479/*[clinic input]
3480_ssl._SSLContext.get_ca_certs
3481 binary_form: bool = False
3482
3483Returns a list of dicts with information of loaded CA certs.
3484
3485If the optional argument is True, returns a DER-encoded copy of the CA
3486certificate.
3487
3488NOTE: Certificates in a capath directory aren't loaded unless they have
3489been used at least once.
3490[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003491
3492static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003493_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3494/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003495{
3496 X509_STORE *store;
3497 PyObject *ci = NULL, *rlist = NULL;
3498 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003499
3500 if ((rlist = PyList_New(0)) == NULL) {
3501 return NULL;
3502 }
3503
3504 store = SSL_CTX_get_cert_store(self->ctx);
3505 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3506 X509_OBJECT *obj;
3507 X509 *cert;
3508
3509 obj = sk_X509_OBJECT_value(store->objs, i);
3510 if (obj->type != X509_LU_X509) {
3511 /* not a x509 cert */
3512 continue;
3513 }
3514 /* CA for any purpose */
3515 cert = obj->data.x509;
3516 if (!X509_check_ca(cert)) {
3517 continue;
3518 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003519 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003520 ci = _certificate_to_der(cert);
3521 } else {
3522 ci = _decode_certificate(cert);
3523 }
3524 if (ci == NULL) {
3525 goto error;
3526 }
3527 if (PyList_Append(rlist, ci) == -1) {
3528 goto error;
3529 }
3530 Py_CLEAR(ci);
3531 }
3532 return rlist;
3533
3534 error:
3535 Py_XDECREF(ci);
3536 Py_XDECREF(rlist);
3537 return NULL;
3538}
3539
3540
Antoine Pitrou152efa22010-05-16 18:19:27 +00003541static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003542 {"check_hostname", (getter) get_check_hostname,
3543 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003544 {"options", (getter) get_options,
3545 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003546 {"verify_flags", (getter) get_verify_flags,
3547 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003548 {"verify_mode", (getter) get_verify_mode,
3549 (setter) set_verify_mode, NULL},
3550 {NULL}, /* sentinel */
3551};
3552
3553static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003554 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
3555 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
3556 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
3557 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
3558 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
3559 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
3560 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
3561 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
3562 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
3563 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
3564 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
3565 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
3566 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
3567 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00003568 {NULL, NULL} /* sentinel */
3569};
3570
3571static PyTypeObject PySSLContext_Type = {
3572 PyVarObject_HEAD_INIT(NULL, 0)
3573 "_ssl._SSLContext", /*tp_name*/
3574 sizeof(PySSLContext), /*tp_basicsize*/
3575 0, /*tp_itemsize*/
3576 (destructor)context_dealloc, /*tp_dealloc*/
3577 0, /*tp_print*/
3578 0, /*tp_getattr*/
3579 0, /*tp_setattr*/
3580 0, /*tp_reserved*/
3581 0, /*tp_repr*/
3582 0, /*tp_as_number*/
3583 0, /*tp_as_sequence*/
3584 0, /*tp_as_mapping*/
3585 0, /*tp_hash*/
3586 0, /*tp_call*/
3587 0, /*tp_str*/
3588 0, /*tp_getattro*/
3589 0, /*tp_setattro*/
3590 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003591 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003592 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003593 (traverseproc) context_traverse, /*tp_traverse*/
3594 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003595 0, /*tp_richcompare*/
3596 0, /*tp_weaklistoffset*/
3597 0, /*tp_iter*/
3598 0, /*tp_iternext*/
3599 context_methods, /*tp_methods*/
3600 0, /*tp_members*/
3601 context_getsetlist, /*tp_getset*/
3602 0, /*tp_base*/
3603 0, /*tp_dict*/
3604 0, /*tp_descr_get*/
3605 0, /*tp_descr_set*/
3606 0, /*tp_dictoffset*/
3607 0, /*tp_init*/
3608 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003609 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003610};
3611
3612
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003613/*
3614 * MemoryBIO objects
3615 */
3616
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003617/*[clinic input]
3618@classmethod
3619_ssl.MemoryBIO.__new__
3620
3621[clinic start generated code]*/
3622
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003623static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003624_ssl_MemoryBIO_impl(PyTypeObject *type)
3625/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003626{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003627 BIO *bio;
3628 PySSLMemoryBIO *self;
3629
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003630 bio = BIO_new(BIO_s_mem());
3631 if (bio == NULL) {
3632 PyErr_SetString(PySSLErrorObject,
3633 "failed to allocate BIO");
3634 return NULL;
3635 }
3636 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3637 * just that no data is currently available. The SSL routines should retry
3638 * the read, which we can achieve by calling BIO_set_retry_read(). */
3639 BIO_set_retry_read(bio);
3640 BIO_set_mem_eof_return(bio, -1);
3641
3642 assert(type != NULL && type->tp_alloc != NULL);
3643 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3644 if (self == NULL) {
3645 BIO_free(bio);
3646 return NULL;
3647 }
3648 self->bio = bio;
3649 self->eof_written = 0;
3650
3651 return (PyObject *) self;
3652}
3653
3654static void
3655memory_bio_dealloc(PySSLMemoryBIO *self)
3656{
3657 BIO_free(self->bio);
3658 Py_TYPE(self)->tp_free(self);
3659}
3660
3661static PyObject *
3662memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3663{
3664 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3665}
3666
3667PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3668"The number of bytes pending in the memory BIO.");
3669
3670static PyObject *
3671memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3672{
3673 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3674 && self->eof_written);
3675}
3676
3677PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3678"Whether the memory BIO is at EOF.");
3679
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003680/*[clinic input]
3681_ssl.MemoryBIO.read
3682 size as len: int = -1
3683 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003684
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003685Read up to size bytes from the memory BIO.
3686
3687If size is not specified, read the entire buffer.
3688If the return value is an empty bytes instance, this means either
3689EOF or that no data is available. Use the "eof" property to
3690distinguish between the two.
3691[clinic start generated code]*/
3692
3693static PyObject *
3694_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
3695/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
3696{
3697 int avail, nbytes;
3698 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003699
3700 avail = BIO_ctrl_pending(self->bio);
3701 if ((len < 0) || (len > avail))
3702 len = avail;
3703
3704 result = PyBytes_FromStringAndSize(NULL, len);
3705 if ((result == NULL) || (len == 0))
3706 return result;
3707
3708 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3709 /* There should never be any short reads but check anyway. */
3710 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3711 Py_DECREF(result);
3712 return NULL;
3713 }
3714
3715 return result;
3716}
3717
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003718/*[clinic input]
3719_ssl.MemoryBIO.write
3720 b: Py_buffer
3721 /
3722
3723Writes the bytes b into the memory BIO.
3724
3725Returns the number of bytes written.
3726[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003727
3728static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003729_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
3730/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003731{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003732 int nbytes;
3733
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003734 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003735 PyErr_Format(PyExc_OverflowError,
3736 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003737 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003738 }
3739
3740 if (self->eof_written) {
3741 PyErr_SetString(PySSLErrorObject,
3742 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003743 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003744 }
3745
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003746 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003747 if (nbytes < 0) {
3748 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003749 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003750 }
3751
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003752 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003753}
3754
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003755/*[clinic input]
3756_ssl.MemoryBIO.write_eof
3757
3758Write an EOF marker to the memory BIO.
3759
3760When all data has been read, the "eof" property will be True.
3761[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003762
3763static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003764_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
3765/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003766{
3767 self->eof_written = 1;
3768 /* After an EOF is written, a zero return from read() should be a real EOF
3769 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3770 BIO_clear_retry_flags(self->bio);
3771 BIO_set_mem_eof_return(self->bio, 0);
3772
3773 Py_RETURN_NONE;
3774}
3775
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003776static PyGetSetDef memory_bio_getsetlist[] = {
3777 {"pending", (getter) memory_bio_get_pending, NULL,
3778 PySSL_memory_bio_pending_doc},
3779 {"eof", (getter) memory_bio_get_eof, NULL,
3780 PySSL_memory_bio_eof_doc},
3781 {NULL}, /* sentinel */
3782};
3783
3784static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003785 _SSL_MEMORYBIO_READ_METHODDEF
3786 _SSL_MEMORYBIO_WRITE_METHODDEF
3787 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003788 {NULL, NULL} /* sentinel */
3789};
3790
3791static PyTypeObject PySSLMemoryBIO_Type = {
3792 PyVarObject_HEAD_INIT(NULL, 0)
3793 "_ssl.MemoryBIO", /*tp_name*/
3794 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3795 0, /*tp_itemsize*/
3796 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3797 0, /*tp_print*/
3798 0, /*tp_getattr*/
3799 0, /*tp_setattr*/
3800 0, /*tp_reserved*/
3801 0, /*tp_repr*/
3802 0, /*tp_as_number*/
3803 0, /*tp_as_sequence*/
3804 0, /*tp_as_mapping*/
3805 0, /*tp_hash*/
3806 0, /*tp_call*/
3807 0, /*tp_str*/
3808 0, /*tp_getattro*/
3809 0, /*tp_setattro*/
3810 0, /*tp_as_buffer*/
3811 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3812 0, /*tp_doc*/
3813 0, /*tp_traverse*/
3814 0, /*tp_clear*/
3815 0, /*tp_richcompare*/
3816 0, /*tp_weaklistoffset*/
3817 0, /*tp_iter*/
3818 0, /*tp_iternext*/
3819 memory_bio_methods, /*tp_methods*/
3820 0, /*tp_members*/
3821 memory_bio_getsetlist, /*tp_getset*/
3822 0, /*tp_base*/
3823 0, /*tp_dict*/
3824 0, /*tp_descr_get*/
3825 0, /*tp_descr_set*/
3826 0, /*tp_dictoffset*/
3827 0, /*tp_init*/
3828 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003829 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003830};
3831
Antoine Pitrou152efa22010-05-16 18:19:27 +00003832
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003833/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003834/*[clinic input]
3835_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07003836 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003837 entropy: double
3838 /
3839
3840Mix string into the OpenSSL PRNG state.
3841
3842entropy (a float) is a lower bound on the entropy contained in
3843string. See RFC 1750.
3844[clinic start generated code]*/
3845
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003846static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003847_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
3848/*[clinic end generated code: output=e6dd48df9c9024e9 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003849{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02003850 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003851 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003852
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003853 buf = (const char *)view->buf;
3854 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003855 do {
3856 written = Py_MIN(len, INT_MAX);
3857 RAND_add(buf, (int)written, entropy);
3858 buf += written;
3859 len -= written;
3860 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003861 Py_INCREF(Py_None);
3862 return Py_None;
3863}
3864
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003865static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003866PySSL_RAND(int len, int pseudo)
3867{
3868 int ok;
3869 PyObject *bytes;
3870 unsigned long err;
3871 const char *errstr;
3872 PyObject *v;
3873
Victor Stinner1e81a392013-12-19 16:47:04 +01003874 if (len < 0) {
3875 PyErr_SetString(PyExc_ValueError, "num must be positive");
3876 return NULL;
3877 }
3878
Victor Stinner99c8b162011-05-24 12:05:19 +02003879 bytes = PyBytes_FromStringAndSize(NULL, len);
3880 if (bytes == NULL)
3881 return NULL;
3882 if (pseudo) {
3883 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3884 if (ok == 0 || ok == 1)
3885 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3886 }
3887 else {
3888 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3889 if (ok == 1)
3890 return bytes;
3891 }
3892 Py_DECREF(bytes);
3893
3894 err = ERR_get_error();
3895 errstr = ERR_reason_error_string(err);
3896 v = Py_BuildValue("(ks)", err, errstr);
3897 if (v != NULL) {
3898 PyErr_SetObject(PySSLErrorObject, v);
3899 Py_DECREF(v);
3900 }
3901 return NULL;
3902}
3903
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003904/*[clinic input]
3905_ssl.RAND_bytes
3906 n: int
3907 /
3908
3909Generate n cryptographically strong pseudo-random bytes.
3910[clinic start generated code]*/
3911
Victor Stinner99c8b162011-05-24 12:05:19 +02003912static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003913_ssl_RAND_bytes_impl(PyObject *module, int n)
3914/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003915{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003916 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02003917}
3918
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003919/*[clinic input]
3920_ssl.RAND_pseudo_bytes
3921 n: int
3922 /
3923
3924Generate n pseudo-random bytes.
3925
3926Return a pair (bytes, is_cryptographic). is_cryptographic is True
3927if the bytes generated are cryptographically strong.
3928[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003929
3930static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003931_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
3932/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003933{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003934 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02003935}
3936
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003937/*[clinic input]
3938_ssl.RAND_status
3939
3940Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
3941
3942It is necessary to seed the PRNG with RAND_add() on some platforms before
3943using the ssl() function.
3944[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003945
3946static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003947_ssl_RAND_status_impl(PyObject *module)
3948/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003949{
Christian Heimes217cfd12007-12-02 14:31:20 +00003950 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003951}
3952
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07003953#ifndef OPENSSL_NO_EGD
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003954/*[clinic input]
3955_ssl.RAND_egd
3956 path: object(converter="PyUnicode_FSConverter")
3957 /
3958
3959Queries the entropy gather daemon (EGD) on the socket named by 'path'.
3960
3961Returns number of bytes read. Raises SSLError if connection to EGD
3962fails or if it does not provide enough data to seed PRNG.
3963[clinic start generated code]*/
3964
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003965static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003966_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
3967/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003968{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003969 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003970 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003971 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003972 PyErr_SetString(PySSLErrorObject,
3973 "EGD connection failed or EGD did not return "
3974 "enough data to seed the PRNG");
3975 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003976 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003977 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003978}
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07003979#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003980
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003981
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003982
3983/*[clinic input]
3984_ssl.get_default_verify_paths
3985
3986Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
3987
3988The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
3989[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02003990
3991static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003992_ssl_get_default_verify_paths_impl(PyObject *module)
3993/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02003994{
3995 PyObject *ofile_env = NULL;
3996 PyObject *ofile = NULL;
3997 PyObject *odir_env = NULL;
3998 PyObject *odir = NULL;
3999
Benjamin Petersond113c962015-07-18 10:59:13 -07004000#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004001 const char *tmp = (info); \
4002 target = NULL; \
4003 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4004 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4005 target = PyBytes_FromString(tmp); } \
4006 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004007 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004008
Benjamin Petersond113c962015-07-18 10:59:13 -07004009 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4010 CONVERT(X509_get_default_cert_file(), ofile);
4011 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4012 CONVERT(X509_get_default_cert_dir(), odir);
4013#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004014
Christian Heimes200bb1b2013-06-14 15:14:29 +02004015 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004016
4017 error:
4018 Py_XDECREF(ofile_env);
4019 Py_XDECREF(ofile);
4020 Py_XDECREF(odir_env);
4021 Py_XDECREF(odir);
4022 return NULL;
4023}
4024
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004025static PyObject*
4026asn1obj2py(ASN1_OBJECT *obj)
4027{
4028 int nid;
4029 const char *ln, *sn;
4030 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004031 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004032
4033 nid = OBJ_obj2nid(obj);
4034 if (nid == NID_undef) {
4035 PyErr_Format(PyExc_ValueError, "Unknown object");
4036 return NULL;
4037 }
4038 sn = OBJ_nid2sn(nid);
4039 ln = OBJ_nid2ln(nid);
4040 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4041 if (buflen < 0) {
4042 _setSSLError(NULL, 0, __FILE__, __LINE__);
4043 return NULL;
4044 }
4045 if (buflen) {
4046 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4047 } else {
4048 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4049 }
4050}
4051
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004052/*[clinic input]
4053_ssl.txt2obj
4054 txt: str
4055 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004056
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004057Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4058
4059By default objects are looked up by OID. With name=True short and
4060long name are also matched.
4061[clinic start generated code]*/
4062
4063static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004064_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4065/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004066{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004067 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004068 ASN1_OBJECT *obj;
4069
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004070 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4071 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004072 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004073 return NULL;
4074 }
4075 result = asn1obj2py(obj);
4076 ASN1_OBJECT_free(obj);
4077 return result;
4078}
4079
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004080/*[clinic input]
4081_ssl.nid2obj
4082 nid: int
4083 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004084
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004085Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4086[clinic start generated code]*/
4087
4088static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004089_ssl_nid2obj_impl(PyObject *module, int nid)
4090/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004091{
4092 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004093 ASN1_OBJECT *obj;
4094
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004095 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004096 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004097 return NULL;
4098 }
4099 obj = OBJ_nid2obj(nid);
4100 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004101 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004102 return NULL;
4103 }
4104 result = asn1obj2py(obj);
4105 ASN1_OBJECT_free(obj);
4106 return result;
4107}
4108
Christian Heimes46bebee2013-06-09 19:03:31 +02004109#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004110
4111static PyObject*
4112certEncodingType(DWORD encodingType)
4113{
4114 static PyObject *x509_asn = NULL;
4115 static PyObject *pkcs_7_asn = NULL;
4116
4117 if (x509_asn == NULL) {
4118 x509_asn = PyUnicode_InternFromString("x509_asn");
4119 if (x509_asn == NULL)
4120 return NULL;
4121 }
4122 if (pkcs_7_asn == NULL) {
4123 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4124 if (pkcs_7_asn == NULL)
4125 return NULL;
4126 }
4127 switch(encodingType) {
4128 case X509_ASN_ENCODING:
4129 Py_INCREF(x509_asn);
4130 return x509_asn;
4131 case PKCS_7_ASN_ENCODING:
4132 Py_INCREF(pkcs_7_asn);
4133 return pkcs_7_asn;
4134 default:
4135 return PyLong_FromLong(encodingType);
4136 }
4137}
4138
4139static PyObject*
4140parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4141{
4142 CERT_ENHKEY_USAGE *usage;
4143 DWORD size, error, i;
4144 PyObject *retval;
4145
4146 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4147 error = GetLastError();
4148 if (error == CRYPT_E_NOT_FOUND) {
4149 Py_RETURN_TRUE;
4150 }
4151 return PyErr_SetFromWindowsErr(error);
4152 }
4153
4154 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4155 if (usage == NULL) {
4156 return PyErr_NoMemory();
4157 }
4158
4159 /* Now get the actual enhanced usage property */
4160 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4161 PyMem_Free(usage);
4162 error = GetLastError();
4163 if (error == CRYPT_E_NOT_FOUND) {
4164 Py_RETURN_TRUE;
4165 }
4166 return PyErr_SetFromWindowsErr(error);
4167 }
4168 retval = PySet_New(NULL);
4169 if (retval == NULL) {
4170 goto error;
4171 }
4172 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4173 if (usage->rgpszUsageIdentifier[i]) {
4174 PyObject *oid;
4175 int err;
4176 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4177 if (oid == NULL) {
4178 Py_CLEAR(retval);
4179 goto error;
4180 }
4181 err = PySet_Add(retval, oid);
4182 Py_DECREF(oid);
4183 if (err == -1) {
4184 Py_CLEAR(retval);
4185 goto error;
4186 }
4187 }
4188 }
4189 error:
4190 PyMem_Free(usage);
4191 return retval;
4192}
4193
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004194/*[clinic input]
4195_ssl.enum_certificates
4196 store_name: str
4197
4198Retrieve certificates from Windows' cert store.
4199
4200store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4201more cert storages, too. The function returns a list of (bytes,
4202encoding_type, trust) tuples. The encoding_type flag can be interpreted
4203with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4204a set of OIDs or the boolean True.
4205[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004206
Christian Heimes46bebee2013-06-09 19:03:31 +02004207static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004208_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4209/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004210{
Christian Heimes46bebee2013-06-09 19:03:31 +02004211 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004212 PCCERT_CONTEXT pCertCtx = NULL;
4213 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004214 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004215
Christian Heimes44109d72013-11-22 01:51:30 +01004216 result = PyList_New(0);
4217 if (result == NULL) {
4218 return NULL;
4219 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004220 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4221 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4222 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004223 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004224 Py_DECREF(result);
4225 return PyErr_SetFromWindowsErr(GetLastError());
4226 }
4227
Christian Heimes44109d72013-11-22 01:51:30 +01004228 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4229 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4230 pCertCtx->cbCertEncoded);
4231 if (!cert) {
4232 Py_CLEAR(result);
4233 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004234 }
Christian Heimes44109d72013-11-22 01:51:30 +01004235 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4236 Py_CLEAR(result);
4237 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004238 }
Christian Heimes44109d72013-11-22 01:51:30 +01004239 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4240 if (keyusage == Py_True) {
4241 Py_DECREF(keyusage);
4242 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004243 }
Christian Heimes44109d72013-11-22 01:51:30 +01004244 if (keyusage == NULL) {
4245 Py_CLEAR(result);
4246 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004247 }
Christian Heimes44109d72013-11-22 01:51:30 +01004248 if ((tup = PyTuple_New(3)) == NULL) {
4249 Py_CLEAR(result);
4250 break;
4251 }
4252 PyTuple_SET_ITEM(tup, 0, cert);
4253 cert = NULL;
4254 PyTuple_SET_ITEM(tup, 1, enc);
4255 enc = NULL;
4256 PyTuple_SET_ITEM(tup, 2, keyusage);
4257 keyusage = NULL;
4258 if (PyList_Append(result, tup) < 0) {
4259 Py_CLEAR(result);
4260 break;
4261 }
4262 Py_CLEAR(tup);
4263 }
4264 if (pCertCtx) {
4265 /* loop ended with an error, need to clean up context manually */
4266 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004267 }
4268
4269 /* In error cases cert, enc and tup may not be NULL */
4270 Py_XDECREF(cert);
4271 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004272 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004273 Py_XDECREF(tup);
4274
4275 if (!CertCloseStore(hStore, 0)) {
4276 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004277 Py_XDECREF(result);
4278 return PyErr_SetFromWindowsErr(GetLastError());
4279 }
4280 return result;
4281}
4282
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004283/*[clinic input]
4284_ssl.enum_crls
4285 store_name: str
4286
4287Retrieve CRLs from Windows' cert store.
4288
4289store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4290more cert storages, too. The function returns a list of (bytes,
4291encoding_type) tuples. The encoding_type flag can be interpreted with
4292X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4293[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004294
4295static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004296_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4297/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004298{
Christian Heimes44109d72013-11-22 01:51:30 +01004299 HCERTSTORE hStore = NULL;
4300 PCCRL_CONTEXT pCrlCtx = NULL;
4301 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4302 PyObject *result = NULL;
4303
Christian Heimes44109d72013-11-22 01:51:30 +01004304 result = PyList_New(0);
4305 if (result == NULL) {
4306 return NULL;
4307 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004308 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4309 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4310 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004311 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004312 Py_DECREF(result);
4313 return PyErr_SetFromWindowsErr(GetLastError());
4314 }
Christian Heimes44109d72013-11-22 01:51:30 +01004315
4316 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4317 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4318 pCrlCtx->cbCrlEncoded);
4319 if (!crl) {
4320 Py_CLEAR(result);
4321 break;
4322 }
4323 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4324 Py_CLEAR(result);
4325 break;
4326 }
4327 if ((tup = PyTuple_New(2)) == NULL) {
4328 Py_CLEAR(result);
4329 break;
4330 }
4331 PyTuple_SET_ITEM(tup, 0, crl);
4332 crl = NULL;
4333 PyTuple_SET_ITEM(tup, 1, enc);
4334 enc = NULL;
4335
4336 if (PyList_Append(result, tup) < 0) {
4337 Py_CLEAR(result);
4338 break;
4339 }
4340 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004341 }
Christian Heimes44109d72013-11-22 01:51:30 +01004342 if (pCrlCtx) {
4343 /* loop ended with an error, need to clean up context manually */
4344 CertFreeCRLContext(pCrlCtx);
4345 }
4346
4347 /* In error cases cert, enc and tup may not be NULL */
4348 Py_XDECREF(crl);
4349 Py_XDECREF(enc);
4350 Py_XDECREF(tup);
4351
4352 if (!CertCloseStore(hStore, 0)) {
4353 /* This error case might shadow another exception.*/
4354 Py_XDECREF(result);
4355 return PyErr_SetFromWindowsErr(GetLastError());
4356 }
4357 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004358}
Christian Heimes44109d72013-11-22 01:51:30 +01004359
4360#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004361
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004362/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004363static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004364 _SSL__TEST_DECODE_CERT_METHODDEF
4365 _SSL_RAND_ADD_METHODDEF
4366 _SSL_RAND_BYTES_METHODDEF
4367 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4368 _SSL_RAND_EGD_METHODDEF
4369 _SSL_RAND_STATUS_METHODDEF
4370 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
4371 _SSL_ENUM_CERTIFICATES_METHODDEF
4372 _SSL_ENUM_CRLS_METHODDEF
4373 _SSL_TXT2OBJ_METHODDEF
4374 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004375 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004376};
4377
4378
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004379#ifdef WITH_THREAD
4380
4381/* an implementation of OpenSSL threading operations in terms
4382 of the Python C thread library */
4383
4384static PyThread_type_lock *_ssl_locks = NULL;
4385
Christian Heimes4d98ca92013-08-19 17:36:29 +02004386#if OPENSSL_VERSION_NUMBER >= 0x10000000
4387/* use new CRYPTO_THREADID API. */
4388static void
4389_ssl_threadid_callback(CRYPTO_THREADID *id)
4390{
4391 CRYPTO_THREADID_set_numeric(id,
4392 (unsigned long)PyThread_get_thread_ident());
4393}
4394#else
4395/* deprecated CRYPTO_set_id_callback() API. */
4396static unsigned long
4397_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004398 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004399}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004400#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004401
Bill Janssen6e027db2007-11-15 22:23:56 +00004402static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004403 (int mode, int n, const char *file, int line) {
4404 /* this function is needed to perform locking on shared data
4405 structures. (Note that OpenSSL uses a number of global data
4406 structures that will be implicitly shared whenever multiple
4407 threads use OpenSSL.) Multi-threaded applications will
4408 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004409
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004410 locking_function() must be able to handle up to
4411 CRYPTO_num_locks() different mutex locks. It sets the n-th
4412 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004413
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004414 file and line are the file number of the function setting the
4415 lock. They can be useful for debugging.
4416 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004417
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004418 if ((_ssl_locks == NULL) ||
4419 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4420 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004421
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004422 if (mode & CRYPTO_LOCK) {
4423 PyThread_acquire_lock(_ssl_locks[n], 1);
4424 } else {
4425 PyThread_release_lock(_ssl_locks[n]);
4426 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004427}
4428
4429static int _setup_ssl_threads(void) {
4430
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004431 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004432
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004433 if (_ssl_locks == NULL) {
4434 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004435 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4436 if (_ssl_locks == NULL) {
4437 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004438 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004439 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004440 memset(_ssl_locks, 0,
4441 sizeof(PyThread_type_lock) * _ssl_locks_count);
4442 for (i = 0; i < _ssl_locks_count; i++) {
4443 _ssl_locks[i] = PyThread_allocate_lock();
4444 if (_ssl_locks[i] == NULL) {
4445 unsigned int j;
4446 for (j = 0; j < i; j++) {
4447 PyThread_free_lock(_ssl_locks[j]);
4448 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004449 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004450 return 0;
4451 }
4452 }
4453 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004454#if OPENSSL_VERSION_NUMBER >= 0x10000000
4455 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4456#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004457 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004458#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004459 }
4460 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004461}
4462
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004463#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004464
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004465PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004466"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004467for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004468
Martin v. Löwis1a214512008-06-11 05:26:20 +00004469
4470static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004471 PyModuleDef_HEAD_INIT,
4472 "_ssl",
4473 module_doc,
4474 -1,
4475 PySSL_methods,
4476 NULL,
4477 NULL,
4478 NULL,
4479 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004480};
4481
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004482
4483static void
4484parse_openssl_version(unsigned long libver,
4485 unsigned int *major, unsigned int *minor,
4486 unsigned int *fix, unsigned int *patch,
4487 unsigned int *status)
4488{
4489 *status = libver & 0xF;
4490 libver >>= 4;
4491 *patch = libver & 0xFF;
4492 libver >>= 8;
4493 *fix = libver & 0xFF;
4494 libver >>= 8;
4495 *minor = libver & 0xFF;
4496 libver >>= 8;
4497 *major = libver & 0xFF;
4498}
4499
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004500PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004501PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004502{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004503 PyObject *m, *d, *r;
4504 unsigned long libver;
4505 unsigned int major, minor, fix, patch, status;
4506 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004507 struct py_ssl_error_code *errcode;
4508 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004509
Antoine Pitrou152efa22010-05-16 18:19:27 +00004510 if (PyType_Ready(&PySSLContext_Type) < 0)
4511 return NULL;
4512 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004513 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004514 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4515 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004516
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004517 m = PyModule_Create(&_sslmodule);
4518 if (m == NULL)
4519 return NULL;
4520 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004521
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004522 /* Load _socket module and its C API */
4523 socket_api = PySocketModule_ImportModuleAndAPI();
4524 if (!socket_api)
4525 return NULL;
4526 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004527
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004528 /* Init OpenSSL */
4529 SSL_load_error_strings();
4530 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004531#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004532 /* note that this will start threading if not already started */
4533 if (!_setup_ssl_threads()) {
4534 return NULL;
4535 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004536#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004537 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004538
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004539 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004540 sslerror_type_slots[0].pfunc = PyExc_OSError;
4541 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004542 if (PySSLErrorObject == NULL)
4543 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004544
Antoine Pitrou41032a62011-10-27 23:56:55 +02004545 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4546 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4547 PySSLErrorObject, NULL);
4548 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4549 "ssl.SSLWantReadError", SSLWantReadError_doc,
4550 PySSLErrorObject, NULL);
4551 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4552 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4553 PySSLErrorObject, NULL);
4554 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4555 "ssl.SSLSyscallError", SSLSyscallError_doc,
4556 PySSLErrorObject, NULL);
4557 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4558 "ssl.SSLEOFError", SSLEOFError_doc,
4559 PySSLErrorObject, NULL);
4560 if (PySSLZeroReturnErrorObject == NULL
4561 || PySSLWantReadErrorObject == NULL
4562 || PySSLWantWriteErrorObject == NULL
4563 || PySSLSyscallErrorObject == NULL
4564 || PySSLEOFErrorObject == NULL)
4565 return NULL;
4566 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4567 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4568 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4569 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4570 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4571 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004572 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004573 if (PyDict_SetItemString(d, "_SSLContext",
4574 (PyObject *)&PySSLContext_Type) != 0)
4575 return NULL;
4576 if (PyDict_SetItemString(d, "_SSLSocket",
4577 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004578 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004579 if (PyDict_SetItemString(d, "MemoryBIO",
4580 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4581 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004582 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4583 PY_SSL_ERROR_ZERO_RETURN);
4584 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4585 PY_SSL_ERROR_WANT_READ);
4586 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4587 PY_SSL_ERROR_WANT_WRITE);
4588 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4589 PY_SSL_ERROR_WANT_X509_LOOKUP);
4590 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4591 PY_SSL_ERROR_SYSCALL);
4592 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4593 PY_SSL_ERROR_SSL);
4594 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4595 PY_SSL_ERROR_WANT_CONNECT);
4596 /* non ssl.h errorcodes */
4597 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4598 PY_SSL_ERROR_EOF);
4599 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4600 PY_SSL_ERROR_INVALID_ERROR_CODE);
4601 /* cert requirements */
4602 PyModule_AddIntConstant(m, "CERT_NONE",
4603 PY_SSL_CERT_NONE);
4604 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4605 PY_SSL_CERT_OPTIONAL);
4606 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4607 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004608 /* CRL verification for verification_flags */
4609 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4610 0);
4611 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4612 X509_V_FLAG_CRL_CHECK);
4613 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4614 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4615 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4616 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05004617#ifdef X509_V_FLAG_TRUSTED_FIRST
4618 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4619 X509_V_FLAG_TRUSTED_FIRST);
4620#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004621
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004622 /* Alert Descriptions from ssl.h */
4623 /* note RESERVED constants no longer intended for use have been removed */
4624 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4625
4626#define ADD_AD_CONSTANT(s) \
4627 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4628 SSL_AD_##s)
4629
4630 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4631 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4632 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4633 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4634 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4635 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4636 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4637 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4638 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4639 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4640 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4641 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4642 ADD_AD_CONSTANT(UNKNOWN_CA);
4643 ADD_AD_CONSTANT(ACCESS_DENIED);
4644 ADD_AD_CONSTANT(DECODE_ERROR);
4645 ADD_AD_CONSTANT(DECRYPT_ERROR);
4646 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4647 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4648 ADD_AD_CONSTANT(INTERNAL_ERROR);
4649 ADD_AD_CONSTANT(USER_CANCELLED);
4650 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004651 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004652#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4653 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4654#endif
4655#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4656 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4657#endif
4658#ifdef SSL_AD_UNRECOGNIZED_NAME
4659 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4660#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004661#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4662 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4663#endif
4664#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4665 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4666#endif
4667#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4668 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4669#endif
4670
4671#undef ADD_AD_CONSTANT
4672
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004673 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004674#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004675 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4676 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004677#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004678#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004679 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4680 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004681#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004682 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4683 PY_SSL_VERSION_SSL23);
4684 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4685 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004686#if HAVE_TLSv1_2
4687 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4688 PY_SSL_VERSION_TLS1_1);
4689 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4690 PY_SSL_VERSION_TLS1_2);
4691#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004692
Antoine Pitroub5218772010-05-21 09:56:06 +00004693 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004694 PyModule_AddIntConstant(m, "OP_ALL",
4695 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004696 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4697 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4698 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004699#if HAVE_TLSv1_2
4700 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4701 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4702#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004703 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4704 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004705 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004706#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004707 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004708#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004709#ifdef SSL_OP_NO_COMPRESSION
4710 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4711 SSL_OP_NO_COMPRESSION);
4712#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004713
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004714#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004715 r = Py_True;
4716#else
4717 r = Py_False;
4718#endif
4719 Py_INCREF(r);
4720 PyModule_AddObject(m, "HAS_SNI", r);
4721
Antoine Pitroud6494802011-07-21 01:11:30 +02004722 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004723 Py_INCREF(r);
4724 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4725
Antoine Pitrou501da612011-12-21 09:27:41 +01004726#ifdef OPENSSL_NO_ECDH
4727 r = Py_False;
4728#else
4729 r = Py_True;
4730#endif
4731 Py_INCREF(r);
4732 PyModule_AddObject(m, "HAS_ECDH", r);
4733
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004734#ifdef OPENSSL_NPN_NEGOTIATED
4735 r = Py_True;
4736#else
4737 r = Py_False;
4738#endif
4739 Py_INCREF(r);
4740 PyModule_AddObject(m, "HAS_NPN", r);
4741
Benjamin Petersoncca27322015-01-23 16:35:37 -05004742#ifdef HAVE_ALPN
4743 r = Py_True;
4744#else
4745 r = Py_False;
4746#endif
4747 Py_INCREF(r);
4748 PyModule_AddObject(m, "HAS_ALPN", r);
4749
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004750 /* Mappings for error codes */
4751 err_codes_to_names = PyDict_New();
4752 err_names_to_codes = PyDict_New();
4753 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4754 return NULL;
4755 errcode = error_codes;
4756 while (errcode->mnemonic != NULL) {
4757 PyObject *mnemo, *key;
4758 mnemo = PyUnicode_FromString(errcode->mnemonic);
4759 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4760 if (mnemo == NULL || key == NULL)
4761 return NULL;
4762 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4763 return NULL;
4764 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4765 return NULL;
4766 Py_DECREF(key);
4767 Py_DECREF(mnemo);
4768 errcode++;
4769 }
4770 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4771 return NULL;
4772 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4773 return NULL;
4774
4775 lib_codes_to_names = PyDict_New();
4776 if (lib_codes_to_names == NULL)
4777 return NULL;
4778 libcode = library_codes;
4779 while (libcode->library != NULL) {
4780 PyObject *mnemo, *key;
4781 key = PyLong_FromLong(libcode->code);
4782 mnemo = PyUnicode_FromString(libcode->library);
4783 if (key == NULL || mnemo == NULL)
4784 return NULL;
4785 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4786 return NULL;
4787 Py_DECREF(key);
4788 Py_DECREF(mnemo);
4789 libcode++;
4790 }
4791 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4792 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004793
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004794 /* OpenSSL version */
4795 /* SSLeay() gives us the version of the library linked against,
4796 which could be different from the headers version.
4797 */
4798 libver = SSLeay();
4799 r = PyLong_FromUnsignedLong(libver);
4800 if (r == NULL)
4801 return NULL;
4802 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4803 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004804 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004805 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4806 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4807 return NULL;
4808 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4809 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4810 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004811
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004812 libver = OPENSSL_VERSION_NUMBER;
4813 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4814 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4815 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4816 return NULL;
4817
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004818 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004819}