blob: ca3549c6570bfbb916e8641e280df6e88643e3ea [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 Petersoncca27322015-01-23 16:35:37 -0500112/* ALPN added in OpenSSL 1.0.2 */
Benjamin Peterson07f05152015-01-27 11:10:18 -0500113#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
Benjamin Petersoncca27322015-01-23 16:35:37 -0500114# define HAVE_ALPN
115#endif
116
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000117enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000118 /* these mirror ssl.h */
119 PY_SSL_ERROR_NONE,
120 PY_SSL_ERROR_SSL,
121 PY_SSL_ERROR_WANT_READ,
122 PY_SSL_ERROR_WANT_WRITE,
123 PY_SSL_ERROR_WANT_X509_LOOKUP,
124 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
125 PY_SSL_ERROR_ZERO_RETURN,
126 PY_SSL_ERROR_WANT_CONNECT,
127 /* start of non ssl.h errorcodes */
128 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
129 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
130 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000131};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000132
Thomas Woutersed03b412007-08-28 21:37:11 +0000133enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000134 PY_SSL_CLIENT,
135 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000136};
137
138enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000139 PY_SSL_CERT_NONE,
140 PY_SSL_CERT_OPTIONAL,
141 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000142};
143
144enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000145 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200146 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000147 PY_SSL_VERSION_SSL23,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100148#if HAVE_TLSv1_2
149 PY_SSL_VERSION_TLS1,
150 PY_SSL_VERSION_TLS1_1,
151 PY_SSL_VERSION_TLS1_2
152#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000153 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000154#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100155};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200156
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000157#ifdef WITH_THREAD
158
159/* serves as a flag to see whether we've initialized the SSL thread support. */
160/* 0 means no, greater than 0 means yes */
161
162static unsigned int _ssl_locks_count = 0;
163
164#endif /* def WITH_THREAD */
165
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000166/* SSL socket object */
167
168#define X509_NAME_MAXLEN 256
169
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000170/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
171 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
172 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
173#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000174# define HAVE_SSL_CTX_CLEAR_OPTIONS
175#else
176# undef HAVE_SSL_CTX_CLEAR_OPTIONS
177#endif
178
Antoine Pitroud6494802011-07-21 01:11:30 +0200179/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
180 * older SSL, but let's be safe */
181#define PySSL_CB_MAXLEN 128
182
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100183
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000184typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000185 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000186 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100187#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -0500188 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100189 int npn_protocols_len;
190#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500191#ifdef HAVE_ALPN
192 unsigned char *alpn_protocols;
193 int alpn_protocols_len;
194#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100195#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200196 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100197#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100198 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000199} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000200
Antoine Pitrou152efa22010-05-16 18:19:27 +0000201typedef struct {
202 PyObject_HEAD
203 PyObject *Socket; /* weakref to socket on which we're layered */
204 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100205 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000206 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200207 char shutdown_seen_zero;
208 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200209 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200210 PyObject *owner; /* Python level "owner" passed to servername callback */
211 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000212} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000213
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200214typedef struct {
215 PyObject_HEAD
216 BIO *bio;
217 int eof_written;
218} PySSLMemoryBIO;
219
Antoine Pitrou152efa22010-05-16 18:19:27 +0000220static PyTypeObject PySSLContext_Type;
221static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200222static PyTypeObject PySSLMemoryBIO_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000223
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300224/*[clinic input]
225module _ssl
226class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
227class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
228class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
229[clinic start generated code]*/
230/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7bf7cb832638e2e1]*/
231
232#include "clinic/_ssl.c.h"
233
Victor Stinner14690702015-04-06 22:46:13 +0200234static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000235
Antoine Pitrou152efa22010-05-16 18:19:27 +0000236#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
237#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200238#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000239
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000240typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000241 SOCKET_IS_NONBLOCKING,
242 SOCKET_IS_BLOCKING,
243 SOCKET_HAS_TIMED_OUT,
244 SOCKET_HAS_BEEN_CLOSED,
245 SOCKET_TOO_LARGE_FOR_SELECT,
246 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000247} timeout_state;
248
Thomas Woutersed03b412007-08-28 21:37:11 +0000249/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000250#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200251#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000252
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200253/* Get the socket from a PySSLSocket, if it has one */
254#define GET_SOCKET(obj) ((obj)->Socket ? \
255 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200256
Victor Stinner14690702015-04-06 22:46:13 +0200257/* If sock is NULL, use a timeout of 0 second */
258#define GET_SOCKET_TIMEOUT(sock) \
259 ((sock != NULL) ? (sock)->sock_timeout : 0)
260
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200261/*
262 * SSL errors.
263 */
264
265PyDoc_STRVAR(SSLError_doc,
266"An error occurred in the SSL implementation.");
267
268PyDoc_STRVAR(SSLZeroReturnError_doc,
269"SSL/TLS session closed cleanly.");
270
271PyDoc_STRVAR(SSLWantReadError_doc,
272"Non-blocking SSL socket needs to read more data\n"
273"before the requested operation can be completed.");
274
275PyDoc_STRVAR(SSLWantWriteError_doc,
276"Non-blocking SSL socket needs to write more data\n"
277"before the requested operation can be completed.");
278
279PyDoc_STRVAR(SSLSyscallError_doc,
280"System error when attempting SSL operation.");
281
282PyDoc_STRVAR(SSLEOFError_doc,
283"SSL/TLS connection terminated abruptly.");
284
285static PyObject *
286SSLError_str(PyOSErrorObject *self)
287{
288 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
289 Py_INCREF(self->strerror);
290 return self->strerror;
291 }
292 else
293 return PyObject_Str(self->args);
294}
295
296static PyType_Slot sslerror_type_slots[] = {
297 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
298 {Py_tp_doc, SSLError_doc},
299 {Py_tp_str, SSLError_str},
300 {0, 0},
301};
302
303static PyType_Spec sslerror_type_spec = {
304 "ssl.SSLError",
305 sizeof(PyOSErrorObject),
306 0,
307 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
308 sslerror_type_slots
309};
310
311static void
312fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
313 int lineno, unsigned long errcode)
314{
315 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
316 PyObject *init_value, *msg, *key;
317 _Py_IDENTIFIER(reason);
318 _Py_IDENTIFIER(library);
319
320 if (errcode != 0) {
321 int lib, reason;
322
323 lib = ERR_GET_LIB(errcode);
324 reason = ERR_GET_REASON(errcode);
325 key = Py_BuildValue("ii", lib, reason);
326 if (key == NULL)
327 goto fail;
328 reason_obj = PyDict_GetItem(err_codes_to_names, key);
329 Py_DECREF(key);
330 if (reason_obj == NULL) {
331 /* XXX if reason < 100, it might reflect a library number (!!) */
332 PyErr_Clear();
333 }
334 key = PyLong_FromLong(lib);
335 if (key == NULL)
336 goto fail;
337 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
338 Py_DECREF(key);
339 if (lib_obj == NULL) {
340 PyErr_Clear();
341 }
342 if (errstr == NULL)
343 errstr = ERR_reason_error_string(errcode);
344 }
345 if (errstr == NULL)
346 errstr = "unknown error";
347
348 if (reason_obj && lib_obj)
349 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
350 lib_obj, reason_obj, errstr, lineno);
351 else if (lib_obj)
352 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
353 lib_obj, errstr, lineno);
354 else
355 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200356 if (msg == NULL)
357 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100358
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200359 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100360 if (init_value == NULL)
361 goto fail;
362
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200363 err_value = PyObject_CallObject(type, init_value);
364 Py_DECREF(init_value);
365 if (err_value == NULL)
366 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100367
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200368 if (reason_obj == NULL)
369 reason_obj = Py_None;
370 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
371 goto fail;
372 if (lib_obj == NULL)
373 lib_obj = Py_None;
374 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
375 goto fail;
376 PyErr_SetObject(type, err_value);
377fail:
378 Py_XDECREF(err_value);
379}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000380
381static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000382PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000383{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200384 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200385 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000386 int err;
387 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200388 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000389
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000390 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200391 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000392
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000393 if (obj->ssl != NULL) {
394 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000395
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000396 switch (err) {
397 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200398 errstr = "TLS/SSL connection has been closed (EOF)";
399 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000400 p = PY_SSL_ERROR_ZERO_RETURN;
401 break;
402 case SSL_ERROR_WANT_READ:
403 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200404 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000405 p = PY_SSL_ERROR_WANT_READ;
406 break;
407 case SSL_ERROR_WANT_WRITE:
408 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200409 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000410 errstr = "The operation did not complete (write)";
411 break;
412 case SSL_ERROR_WANT_X509_LOOKUP:
413 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000414 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000415 break;
416 case SSL_ERROR_WANT_CONNECT:
417 p = PY_SSL_ERROR_WANT_CONNECT;
418 errstr = "The operation did not complete (connect)";
419 break;
420 case SSL_ERROR_SYSCALL:
421 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000422 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200423 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000424 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000425 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200426 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000427 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200428 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000429 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000430 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000431 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200432 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000433 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200434 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000435 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000436 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200437 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000438 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000439 }
440 } else {
441 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000442 }
443 break;
444 }
445 case SSL_ERROR_SSL:
446 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000447 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200448 if (e == 0)
449 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000450 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000451 break;
452 }
453 default:
454 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
455 errstr = "Invalid error code";
456 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000457 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200458 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000459 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000460 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000461}
462
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000463static PyObject *
464_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
465
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200466 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000467 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200468 else
469 errcode = 0;
470 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000471 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000472 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000473}
474
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200475/*
476 * SSL objects
477 */
478
Antoine Pitrou152efa22010-05-16 18:19:27 +0000479static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100480newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000481 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200482 char *server_hostname,
483 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000484{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000485 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100486 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200487 PyObject *hostname;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200488 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000489
Antoine Pitrou152efa22010-05-16 18:19:27 +0000490 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000491 if (self == NULL)
492 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000493
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000494 self->peer_cert = NULL;
495 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000496 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100497 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200498 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200499 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200500 self->owner = NULL;
501 if (server_hostname != NULL) {
502 hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
503 "idna", "strict");
504 if (hostname == NULL) {
505 Py_DECREF(self);
506 return NULL;
507 }
508 self->server_hostname = hostname;
509 } else
510 self->server_hostname = NULL;
511
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100512 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000513
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000514 /* Make sure the SSL error state is initialized */
515 (void) ERR_get_state();
516 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000519 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000520 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200521 SSL_set_app_data(self->ssl, self);
522 if (sock) {
523 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
524 } else {
525 /* BIOs are reference counted and SSL_set_bio borrows our reference.
526 * To prevent a double free in memory_bio_dealloc() we need to take an
527 * extra reference here. */
528 CRYPTO_add(&inbio->bio->references, 1, CRYPTO_LOCK_BIO);
529 CRYPTO_add(&outbio->bio->references, 1, CRYPTO_LOCK_BIO);
530 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
531 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200532 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000533#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200534 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000535#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200536 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000537
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100538#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000539 if (server_hostname != NULL)
540 SSL_set_tlsext_host_name(self->ssl, server_hostname);
541#endif
542
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000543 /* If the socket is in non-blocking mode or timeout mode, set the BIO
544 * to non-blocking mode (blocking is the default)
545 */
Victor Stinnere2452312015-03-28 03:00:46 +0100546 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000547 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
548 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
549 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000550
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000551 PySSL_BEGIN_ALLOW_THREADS
552 if (socket_type == PY_SSL_CLIENT)
553 SSL_set_connect_state(self->ssl);
554 else
555 SSL_set_accept_state(self->ssl);
556 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000557
Antoine Pitroud6494802011-07-21 01:11:30 +0200558 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200559 if (sock != NULL) {
560 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
561 if (self->Socket == NULL) {
562 Py_DECREF(self);
563 Py_XDECREF(self->server_hostname);
564 return NULL;
565 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100566 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000567 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000568}
569
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000570/* SSL object methods */
571
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300572/*[clinic input]
573_ssl._SSLSocket.do_handshake
574[clinic start generated code]*/
575
576static PyObject *
577_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
578/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000579{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000580 int ret;
581 int err;
582 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200583 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200584 _PyTime_t timeout, deadline = 0;
585 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000586
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200587 if (sock) {
588 if (((PyObject*)sock) == Py_None) {
589 _setSSLError("Underlying socket connection gone",
590 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
591 return NULL;
592 }
593 Py_INCREF(sock);
594
595 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100596 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200597 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
598 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000599 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000600
Victor Stinner14690702015-04-06 22:46:13 +0200601 timeout = GET_SOCKET_TIMEOUT(sock);
602 has_timeout = (timeout > 0);
603 if (has_timeout)
604 deadline = _PyTime_GetMonotonicClock() + timeout;
605
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000606 /* Actually negotiate SSL connection */
607 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000608 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000609 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000610 ret = SSL_do_handshake(self->ssl);
611 err = SSL_get_error(self->ssl, ret);
612 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200613
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000614 if (PyErr_CheckSignals())
615 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200616
Victor Stinner14690702015-04-06 22:46:13 +0200617 if (has_timeout)
618 timeout = deadline - _PyTime_GetMonotonicClock();
619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000620 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200621 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000622 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200623 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000624 } else {
625 sockstate = SOCKET_OPERATION_OK;
626 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200627
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000628 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000629 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000630 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000631 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000632 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
633 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000634 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000635 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000636 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
637 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000638 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000639 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000640 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
641 break;
642 }
643 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200644 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000645 if (ret < 1)
646 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000647
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000648 if (self->peer_cert)
649 X509_free (self->peer_cert);
650 PySSL_BEGIN_ALLOW_THREADS
651 self->peer_cert = SSL_get_peer_certificate(self->ssl);
652 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200653 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000654
655 Py_INCREF(Py_None);
656 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000657
658error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200659 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000660 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000661}
662
Thomas Woutersed03b412007-08-28 21:37:11 +0000663static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000664_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000665
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 char namebuf[X509_NAME_MAXLEN];
667 int buflen;
668 PyObject *name_obj;
669 PyObject *value_obj;
670 PyObject *attr;
671 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000672
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000673 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
674 if (buflen < 0) {
675 _setSSLError(NULL, 0, __FILE__, __LINE__);
676 goto fail;
677 }
678 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
679 if (name_obj == NULL)
680 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000681
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000682 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
683 if (buflen < 0) {
684 _setSSLError(NULL, 0, __FILE__, __LINE__);
685 Py_DECREF(name_obj);
686 goto fail;
687 }
688 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000689 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000690 OPENSSL_free(valuebuf);
691 if (value_obj == NULL) {
692 Py_DECREF(name_obj);
693 goto fail;
694 }
695 attr = PyTuple_New(2);
696 if (attr == NULL) {
697 Py_DECREF(name_obj);
698 Py_DECREF(value_obj);
699 goto fail;
700 }
701 PyTuple_SET_ITEM(attr, 0, name_obj);
702 PyTuple_SET_ITEM(attr, 1, value_obj);
703 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000704
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000705 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000706 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000707}
708
709static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000710_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000711{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000712 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
713 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
714 PyObject *rdnt;
715 PyObject *attr = NULL; /* tuple to hold an attribute */
716 int entry_count = X509_NAME_entry_count(xname);
717 X509_NAME_ENTRY *entry;
718 ASN1_OBJECT *name;
719 ASN1_STRING *value;
720 int index_counter;
721 int rdn_level = -1;
722 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000723
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000724 dn = PyList_New(0);
725 if (dn == NULL)
726 return NULL;
727 /* now create another tuple to hold the top-level RDN */
728 rdn = PyList_New(0);
729 if (rdn == NULL)
730 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000731
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000732 for (index_counter = 0;
733 index_counter < entry_count;
734 index_counter++)
735 {
736 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000737
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000738 /* check to see if we've gotten to a new RDN */
739 if (rdn_level >= 0) {
740 if (rdn_level != entry->set) {
741 /* yes, new RDN */
742 /* add old RDN to DN */
743 rdnt = PyList_AsTuple(rdn);
744 Py_DECREF(rdn);
745 if (rdnt == NULL)
746 goto fail0;
747 retcode = PyList_Append(dn, rdnt);
748 Py_DECREF(rdnt);
749 if (retcode < 0)
750 goto fail0;
751 /* create new RDN */
752 rdn = PyList_New(0);
753 if (rdn == NULL)
754 goto fail0;
755 }
756 }
757 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000758
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000759 /* now add this attribute to the current RDN */
760 name = X509_NAME_ENTRY_get_object(entry);
761 value = X509_NAME_ENTRY_get_data(entry);
762 attr = _create_tuple_for_attribute(name, value);
763 /*
764 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
765 entry->set,
766 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
767 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
768 */
769 if (attr == NULL)
770 goto fail1;
771 retcode = PyList_Append(rdn, attr);
772 Py_DECREF(attr);
773 if (retcode < 0)
774 goto fail1;
775 }
776 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100777 if (rdn != NULL) {
778 if (PyList_GET_SIZE(rdn) > 0) {
779 rdnt = PyList_AsTuple(rdn);
780 Py_DECREF(rdn);
781 if (rdnt == NULL)
782 goto fail0;
783 retcode = PyList_Append(dn, rdnt);
784 Py_DECREF(rdnt);
785 if (retcode < 0)
786 goto fail0;
787 }
788 else {
789 Py_DECREF(rdn);
790 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000791 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000792
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000793 /* convert list to tuple */
794 rdnt = PyList_AsTuple(dn);
795 Py_DECREF(dn);
796 if (rdnt == NULL)
797 return NULL;
798 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000799
800 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000801 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802
803 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000804 Py_XDECREF(dn);
805 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000806}
807
808static PyObject *
809_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000810
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000811 /* this code follows the procedure outlined in
812 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
813 function to extract the STACK_OF(GENERAL_NAME),
814 then iterates through the stack to add the
815 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000816
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000817 int i, j;
818 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200819 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000820 X509_EXTENSION *ext = NULL;
821 GENERAL_NAMES *names = NULL;
822 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000823 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000824 BIO *biobuf = NULL;
825 char buf[2048];
826 char *vptr;
827 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000828 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 if (certificate == NULL)
831 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000832
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 /* get a memory buffer */
834 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000835
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200836 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000837 while ((i = X509_get_ext_by_NID(
838 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000839
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 if (peer_alt_names == Py_None) {
841 peer_alt_names = PyList_New(0);
842 if (peer_alt_names == NULL)
843 goto fail;
844 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000845
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000846 /* now decode the altName */
847 ext = X509_get_ext(certificate, i);
848 if(!(method = X509V3_EXT_get(ext))) {
849 PyErr_SetString
850 (PySSLErrorObject,
851 ERRSTR("No method for internalizing subjectAltName!"));
852 goto fail;
853 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000854
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000855 p = ext->value->data;
856 if (method->it)
857 names = (GENERAL_NAMES*)
858 (ASN1_item_d2i(NULL,
859 &p,
860 ext->value->length,
861 ASN1_ITEM_ptr(method->it)));
862 else
863 names = (GENERAL_NAMES*)
864 (method->d2i(NULL,
865 &p,
866 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000867
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000868 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000869 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200870 int gntype;
871 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000872
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000873 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200874 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200875 switch (gntype) {
876 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000877 /* we special-case DirName as a tuple of
878 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000879
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000880 t = PyTuple_New(2);
881 if (t == NULL) {
882 goto fail;
883 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000884
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000885 v = PyUnicode_FromString("DirName");
886 if (v == NULL) {
887 Py_DECREF(t);
888 goto fail;
889 }
890 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000891
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000892 v = _create_tuple_for_X509_NAME (name->d.dirn);
893 if (v == NULL) {
894 Py_DECREF(t);
895 goto fail;
896 }
897 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200898 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000899
Christian Heimes824f7f32013-08-17 00:54:47 +0200900 case GEN_EMAIL:
901 case GEN_DNS:
902 case GEN_URI:
903 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
904 correctly, CVE-2013-4238 */
905 t = PyTuple_New(2);
906 if (t == NULL)
907 goto fail;
908 switch (gntype) {
909 case GEN_EMAIL:
910 v = PyUnicode_FromString("email");
911 as = name->d.rfc822Name;
912 break;
913 case GEN_DNS:
914 v = PyUnicode_FromString("DNS");
915 as = name->d.dNSName;
916 break;
917 case GEN_URI:
918 v = PyUnicode_FromString("URI");
919 as = name->d.uniformResourceIdentifier;
920 break;
921 }
922 if (v == NULL) {
923 Py_DECREF(t);
924 goto fail;
925 }
926 PyTuple_SET_ITEM(t, 0, v);
927 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
928 ASN1_STRING_length(as));
929 if (v == NULL) {
930 Py_DECREF(t);
931 goto fail;
932 }
933 PyTuple_SET_ITEM(t, 1, v);
934 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000935
Christian Heimes824f7f32013-08-17 00:54:47 +0200936 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000937 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200938 switch (gntype) {
939 /* check for new general name type */
940 case GEN_OTHERNAME:
941 case GEN_X400:
942 case GEN_EDIPARTY:
943 case GEN_IPADD:
944 case GEN_RID:
945 break;
946 default:
947 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
948 "Unknown general name type %d",
949 gntype) == -1) {
950 goto fail;
951 }
952 break;
953 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000954 (void) BIO_reset(biobuf);
955 GENERAL_NAME_print(biobuf, name);
956 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
957 if (len < 0) {
958 _setSSLError(NULL, 0, __FILE__, __LINE__);
959 goto fail;
960 }
961 vptr = strchr(buf, ':');
962 if (vptr == NULL)
963 goto fail;
964 t = PyTuple_New(2);
965 if (t == NULL)
966 goto fail;
967 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
968 if (v == NULL) {
969 Py_DECREF(t);
970 goto fail;
971 }
972 PyTuple_SET_ITEM(t, 0, v);
973 v = PyUnicode_FromStringAndSize((vptr + 1),
974 (len - (vptr - buf + 1)));
975 if (v == NULL) {
976 Py_DECREF(t);
977 goto fail;
978 }
979 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200980 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000981 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000982
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000983 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000984
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000985 if (PyList_Append(peer_alt_names, t) < 0) {
986 Py_DECREF(t);
987 goto fail;
988 }
989 Py_DECREF(t);
990 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100991 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000992 }
993 BIO_free(biobuf);
994 if (peer_alt_names != Py_None) {
995 v = PyList_AsTuple(peer_alt_names);
996 Py_DECREF(peer_alt_names);
997 return v;
998 } else {
999 return peer_alt_names;
1000 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001001
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001002
1003 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001004 if (biobuf != NULL)
1005 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001006
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 if (peer_alt_names != Py_None) {
1008 Py_XDECREF(peer_alt_names);
1009 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001010
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001011 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001012}
1013
1014static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001015_get_aia_uri(X509 *certificate, int nid) {
1016 PyObject *lst = NULL, *ostr = NULL;
1017 int i, result;
1018 AUTHORITY_INFO_ACCESS *info;
1019
1020 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
1021 if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
1022 return Py_None;
1023 }
1024
1025 if ((lst = PyList_New(0)) == NULL) {
1026 goto fail;
1027 }
1028
1029 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1030 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1031 ASN1_IA5STRING *uri;
1032
1033 if ((OBJ_obj2nid(ad->method) != nid) ||
1034 (ad->location->type != GEN_URI)) {
1035 continue;
1036 }
1037 uri = ad->location->d.uniformResourceIdentifier;
1038 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1039 uri->length);
1040 if (ostr == NULL) {
1041 goto fail;
1042 }
1043 result = PyList_Append(lst, ostr);
1044 Py_DECREF(ostr);
1045 if (result < 0) {
1046 goto fail;
1047 }
1048 }
1049 AUTHORITY_INFO_ACCESS_free(info);
1050
1051 /* convert to tuple or None */
1052 if (PyList_Size(lst) == 0) {
1053 Py_DECREF(lst);
1054 return Py_None;
1055 } else {
1056 PyObject *tup;
1057 tup = PyList_AsTuple(lst);
1058 Py_DECREF(lst);
1059 return tup;
1060 }
1061
1062 fail:
1063 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001064 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001065 return NULL;
1066}
1067
1068static PyObject *
1069_get_crl_dp(X509 *certificate) {
1070 STACK_OF(DIST_POINT) *dps;
1071 int i, j, result;
1072 PyObject *lst;
1073
Christian Heimes949ec142013-11-21 16:26:51 +01001074#if OPENSSL_VERSION_NUMBER < 0x10001000L
1075 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points,
1076 NULL, NULL);
1077#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001078 /* Calls x509v3_cache_extensions and sets up crldp */
1079 X509_check_ca(certificate);
1080 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001081#endif
1082
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001083 if (dps == NULL) {
1084 return Py_None;
1085 }
1086
1087 if ((lst = PyList_New(0)) == NULL) {
1088 return NULL;
1089 }
1090
1091 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1092 DIST_POINT *dp;
1093 STACK_OF(GENERAL_NAME) *gns;
1094
1095 dp = sk_DIST_POINT_value(dps, i);
1096 gns = dp->distpoint->name.fullname;
1097
1098 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1099 GENERAL_NAME *gn;
1100 ASN1_IA5STRING *uri;
1101 PyObject *ouri;
1102
1103 gn = sk_GENERAL_NAME_value(gns, j);
1104 if (gn->type != GEN_URI) {
1105 continue;
1106 }
1107 uri = gn->d.uniformResourceIdentifier;
1108 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1109 uri->length);
1110 if (ouri == NULL) {
1111 Py_DECREF(lst);
1112 return NULL;
1113 }
1114 result = PyList_Append(lst, ouri);
1115 Py_DECREF(ouri);
1116 if (result < 0) {
1117 Py_DECREF(lst);
1118 return NULL;
1119 }
1120 }
1121 }
1122 /* convert to tuple or None */
1123 if (PyList_Size(lst) == 0) {
1124 Py_DECREF(lst);
1125 return Py_None;
1126 } else {
1127 PyObject *tup;
1128 tup = PyList_AsTuple(lst);
1129 Py_DECREF(lst);
1130 return tup;
1131 }
1132}
1133
1134static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001135_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 PyObject *retval = NULL;
1138 BIO *biobuf = NULL;
1139 PyObject *peer;
1140 PyObject *peer_alt_names = NULL;
1141 PyObject *issuer;
1142 PyObject *version;
1143 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001144 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 ASN1_INTEGER *serialNumber;
1146 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001147 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 ASN1_TIME *notBefore, *notAfter;
1149 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001150
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001151 retval = PyDict_New();
1152 if (retval == NULL)
1153 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001154
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001155 peer = _create_tuple_for_X509_NAME(
1156 X509_get_subject_name(certificate));
1157 if (peer == NULL)
1158 goto fail0;
1159 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1160 Py_DECREF(peer);
1161 goto fail0;
1162 }
1163 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001164
Antoine Pitroufb046912010-11-09 20:21:19 +00001165 issuer = _create_tuple_for_X509_NAME(
1166 X509_get_issuer_name(certificate));
1167 if (issuer == NULL)
1168 goto fail0;
1169 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001170 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001171 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001172 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001173 Py_DECREF(issuer);
1174
1175 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001176 if (version == NULL)
1177 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001178 if (PyDict_SetItemString(retval, "version", version) < 0) {
1179 Py_DECREF(version);
1180 goto fail0;
1181 }
1182 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001183
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001184 /* get a memory buffer */
1185 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001186
Antoine Pitroufb046912010-11-09 20:21:19 +00001187 (void) BIO_reset(biobuf);
1188 serialNumber = X509_get_serialNumber(certificate);
1189 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1190 i2a_ASN1_INTEGER(biobuf, serialNumber);
1191 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1192 if (len < 0) {
1193 _setSSLError(NULL, 0, __FILE__, __LINE__);
1194 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001195 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001196 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1197 if (sn_obj == NULL)
1198 goto fail1;
1199 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1200 Py_DECREF(sn_obj);
1201 goto fail1;
1202 }
1203 Py_DECREF(sn_obj);
1204
1205 (void) BIO_reset(biobuf);
1206 notBefore = X509_get_notBefore(certificate);
1207 ASN1_TIME_print(biobuf, notBefore);
1208 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1209 if (len < 0) {
1210 _setSSLError(NULL, 0, __FILE__, __LINE__);
1211 goto fail1;
1212 }
1213 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1214 if (pnotBefore == NULL)
1215 goto fail1;
1216 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1217 Py_DECREF(pnotBefore);
1218 goto fail1;
1219 }
1220 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001221
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001222 (void) BIO_reset(biobuf);
1223 notAfter = X509_get_notAfter(certificate);
1224 ASN1_TIME_print(biobuf, notAfter);
1225 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1226 if (len < 0) {
1227 _setSSLError(NULL, 0, __FILE__, __LINE__);
1228 goto fail1;
1229 }
1230 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1231 if (pnotAfter == NULL)
1232 goto fail1;
1233 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1234 Py_DECREF(pnotAfter);
1235 goto fail1;
1236 }
1237 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001238
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001239 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001240
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241 peer_alt_names = _get_peer_alt_names(certificate);
1242 if (peer_alt_names == NULL)
1243 goto fail1;
1244 else if (peer_alt_names != Py_None) {
1245 if (PyDict_SetItemString(retval, "subjectAltName",
1246 peer_alt_names) < 0) {
1247 Py_DECREF(peer_alt_names);
1248 goto fail1;
1249 }
1250 Py_DECREF(peer_alt_names);
1251 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001252
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001253 /* Authority Information Access: OCSP URIs */
1254 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1255 if (obj == NULL) {
1256 goto fail1;
1257 } else if (obj != Py_None) {
1258 result = PyDict_SetItemString(retval, "OCSP", obj);
1259 Py_DECREF(obj);
1260 if (result < 0) {
1261 goto fail1;
1262 }
1263 }
1264
1265 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1266 if (obj == NULL) {
1267 goto fail1;
1268 } else if (obj != Py_None) {
1269 result = PyDict_SetItemString(retval, "caIssuers", obj);
1270 Py_DECREF(obj);
1271 if (result < 0) {
1272 goto fail1;
1273 }
1274 }
1275
1276 /* CDP (CRL distribution points) */
1277 obj = _get_crl_dp(certificate);
1278 if (obj == NULL) {
1279 goto fail1;
1280 } else if (obj != Py_None) {
1281 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1282 Py_DECREF(obj);
1283 if (result < 0) {
1284 goto fail1;
1285 }
1286 }
1287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 BIO_free(biobuf);
1289 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001290
1291 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001292 if (biobuf != NULL)
1293 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001294 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 Py_XDECREF(retval);
1296 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001297}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001298
Christian Heimes9a5395a2013-06-17 15:44:12 +02001299static PyObject *
1300_certificate_to_der(X509 *certificate)
1301{
1302 unsigned char *bytes_buf = NULL;
1303 int len;
1304 PyObject *retval;
1305
1306 bytes_buf = NULL;
1307 len = i2d_X509(certificate, &bytes_buf);
1308 if (len < 0) {
1309 _setSSLError(NULL, 0, __FILE__, __LINE__);
1310 return NULL;
1311 }
1312 /* this is actually an immutable bytes sequence */
1313 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1314 OPENSSL_free(bytes_buf);
1315 return retval;
1316}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001317
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001318/*[clinic input]
1319_ssl._test_decode_cert
1320 path: object(converter="PyUnicode_FSConverter")
1321 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001322
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001323[clinic start generated code]*/
1324
1325static PyObject *
1326_ssl__test_decode_cert_impl(PyModuleDef *module, PyObject *path)
1327/*[clinic end generated code: output=679e01db282804e9 input=cdeaaf02d4346628]*/
1328{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 X509 *x=NULL;
1331 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001332
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001333 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1334 PyErr_SetString(PySSLErrorObject,
1335 "Can't malloc memory to read file");
1336 goto fail0;
1337 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001338
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001339 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 PyErr_SetString(PySSLErrorObject,
1341 "Can't open file");
1342 goto fail0;
1343 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001344
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001345 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1346 if (x == NULL) {
1347 PyErr_SetString(PySSLErrorObject,
1348 "Error decoding PEM-encoded file");
1349 goto fail0;
1350 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001351
Antoine Pitroufb046912010-11-09 20:21:19 +00001352 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001353 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001354
1355 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001356 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001357 if (cert != NULL) BIO_free(cert);
1358 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001359}
1360
1361
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001362/*[clinic input]
1363_ssl._SSLSocket.peer_certificate
1364 der as binary_mode: bool = False
1365 /
1366
1367Returns the certificate for the peer.
1368
1369If no certificate was provided, returns None. If a certificate was
1370provided, but not validated, returns an empty dictionary. Otherwise
1371returns a dict containing information about the peer certificate.
1372
1373If the optional argument is True, returns a DER-encoded copy of the
1374peer certificate, or None if no certificate was provided. This will
1375return the certificate even if it wasn't validated.
1376[clinic start generated code]*/
1377
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001378static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001379_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1380/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001381{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001382 int verification;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001383
Antoine Pitrou20b85552013-09-29 19:50:53 +02001384 if (!self->handshake_done) {
1385 PyErr_SetString(PyExc_ValueError,
1386 "handshake not done yet");
1387 return NULL;
1388 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001389 if (!self->peer_cert)
1390 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001391
Antoine Pitrou721738f2012-08-15 23:20:39 +02001392 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001393 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001394 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001395 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001396 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 if ((verification & SSL_VERIFY_PEER) == 0)
1398 return PyDict_New();
1399 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001400 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001401 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001402}
1403
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001404static PyObject *
1405cipher_to_tuple(const SSL_CIPHER *cipher)
1406{
1407 const char *cipher_name, *cipher_protocol;
1408 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001409 if (retval == NULL)
1410 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001411
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001412 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001413 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001414 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001415 PyTuple_SET_ITEM(retval, 0, Py_None);
1416 } else {
1417 v = PyUnicode_FromString(cipher_name);
1418 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001419 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001420 PyTuple_SET_ITEM(retval, 0, v);
1421 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001422
1423 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001424 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001425 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001426 PyTuple_SET_ITEM(retval, 1, Py_None);
1427 } else {
1428 v = PyUnicode_FromString(cipher_protocol);
1429 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001430 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001431 PyTuple_SET_ITEM(retval, 1, v);
1432 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001433
1434 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001435 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001436 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001437 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001438
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001439 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001440
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001441 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001442 Py_DECREF(retval);
1443 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001444}
1445
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001446/*[clinic input]
1447_ssl._SSLSocket.shared_ciphers
1448[clinic start generated code]*/
1449
1450static PyObject *
1451_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1452/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001453{
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001454 SSL_SESSION *sess = SSL_get_session(self->ssl);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001455 STACK_OF(SSL_CIPHER) *ciphers;
1456 int i;
1457 PyObject *res;
1458
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001459 if (!sess || !sess->ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001460 Py_RETURN_NONE;
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001461 ciphers = sess->ciphers;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001462 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1463 if (!res)
1464 return NULL;
1465 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1466 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1467 if (!tup) {
1468 Py_DECREF(res);
1469 return NULL;
1470 }
1471 PyList_SET_ITEM(res, i, tup);
1472 }
1473 return res;
1474}
1475
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001476/*[clinic input]
1477_ssl._SSLSocket.cipher
1478[clinic start generated code]*/
1479
1480static PyObject *
1481_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1482/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001483{
1484 const SSL_CIPHER *current;
1485
1486 if (self->ssl == NULL)
1487 Py_RETURN_NONE;
1488 current = SSL_get_current_cipher(self->ssl);
1489 if (current == NULL)
1490 Py_RETURN_NONE;
1491 return cipher_to_tuple(current);
1492}
1493
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001494/*[clinic input]
1495_ssl._SSLSocket.version
1496[clinic start generated code]*/
1497
1498static PyObject *
1499_ssl__SSLSocket_version_impl(PySSLSocket *self)
1500/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001501{
1502 const char *version;
1503
1504 if (self->ssl == NULL)
1505 Py_RETURN_NONE;
1506 version = SSL_get_version(self->ssl);
1507 if (!strcmp(version, "unknown"))
1508 Py_RETURN_NONE;
1509 return PyUnicode_FromString(version);
1510}
1511
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001512#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001513/*[clinic input]
1514_ssl._SSLSocket.selected_npn_protocol
1515[clinic start generated code]*/
1516
1517static PyObject *
1518_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1519/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1520{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001521 const unsigned char *out;
1522 unsigned int outlen;
1523
Victor Stinner4569cd52013-06-23 14:58:43 +02001524 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001525 &out, &outlen);
1526
1527 if (out == NULL)
1528 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001529 return PyUnicode_FromStringAndSize((char *)out, outlen);
1530}
1531#endif
1532
1533#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001534/*[clinic input]
1535_ssl._SSLSocket.selected_alpn_protocol
1536[clinic start generated code]*/
1537
1538static PyObject *
1539_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1540/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1541{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001542 const unsigned char *out;
1543 unsigned int outlen;
1544
1545 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1546
1547 if (out == NULL)
1548 Py_RETURN_NONE;
1549 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001550}
1551#endif
1552
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001553/*[clinic input]
1554_ssl._SSLSocket.compression
1555[clinic start generated code]*/
1556
1557static PyObject *
1558_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1559/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1560{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001561#ifdef OPENSSL_NO_COMP
1562 Py_RETURN_NONE;
1563#else
1564 const COMP_METHOD *comp_method;
1565 const char *short_name;
1566
1567 if (self->ssl == NULL)
1568 Py_RETURN_NONE;
1569 comp_method = SSL_get_current_compression(self->ssl);
1570 if (comp_method == NULL || comp_method->type == NID_undef)
1571 Py_RETURN_NONE;
1572 short_name = OBJ_nid2sn(comp_method->type);
1573 if (short_name == NULL)
1574 Py_RETURN_NONE;
1575 return PyUnicode_DecodeFSDefault(short_name);
1576#endif
1577}
1578
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001579static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1580 Py_INCREF(self->ctx);
1581 return self->ctx;
1582}
1583
1584static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1585 void *closure) {
1586
1587 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001588#if !HAVE_SNI
1589 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1590 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001591 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001592#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001593 Py_INCREF(value);
1594 Py_DECREF(self->ctx);
1595 self->ctx = (PySSLContext *) value;
1596 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001597#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001598 } else {
1599 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1600 return -1;
1601 }
1602
1603 return 0;
1604}
1605
1606PyDoc_STRVAR(PySSL_set_context_doc,
1607"_setter_context(ctx)\n\
1608\
1609This changes the context associated with the SSLSocket. This is typically\n\
1610used from within a callback function set by the set_servername_callback\n\
1611on the SSLContext to change the certificate information associated with the\n\
1612SSLSocket before the cryptographic exchange handshake messages\n");
1613
1614
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001615static PyObject *
1616PySSL_get_server_side(PySSLSocket *self, void *c)
1617{
1618 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1619}
1620
1621PyDoc_STRVAR(PySSL_get_server_side_doc,
1622"Whether this is a server-side socket.");
1623
1624static PyObject *
1625PySSL_get_server_hostname(PySSLSocket *self, void *c)
1626{
1627 if (self->server_hostname == NULL)
1628 Py_RETURN_NONE;
1629 Py_INCREF(self->server_hostname);
1630 return self->server_hostname;
1631}
1632
1633PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1634"The currently set server hostname (for SNI).");
1635
1636static PyObject *
1637PySSL_get_owner(PySSLSocket *self, void *c)
1638{
1639 PyObject *owner;
1640
1641 if (self->owner == NULL)
1642 Py_RETURN_NONE;
1643
1644 owner = PyWeakref_GetObject(self->owner);
1645 Py_INCREF(owner);
1646 return owner;
1647}
1648
1649static int
1650PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1651{
1652 Py_XDECREF(self->owner);
1653 self->owner = PyWeakref_NewRef(value, NULL);
1654 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 */
1706 if (s->sock_fd < 0)
1707 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
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001902 if (sock != NULL) {
1903 if (((PyObject*)sock) == Py_None) {
1904 _setSSLError("Underlying socket connection gone",
1905 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1906 return NULL;
1907 }
1908 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001909 }
1910
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001911 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001912 dest = PyBytes_FromStringAndSize(NULL, len);
1913 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001914 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001915 mem = PyBytes_AS_STRING(dest);
1916 }
1917 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001918 mem = buffer->buf;
1919 if (len <= 0 || len > buffer->len) {
1920 len = (int) buffer->len;
1921 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001922 PyErr_SetString(PyExc_OverflowError,
1923 "maximum length can't fit in a C 'int'");
1924 goto error;
1925 }
1926 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001927 }
1928
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001929 if (sock != NULL) {
1930 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001931 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001932 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1933 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1934 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001935
Victor Stinner14690702015-04-06 22:46:13 +02001936 timeout = GET_SOCKET_TIMEOUT(sock);
1937 has_timeout = (timeout > 0);
1938 if (has_timeout)
1939 deadline = _PyTime_GetMonotonicClock() + timeout;
1940
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001941 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001942 PySSL_BEGIN_ALLOW_THREADS
1943 count = SSL_read(self->ssl, mem, len);
1944 err = SSL_get_error(self->ssl, count);
1945 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001946
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001947 if (PyErr_CheckSignals())
1948 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001949
Victor Stinner14690702015-04-06 22:46:13 +02001950 if (has_timeout)
1951 timeout = deadline - _PyTime_GetMonotonicClock();
1952
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001953 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001954 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001955 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001956 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001957 } else if (err == SSL_ERROR_ZERO_RETURN &&
1958 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001959 {
1960 count = 0;
1961 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001962 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001963 else
1964 sockstate = SOCKET_OPERATION_OK;
1965
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001966 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001967 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001968 "The read operation timed out");
1969 goto error;
1970 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1971 break;
1972 }
1973 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001974
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001975 if (count <= 0) {
1976 PySSL_SetError(self, count, __FILE__, __LINE__);
1977 goto error;
1978 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001979
1980done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001981 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001982 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001983 _PyBytes_Resize(&dest, count);
1984 return dest;
1985 }
1986 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001987 return PyLong_FromLong(count);
1988 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001989
1990error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001991 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001992 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001993 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001994 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001995}
1996
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001997/*[clinic input]
1998_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001999
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002000Does the SSL shutdown handshake with the remote end.
2001
2002Returns the underlying socket object.
2003[clinic start generated code]*/
2004
2005static PyObject *
2006_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2007/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002008{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002009 int err, ssl_err, sockstate, nonblocking;
2010 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002011 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002012 _PyTime_t timeout, deadline = 0;
2013 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002014
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002015 if (sock != NULL) {
2016 /* Guard against closed socket */
2017 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
2018 _setSSLError("Underlying socket connection gone",
2019 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2020 return NULL;
2021 }
2022 Py_INCREF(sock);
2023
2024 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002025 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002026 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2027 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002028 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002029
Victor Stinner14690702015-04-06 22:46:13 +02002030 timeout = GET_SOCKET_TIMEOUT(sock);
2031 has_timeout = (timeout > 0);
2032 if (has_timeout)
2033 deadline = _PyTime_GetMonotonicClock() + timeout;
2034
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002035 while (1) {
2036 PySSL_BEGIN_ALLOW_THREADS
2037 /* Disable read-ahead so that unwrap can work correctly.
2038 * Otherwise OpenSSL might read in too much data,
2039 * eating clear text data that happens to be
2040 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002041 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002042 * function is used and the shutdown_seen_zero != 0
2043 * condition is met.
2044 */
2045 if (self->shutdown_seen_zero)
2046 SSL_set_read_ahead(self->ssl, 0);
2047 err = SSL_shutdown(self->ssl);
2048 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002049
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002050 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2051 if (err > 0)
2052 break;
2053 if (err == 0) {
2054 /* Don't loop endlessly; instead preserve legacy
2055 behaviour of trying SSL_shutdown() only twice.
2056 This looks necessary for OpenSSL < 0.9.8m */
2057 if (++zeros > 1)
2058 break;
2059 /* Shutdown was sent, now try receiving */
2060 self->shutdown_seen_zero = 1;
2061 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002062 }
2063
Victor Stinner14690702015-04-06 22:46:13 +02002064 if (has_timeout)
2065 timeout = deadline - _PyTime_GetMonotonicClock();
2066
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002067 /* Possibly retry shutdown until timeout or failure */
2068 ssl_err = SSL_get_error(self->ssl, err);
2069 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002070 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002071 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002072 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002073 else
2074 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002076 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2077 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002078 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002079 "The read operation timed out");
2080 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002081 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002082 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002083 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002084 }
2085 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2086 PyErr_SetString(PySSLErrorObject,
2087 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002088 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002089 }
2090 else if (sockstate != SOCKET_OPERATION_OK)
2091 /* Retain the SSL error code */
2092 break;
2093 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002094
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002095 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002096 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002097 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002098 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002099 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002100 /* It's already INCREF'ed */
2101 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002102 else
2103 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002104
2105error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002106 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002107 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002108}
2109
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002110/*[clinic input]
2111_ssl._SSLSocket.tls_unique_cb
2112
2113Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2114
2115If the TLS handshake is not yet complete, None is returned.
2116[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002117
Antoine Pitroud6494802011-07-21 01:11:30 +02002118static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002119_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2120/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002121{
2122 PyObject *retval = NULL;
2123 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002124 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002125
2126 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2127 /* if session is resumed XOR we are the client */
2128 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2129 }
2130 else {
2131 /* if a new session XOR we are the server */
2132 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2133 }
2134
2135 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002136 if (len == 0)
2137 Py_RETURN_NONE;
2138
2139 retval = PyBytes_FromStringAndSize(buf, len);
2140
2141 return retval;
2142}
2143
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002144static PyGetSetDef ssl_getsetlist[] = {
2145 {"context", (getter) PySSL_get_context,
2146 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002147 {"server_side", (getter) PySSL_get_server_side, NULL,
2148 PySSL_get_server_side_doc},
2149 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2150 PySSL_get_server_hostname_doc},
2151 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2152 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002153 {NULL}, /* sentinel */
2154};
2155
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002156static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002157 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2158 _SSL__SSLSOCKET_WRITE_METHODDEF
2159 _SSL__SSLSOCKET_READ_METHODDEF
2160 _SSL__SSLSOCKET_PENDING_METHODDEF
2161 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2162 _SSL__SSLSOCKET_CIPHER_METHODDEF
2163 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2164 _SSL__SSLSOCKET_VERSION_METHODDEF
2165 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2166 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2167 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2168 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2169 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002170 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002171};
2172
Antoine Pitrou152efa22010-05-16 18:19:27 +00002173static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002174 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002175 "_ssl._SSLSocket", /*tp_name*/
2176 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002177 0, /*tp_itemsize*/
2178 /* methods */
2179 (destructor)PySSL_dealloc, /*tp_dealloc*/
2180 0, /*tp_print*/
2181 0, /*tp_getattr*/
2182 0, /*tp_setattr*/
2183 0, /*tp_reserved*/
2184 0, /*tp_repr*/
2185 0, /*tp_as_number*/
2186 0, /*tp_as_sequence*/
2187 0, /*tp_as_mapping*/
2188 0, /*tp_hash*/
2189 0, /*tp_call*/
2190 0, /*tp_str*/
2191 0, /*tp_getattro*/
2192 0, /*tp_setattro*/
2193 0, /*tp_as_buffer*/
2194 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2195 0, /*tp_doc*/
2196 0, /*tp_traverse*/
2197 0, /*tp_clear*/
2198 0, /*tp_richcompare*/
2199 0, /*tp_weaklistoffset*/
2200 0, /*tp_iter*/
2201 0, /*tp_iternext*/
2202 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002203 0, /*tp_members*/
2204 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002205};
2206
Antoine Pitrou152efa22010-05-16 18:19:27 +00002207
2208/*
2209 * _SSLContext objects
2210 */
2211
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002212/*[clinic input]
2213@classmethod
2214_ssl._SSLContext.__new__
2215 protocol as proto_version: int
2216 /
2217[clinic start generated code]*/
2218
Antoine Pitrou152efa22010-05-16 18:19:27 +00002219static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002220_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2221/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002222{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002223 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002224 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002225 SSL_CTX *ctx = NULL;
2226
Antoine Pitrou152efa22010-05-16 18:19:27 +00002227 PySSL_BEGIN_ALLOW_THREADS
2228 if (proto_version == PY_SSL_VERSION_TLS1)
2229 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002230#if HAVE_TLSv1_2
2231 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2232 ctx = SSL_CTX_new(TLSv1_1_method());
2233 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2234 ctx = SSL_CTX_new(TLSv1_2_method());
2235#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002236#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002237 else if (proto_version == PY_SSL_VERSION_SSL3)
2238 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002239#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002240#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002241 else if (proto_version == PY_SSL_VERSION_SSL2)
2242 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002243#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002244 else if (proto_version == PY_SSL_VERSION_SSL23)
2245 ctx = SSL_CTX_new(SSLv23_method());
2246 else
2247 proto_version = -1;
2248 PySSL_END_ALLOW_THREADS
2249
2250 if (proto_version == -1) {
2251 PyErr_SetString(PyExc_ValueError,
2252 "invalid protocol version");
2253 return NULL;
2254 }
2255 if (ctx == NULL) {
2256 PyErr_SetString(PySSLErrorObject,
2257 "failed to allocate SSL context");
2258 return NULL;
2259 }
2260
2261 assert(type != NULL && type->tp_alloc != NULL);
2262 self = (PySSLContext *) type->tp_alloc(type, 0);
2263 if (self == NULL) {
2264 SSL_CTX_free(ctx);
2265 return NULL;
2266 }
2267 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002268#ifdef OPENSSL_NPN_NEGOTIATED
2269 self->npn_protocols = NULL;
2270#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002271#ifdef HAVE_ALPN
2272 self->alpn_protocols = NULL;
2273#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002274#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002275 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002276#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002277 /* Don't check host name by default */
2278 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002279 /* Defaults */
2280 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002281 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2282 if (proto_version != PY_SSL_VERSION_SSL2)
2283 options |= SSL_OP_NO_SSLv2;
2284 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002285
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002286#ifndef OPENSSL_NO_ECDH
2287 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2288 prime256v1 by default. This is Apache mod_ssl's initialization
2289 policy, so we should be safe. */
2290#if defined(SSL_CTX_set_ecdh_auto)
2291 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2292#else
2293 {
2294 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2295 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2296 EC_KEY_free(key);
2297 }
2298#endif
2299#endif
2300
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002301#define SID_CTX "Python"
2302 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2303 sizeof(SID_CTX));
2304#undef SID_CTX
2305
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002306#ifdef X509_V_FLAG_TRUSTED_FIRST
2307 {
2308 /* Improve trust chain building when cross-signed intermediate
2309 certificates are present. See https://bugs.python.org/issue23476. */
2310 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2311 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2312 }
2313#endif
2314
Antoine Pitrou152efa22010-05-16 18:19:27 +00002315 return (PyObject *)self;
2316}
2317
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002318static int
2319context_traverse(PySSLContext *self, visitproc visit, void *arg)
2320{
2321#ifndef OPENSSL_NO_TLSEXT
2322 Py_VISIT(self->set_hostname);
2323#endif
2324 return 0;
2325}
2326
2327static int
2328context_clear(PySSLContext *self)
2329{
2330#ifndef OPENSSL_NO_TLSEXT
2331 Py_CLEAR(self->set_hostname);
2332#endif
2333 return 0;
2334}
2335
Antoine Pitrou152efa22010-05-16 18:19:27 +00002336static void
2337context_dealloc(PySSLContext *self)
2338{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002339 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002340 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002341#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002342 PyMem_FREE(self->npn_protocols);
2343#endif
2344#ifdef HAVE_ALPN
2345 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002346#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002347 Py_TYPE(self)->tp_free(self);
2348}
2349
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002350/*[clinic input]
2351_ssl._SSLContext.set_ciphers
2352 cipherlist: str
2353 /
2354[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002355
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002356static PyObject *
2357_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2358/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2359{
2360 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002361 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002362 /* Clearing the error queue is necessary on some OpenSSL versions,
2363 otherwise the error will be reported again when another SSL call
2364 is done. */
2365 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002366 PyErr_SetString(PySSLErrorObject,
2367 "No cipher can be selected.");
2368 return NULL;
2369 }
2370 Py_RETURN_NONE;
2371}
2372
Benjamin Petersonc54de472015-01-28 12:06:39 -05002373#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002374static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002375do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2376 const unsigned char *server_protocols, unsigned int server_protocols_len,
2377 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002378{
Benjamin Peterson88615022015-01-23 17:30:26 -05002379 int ret;
2380 if (client_protocols == NULL) {
2381 client_protocols = (unsigned char *)"";
2382 client_protocols_len = 0;
2383 }
2384 if (server_protocols == NULL) {
2385 server_protocols = (unsigned char *)"";
2386 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002387 }
2388
Benjamin Peterson88615022015-01-23 17:30:26 -05002389 ret = SSL_select_next_proto(out, outlen,
2390 server_protocols, server_protocols_len,
2391 client_protocols, client_protocols_len);
2392 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2393 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002394
2395 return SSL_TLSEXT_ERR_OK;
2396}
2397
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002398/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2399static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002400_advertiseNPN_cb(SSL *s,
2401 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002402 void *args)
2403{
2404 PySSLContext *ssl_ctx = (PySSLContext *) args;
2405
2406 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002407 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002408 *len = 0;
2409 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002410 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002411 *len = ssl_ctx->npn_protocols_len;
2412 }
2413
2414 return SSL_TLSEXT_ERR_OK;
2415}
2416/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2417static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002418_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002419 unsigned char **out, unsigned char *outlen,
2420 const unsigned char *server, unsigned int server_len,
2421 void *args)
2422{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002423 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002424 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002425 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002426}
2427#endif
2428
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002429/*[clinic input]
2430_ssl._SSLContext._set_npn_protocols
2431 protos: Py_buffer
2432 /
2433[clinic start generated code]*/
2434
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002435static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002436_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2437 Py_buffer *protos)
2438/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002439{
2440#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002441 PyMem_Free(self->npn_protocols);
2442 self->npn_protocols = PyMem_Malloc(protos->len);
2443 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002444 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002445 memcpy(self->npn_protocols, protos->buf, protos->len);
2446 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002447
2448 /* set both server and client callbacks, because the context can
2449 * be used to create both types of sockets */
2450 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2451 _advertiseNPN_cb,
2452 self);
2453 SSL_CTX_set_next_proto_select_cb(self->ctx,
2454 _selectNPN_cb,
2455 self);
2456
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002457 Py_RETURN_NONE;
2458#else
2459 PyErr_SetString(PyExc_NotImplementedError,
2460 "The NPN extension requires OpenSSL 1.0.1 or later.");
2461 return NULL;
2462#endif
2463}
2464
Benjamin Petersoncca27322015-01-23 16:35:37 -05002465#ifdef HAVE_ALPN
2466static int
2467_selectALPN_cb(SSL *s,
2468 const unsigned char **out, unsigned char *outlen,
2469 const unsigned char *client_protocols, unsigned int client_protocols_len,
2470 void *args)
2471{
2472 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002473 return do_protocol_selection(1, (unsigned char **)out, outlen,
2474 ctx->alpn_protocols, ctx->alpn_protocols_len,
2475 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002476}
2477#endif
2478
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002479/*[clinic input]
2480_ssl._SSLContext._set_alpn_protocols
2481 protos: Py_buffer
2482 /
2483[clinic start generated code]*/
2484
Benjamin Petersoncca27322015-01-23 16:35:37 -05002485static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002486_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2487 Py_buffer *protos)
2488/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002489{
2490#ifdef HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002491 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002492 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002493 if (!self->alpn_protocols)
2494 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002495 memcpy(self->alpn_protocols, protos->buf, protos->len);
2496 self->alpn_protocols_len = protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002497
2498 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2499 return PyErr_NoMemory();
2500 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2501
Benjamin Petersoncca27322015-01-23 16:35:37 -05002502 Py_RETURN_NONE;
2503#else
2504 PyErr_SetString(PyExc_NotImplementedError,
2505 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2506 return NULL;
2507#endif
2508}
2509
Antoine Pitrou152efa22010-05-16 18:19:27 +00002510static PyObject *
2511get_verify_mode(PySSLContext *self, void *c)
2512{
2513 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2514 case SSL_VERIFY_NONE:
2515 return PyLong_FromLong(PY_SSL_CERT_NONE);
2516 case SSL_VERIFY_PEER:
2517 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2518 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2519 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2520 }
2521 PyErr_SetString(PySSLErrorObject,
2522 "invalid return value from SSL_CTX_get_verify_mode");
2523 return NULL;
2524}
2525
2526static int
2527set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2528{
2529 int n, mode;
2530 if (!PyArg_Parse(arg, "i", &n))
2531 return -1;
2532 if (n == PY_SSL_CERT_NONE)
2533 mode = SSL_VERIFY_NONE;
2534 else if (n == PY_SSL_CERT_OPTIONAL)
2535 mode = SSL_VERIFY_PEER;
2536 else if (n == PY_SSL_CERT_REQUIRED)
2537 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2538 else {
2539 PyErr_SetString(PyExc_ValueError,
2540 "invalid value for verify_mode");
2541 return -1;
2542 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002543 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2544 PyErr_SetString(PyExc_ValueError,
2545 "Cannot set verify_mode to CERT_NONE when "
2546 "check_hostname is enabled.");
2547 return -1;
2548 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002549 SSL_CTX_set_verify(self->ctx, mode, NULL);
2550 return 0;
2551}
2552
2553static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002554get_verify_flags(PySSLContext *self, void *c)
2555{
2556 X509_STORE *store;
2557 unsigned long flags;
2558
2559 store = SSL_CTX_get_cert_store(self->ctx);
2560 flags = X509_VERIFY_PARAM_get_flags(store->param);
2561 return PyLong_FromUnsignedLong(flags);
2562}
2563
2564static int
2565set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2566{
2567 X509_STORE *store;
2568 unsigned long new_flags, flags, set, clear;
2569
2570 if (!PyArg_Parse(arg, "k", &new_flags))
2571 return -1;
2572 store = SSL_CTX_get_cert_store(self->ctx);
2573 flags = X509_VERIFY_PARAM_get_flags(store->param);
2574 clear = flags & ~new_flags;
2575 set = ~flags & new_flags;
2576 if (clear) {
2577 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2578 _setSSLError(NULL, 0, __FILE__, __LINE__);
2579 return -1;
2580 }
2581 }
2582 if (set) {
2583 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2584 _setSSLError(NULL, 0, __FILE__, __LINE__);
2585 return -1;
2586 }
2587 }
2588 return 0;
2589}
2590
2591static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002592get_options(PySSLContext *self, void *c)
2593{
2594 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2595}
2596
2597static int
2598set_options(PySSLContext *self, PyObject *arg, void *c)
2599{
2600 long new_opts, opts, set, clear;
2601 if (!PyArg_Parse(arg, "l", &new_opts))
2602 return -1;
2603 opts = SSL_CTX_get_options(self->ctx);
2604 clear = opts & ~new_opts;
2605 set = ~opts & new_opts;
2606 if (clear) {
2607#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2608 SSL_CTX_clear_options(self->ctx, clear);
2609#else
2610 PyErr_SetString(PyExc_ValueError,
2611 "can't clear options before OpenSSL 0.9.8m");
2612 return -1;
2613#endif
2614 }
2615 if (set)
2616 SSL_CTX_set_options(self->ctx, set);
2617 return 0;
2618}
2619
Christian Heimes1aa9a752013-12-02 02:41:19 +01002620static PyObject *
2621get_check_hostname(PySSLContext *self, void *c)
2622{
2623 return PyBool_FromLong(self->check_hostname);
2624}
2625
2626static int
2627set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2628{
2629 int check_hostname;
2630 if (!PyArg_Parse(arg, "p", &check_hostname))
2631 return -1;
2632 if (check_hostname &&
2633 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2634 PyErr_SetString(PyExc_ValueError,
2635 "check_hostname needs a SSL context with either "
2636 "CERT_OPTIONAL or CERT_REQUIRED");
2637 return -1;
2638 }
2639 self->check_hostname = check_hostname;
2640 return 0;
2641}
2642
2643
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002644typedef struct {
2645 PyThreadState *thread_state;
2646 PyObject *callable;
2647 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002648 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002649 int error;
2650} _PySSLPasswordInfo;
2651
2652static int
2653_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2654 const char *bad_type_error)
2655{
2656 /* Set the password and size fields of a _PySSLPasswordInfo struct
2657 from a unicode, bytes, or byte array object.
2658 The password field will be dynamically allocated and must be freed
2659 by the caller */
2660 PyObject *password_bytes = NULL;
2661 const char *data = NULL;
2662 Py_ssize_t size;
2663
2664 if (PyUnicode_Check(password)) {
2665 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2666 if (!password_bytes) {
2667 goto error;
2668 }
2669 data = PyBytes_AS_STRING(password_bytes);
2670 size = PyBytes_GET_SIZE(password_bytes);
2671 } else if (PyBytes_Check(password)) {
2672 data = PyBytes_AS_STRING(password);
2673 size = PyBytes_GET_SIZE(password);
2674 } else if (PyByteArray_Check(password)) {
2675 data = PyByteArray_AS_STRING(password);
2676 size = PyByteArray_GET_SIZE(password);
2677 } else {
2678 PyErr_SetString(PyExc_TypeError, bad_type_error);
2679 goto error;
2680 }
2681
Victor Stinner9ee02032013-06-23 15:08:23 +02002682 if (size > (Py_ssize_t)INT_MAX) {
2683 PyErr_Format(PyExc_ValueError,
2684 "password cannot be longer than %d bytes", INT_MAX);
2685 goto error;
2686 }
2687
Victor Stinner11ebff22013-07-07 17:07:52 +02002688 PyMem_Free(pw_info->password);
2689 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002690 if (!pw_info->password) {
2691 PyErr_SetString(PyExc_MemoryError,
2692 "unable to allocate password buffer");
2693 goto error;
2694 }
2695 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002696 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002697
2698 Py_XDECREF(password_bytes);
2699 return 1;
2700
2701error:
2702 Py_XDECREF(password_bytes);
2703 return 0;
2704}
2705
2706static int
2707_password_callback(char *buf, int size, int rwflag, void *userdata)
2708{
2709 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2710 PyObject *fn_ret = NULL;
2711
2712 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2713
2714 if (pw_info->callable) {
2715 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2716 if (!fn_ret) {
2717 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2718 core python API, so we could use it to add a frame here */
2719 goto error;
2720 }
2721
2722 if (!_pwinfo_set(pw_info, fn_ret,
2723 "password callback must return a string")) {
2724 goto error;
2725 }
2726 Py_CLEAR(fn_ret);
2727 }
2728
2729 if (pw_info->size > size) {
2730 PyErr_Format(PyExc_ValueError,
2731 "password cannot be longer than %d bytes", size);
2732 goto error;
2733 }
2734
2735 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2736 memcpy(buf, pw_info->password, pw_info->size);
2737 return pw_info->size;
2738
2739error:
2740 Py_XDECREF(fn_ret);
2741 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2742 pw_info->error = 1;
2743 return -1;
2744}
2745
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002746/*[clinic input]
2747_ssl._SSLContext.load_cert_chain
2748 certfile: object
2749 keyfile: object = NULL
2750 password: object = NULL
2751
2752[clinic start generated code]*/
2753
Antoine Pitroub5218772010-05-21 09:56:06 +00002754static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002755_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
2756 PyObject *keyfile, PyObject *password)
2757/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002758{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002759 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002760 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2761 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2762 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002763 int r;
2764
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002765 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002766 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002767 if (keyfile == Py_None)
2768 keyfile = NULL;
2769 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2770 PyErr_SetString(PyExc_TypeError,
2771 "certfile should be a valid filesystem path");
2772 return NULL;
2773 }
2774 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2775 PyErr_SetString(PyExc_TypeError,
2776 "keyfile should be a valid filesystem path");
2777 goto error;
2778 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002779 if (password && password != Py_None) {
2780 if (PyCallable_Check(password)) {
2781 pw_info.callable = password;
2782 } else if (!_pwinfo_set(&pw_info, password,
2783 "password should be a string or callable")) {
2784 goto error;
2785 }
2786 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2787 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2788 }
2789 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002790 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2791 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002792 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002793 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002794 if (pw_info.error) {
2795 ERR_clear_error();
2796 /* the password callback has already set the error information */
2797 }
2798 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002799 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002800 PyErr_SetFromErrno(PyExc_IOError);
2801 }
2802 else {
2803 _setSSLError(NULL, 0, __FILE__, __LINE__);
2804 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002805 goto error;
2806 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002807 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002808 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002809 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2810 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002811 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2812 Py_CLEAR(keyfile_bytes);
2813 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002814 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002815 if (pw_info.error) {
2816 ERR_clear_error();
2817 /* the password callback has already set the error information */
2818 }
2819 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002820 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002821 PyErr_SetFromErrno(PyExc_IOError);
2822 }
2823 else {
2824 _setSSLError(NULL, 0, __FILE__, __LINE__);
2825 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002826 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002827 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002828 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002829 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002830 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002831 if (r != 1) {
2832 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002833 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002834 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002835 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2836 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002837 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002838 Py_RETURN_NONE;
2839
2840error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002841 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2842 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002843 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002844 Py_XDECREF(keyfile_bytes);
2845 Py_XDECREF(certfile_bytes);
2846 return NULL;
2847}
2848
Christian Heimesefff7062013-11-21 03:35:02 +01002849/* internal helper function, returns -1 on error
2850 */
2851static int
2852_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2853 int filetype)
2854{
2855 BIO *biobuf = NULL;
2856 X509_STORE *store;
2857 int retval = 0, err, loaded = 0;
2858
2859 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2860
2861 if (len <= 0) {
2862 PyErr_SetString(PyExc_ValueError,
2863 "Empty certificate data");
2864 return -1;
2865 } else if (len > INT_MAX) {
2866 PyErr_SetString(PyExc_OverflowError,
2867 "Certificate data is too long.");
2868 return -1;
2869 }
2870
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002871 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002872 if (biobuf == NULL) {
2873 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2874 return -1;
2875 }
2876
2877 store = SSL_CTX_get_cert_store(self->ctx);
2878 assert(store != NULL);
2879
2880 while (1) {
2881 X509 *cert = NULL;
2882 int r;
2883
2884 if (filetype == SSL_FILETYPE_ASN1) {
2885 cert = d2i_X509_bio(biobuf, NULL);
2886 } else {
2887 cert = PEM_read_bio_X509(biobuf, NULL,
2888 self->ctx->default_passwd_callback,
2889 self->ctx->default_passwd_callback_userdata);
2890 }
2891 if (cert == NULL) {
2892 break;
2893 }
2894 r = X509_STORE_add_cert(store, cert);
2895 X509_free(cert);
2896 if (!r) {
2897 err = ERR_peek_last_error();
2898 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2899 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2900 /* cert already in hash table, not an error */
2901 ERR_clear_error();
2902 } else {
2903 break;
2904 }
2905 }
2906 loaded++;
2907 }
2908
2909 err = ERR_peek_last_error();
2910 if ((filetype == SSL_FILETYPE_ASN1) &&
2911 (loaded > 0) &&
2912 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2913 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2914 /* EOF ASN1 file, not an error */
2915 ERR_clear_error();
2916 retval = 0;
2917 } else if ((filetype == SSL_FILETYPE_PEM) &&
2918 (loaded > 0) &&
2919 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2920 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2921 /* EOF PEM file, not an error */
2922 ERR_clear_error();
2923 retval = 0;
2924 } else {
2925 _setSSLError(NULL, 0, __FILE__, __LINE__);
2926 retval = -1;
2927 }
2928
2929 BIO_free(biobuf);
2930 return retval;
2931}
2932
2933
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002934/*[clinic input]
2935_ssl._SSLContext.load_verify_locations
2936 cafile: object = NULL
2937 capath: object = NULL
2938 cadata: object = NULL
2939
2940[clinic start generated code]*/
2941
Antoine Pitrou152efa22010-05-16 18:19:27 +00002942static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002943_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
2944 PyObject *cafile,
2945 PyObject *capath,
2946 PyObject *cadata)
2947/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002948{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002949 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2950 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002951 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002952
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002953 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002954 if (cafile == Py_None)
2955 cafile = NULL;
2956 if (capath == Py_None)
2957 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002958 if (cadata == Py_None)
2959 cadata = NULL;
2960
2961 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002962 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002963 "cafile, capath and cadata cannot be all omitted");
2964 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002965 }
2966 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2967 PyErr_SetString(PyExc_TypeError,
2968 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002969 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002970 }
2971 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002972 PyErr_SetString(PyExc_TypeError,
2973 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002974 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002975 }
Christian Heimesefff7062013-11-21 03:35:02 +01002976
2977 /* validata cadata type and load cadata */
2978 if (cadata) {
2979 Py_buffer buf;
2980 PyObject *cadata_ascii = NULL;
2981
2982 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2983 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2984 PyBuffer_Release(&buf);
2985 PyErr_SetString(PyExc_TypeError,
2986 "cadata should be a contiguous buffer with "
2987 "a single dimension");
2988 goto error;
2989 }
2990 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2991 PyBuffer_Release(&buf);
2992 if (r == -1) {
2993 goto error;
2994 }
2995 } else {
2996 PyErr_Clear();
2997 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2998 if (cadata_ascii == NULL) {
2999 PyErr_SetString(PyExc_TypeError,
3000 "cadata should be a ASCII string or a "
3001 "bytes-like object");
3002 goto error;
3003 }
3004 r = _add_ca_certs(self,
3005 PyBytes_AS_STRING(cadata_ascii),
3006 PyBytes_GET_SIZE(cadata_ascii),
3007 SSL_FILETYPE_PEM);
3008 Py_DECREF(cadata_ascii);
3009 if (r == -1) {
3010 goto error;
3011 }
3012 }
3013 }
3014
3015 /* load cafile or capath */
3016 if (cafile || capath) {
3017 if (cafile)
3018 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3019 if (capath)
3020 capath_buf = PyBytes_AS_STRING(capath_bytes);
3021 PySSL_BEGIN_ALLOW_THREADS
3022 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3023 PySSL_END_ALLOW_THREADS
3024 if (r != 1) {
3025 ok = 0;
3026 if (errno != 0) {
3027 ERR_clear_error();
3028 PyErr_SetFromErrno(PyExc_IOError);
3029 }
3030 else {
3031 _setSSLError(NULL, 0, __FILE__, __LINE__);
3032 }
3033 goto error;
3034 }
3035 }
3036 goto end;
3037
3038 error:
3039 ok = 0;
3040 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003041 Py_XDECREF(cafile_bytes);
3042 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003043 if (ok) {
3044 Py_RETURN_NONE;
3045 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003046 return NULL;
3047 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003048}
3049
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003050/*[clinic input]
3051_ssl._SSLContext.load_dh_params
3052 path as filepath: object
3053 /
3054
3055[clinic start generated code]*/
3056
Antoine Pitrou152efa22010-05-16 18:19:27 +00003057static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003058_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3059/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003060{
3061 FILE *f;
3062 DH *dh;
3063
Victor Stinnerdaf45552013-08-28 00:53:59 +02003064 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003065 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003066 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003067
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003068 errno = 0;
3069 PySSL_BEGIN_ALLOW_THREADS
3070 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003071 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003072 PySSL_END_ALLOW_THREADS
3073 if (dh == NULL) {
3074 if (errno != 0) {
3075 ERR_clear_error();
3076 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3077 }
3078 else {
3079 _setSSLError(NULL, 0, __FILE__, __LINE__);
3080 }
3081 return NULL;
3082 }
3083 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3084 _setSSLError(NULL, 0, __FILE__, __LINE__);
3085 DH_free(dh);
3086 Py_RETURN_NONE;
3087}
3088
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003089/*[clinic input]
3090_ssl._SSLContext._wrap_socket
3091 sock: object(subclass_of="PySocketModule.Sock_Type")
3092 server_side: int
3093 server_hostname as hostname_obj: object = None
3094
3095[clinic start generated code]*/
3096
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003097static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003098_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3099 int server_side, PyObject *hostname_obj)
3100/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003101{
Antoine Pitroud5323212010-10-22 18:19:07 +00003102 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003103 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003104
Antoine Pitroud5323212010-10-22 18:19:07 +00003105 /* server_hostname is either None (or absent), or to be encoded
3106 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003107 if (hostname_obj != Py_None) {
3108 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003109 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003110 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003111
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003112 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3113 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003114 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003115 if (hostname != NULL)
3116 PyMem_Free(hostname);
3117 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003118}
3119
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003120/*[clinic input]
3121_ssl._SSLContext._wrap_bio
3122 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3123 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3124 server_side: int
3125 server_hostname as hostname_obj: object = None
3126
3127[clinic start generated code]*/
3128
Antoine Pitroub0182c82010-10-12 20:09:02 +00003129static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003130_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3131 PySSLMemoryBIO *outgoing, int server_side,
3132 PyObject *hostname_obj)
3133/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003134{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003135 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003136 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003137
3138 /* server_hostname is either None (or absent), or to be encoded
3139 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003140 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003141 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3142 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003143 }
3144
3145 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3146 incoming, outgoing);
3147
3148 PyMem_Free(hostname);
3149 return res;
3150}
3151
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003152/*[clinic input]
3153_ssl._SSLContext.session_stats
3154[clinic start generated code]*/
3155
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003156static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003157_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3158/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003159{
3160 int r;
3161 PyObject *value, *stats = PyDict_New();
3162 if (!stats)
3163 return NULL;
3164
3165#define ADD_STATS(SSL_NAME, KEY_NAME) \
3166 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3167 if (value == NULL) \
3168 goto error; \
3169 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3170 Py_DECREF(value); \
3171 if (r < 0) \
3172 goto error;
3173
3174 ADD_STATS(number, "number");
3175 ADD_STATS(connect, "connect");
3176 ADD_STATS(connect_good, "connect_good");
3177 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3178 ADD_STATS(accept, "accept");
3179 ADD_STATS(accept_good, "accept_good");
3180 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3181 ADD_STATS(accept, "accept");
3182 ADD_STATS(hits, "hits");
3183 ADD_STATS(misses, "misses");
3184 ADD_STATS(timeouts, "timeouts");
3185 ADD_STATS(cache_full, "cache_full");
3186
3187#undef ADD_STATS
3188
3189 return stats;
3190
3191error:
3192 Py_DECREF(stats);
3193 return NULL;
3194}
3195
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003196/*[clinic input]
3197_ssl._SSLContext.set_default_verify_paths
3198[clinic start generated code]*/
3199
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003200static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003201_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3202/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003203{
3204 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3205 _setSSLError(NULL, 0, __FILE__, __LINE__);
3206 return NULL;
3207 }
3208 Py_RETURN_NONE;
3209}
3210
Antoine Pitrou501da612011-12-21 09:27:41 +01003211#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003212/*[clinic input]
3213_ssl._SSLContext.set_ecdh_curve
3214 name: object
3215 /
3216
3217[clinic start generated code]*/
3218
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003219static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003220_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3221/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003222{
3223 PyObject *name_bytes;
3224 int nid;
3225 EC_KEY *key;
3226
3227 if (!PyUnicode_FSConverter(name, &name_bytes))
3228 return NULL;
3229 assert(PyBytes_Check(name_bytes));
3230 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3231 Py_DECREF(name_bytes);
3232 if (nid == 0) {
3233 PyErr_Format(PyExc_ValueError,
3234 "unknown elliptic curve name %R", name);
3235 return NULL;
3236 }
3237 key = EC_KEY_new_by_curve_name(nid);
3238 if (key == NULL) {
3239 _setSSLError(NULL, 0, __FILE__, __LINE__);
3240 return NULL;
3241 }
3242 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3243 EC_KEY_free(key);
3244 Py_RETURN_NONE;
3245}
Antoine Pitrou501da612011-12-21 09:27:41 +01003246#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003247
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003248#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003249static int
3250_servername_callback(SSL *s, int *al, void *args)
3251{
3252 int ret;
3253 PySSLContext *ssl_ctx = (PySSLContext *) args;
3254 PySSLSocket *ssl;
3255 PyObject *servername_o;
3256 PyObject *servername_idna;
3257 PyObject *result;
3258 /* The high-level ssl.SSLSocket object */
3259 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003260 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003261#ifdef WITH_THREAD
3262 PyGILState_STATE gstate = PyGILState_Ensure();
3263#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003264
3265 if (ssl_ctx->set_hostname == NULL) {
3266 /* remove race condition in this the call back while if removing the
3267 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003268#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003269 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003270#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003271 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003272 }
3273
3274 ssl = SSL_get_app_data(s);
3275 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003276
3277 /* The servername callback expects a argument that represents the current
3278 * SSL connection and that has a .context attribute that can be changed to
3279 * identify the requested hostname. Since the official API is the Python
3280 * level API we want to pass the callback a Python level object rather than
3281 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3282 * SSLObject) that will be passed. Otherwise if there's a socket then that
3283 * will be passed. If both do not exist only then the C-level object is
3284 * passed. */
3285 if (ssl->owner)
3286 ssl_socket = PyWeakref_GetObject(ssl->owner);
3287 else if (ssl->Socket)
3288 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3289 else
3290 ssl_socket = (PyObject *) ssl;
3291
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003292 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003293 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003294 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003295
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003296 if (servername == NULL) {
3297 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3298 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003299 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003300 else {
3301 servername_o = PyBytes_FromString(servername);
3302 if (servername_o == NULL) {
3303 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3304 goto error;
3305 }
3306 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3307 if (servername_idna == NULL) {
3308 PyErr_WriteUnraisable(servername_o);
3309 Py_DECREF(servername_o);
3310 goto error;
3311 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003312 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003313 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3314 servername_idna, ssl_ctx, NULL);
3315 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003316 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003317 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003318
3319 if (result == NULL) {
3320 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3321 *al = SSL_AD_HANDSHAKE_FAILURE;
3322 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3323 }
3324 else {
3325 if (result != Py_None) {
3326 *al = (int) PyLong_AsLong(result);
3327 if (PyErr_Occurred()) {
3328 PyErr_WriteUnraisable(result);
3329 *al = SSL_AD_INTERNAL_ERROR;
3330 }
3331 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3332 }
3333 else {
3334 ret = SSL_TLSEXT_ERR_OK;
3335 }
3336 Py_DECREF(result);
3337 }
3338
Stefan Krah20d60802013-01-17 17:07:17 +01003339#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003340 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003341#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003342 return ret;
3343
3344error:
3345 Py_DECREF(ssl_socket);
3346 *al = SSL_AD_INTERNAL_ERROR;
3347 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003348#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003349 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003350#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003351 return ret;
3352}
Antoine Pitroua5963382013-03-30 16:39:00 +01003353#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003354
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003355/*[clinic input]
3356_ssl._SSLContext.set_servername_callback
3357 method as cb: object
3358 /
3359
3360Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3361
3362If the argument is None then the callback is disabled. The method is called
3363with the SSLSocket, the server name as a string, and the SSLContext object.
3364See RFC 6066 for details of the SNI extension.
3365[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003366
3367static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003368_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3369/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003370{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003371#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003372 Py_CLEAR(self->set_hostname);
3373 if (cb == Py_None) {
3374 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3375 }
3376 else {
3377 if (!PyCallable_Check(cb)) {
3378 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3379 PyErr_SetString(PyExc_TypeError,
3380 "not a callable object");
3381 return NULL;
3382 }
3383 Py_INCREF(cb);
3384 self->set_hostname = cb;
3385 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3386 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3387 }
3388 Py_RETURN_NONE;
3389#else
3390 PyErr_SetString(PyExc_NotImplementedError,
3391 "The TLS extension servername callback, "
3392 "SSL_CTX_set_tlsext_servername_callback, "
3393 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003394 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003395#endif
3396}
3397
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003398/*[clinic input]
3399_ssl._SSLContext.cert_store_stats
3400
3401Returns quantities of loaded X.509 certificates.
3402
3403X.509 certificates with a CA extension and certificate revocation lists
3404inside the context's cert store.
3405
3406NOTE: Certificates in a capath directory aren't loaded unless they have
3407been used at least once.
3408[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003409
3410static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003411_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3412/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003413{
3414 X509_STORE *store;
3415 X509_OBJECT *obj;
3416 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3417
3418 store = SSL_CTX_get_cert_store(self->ctx);
3419 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3420 obj = sk_X509_OBJECT_value(store->objs, i);
3421 switch (obj->type) {
3422 case X509_LU_X509:
3423 x509++;
3424 if (X509_check_ca(obj->data.x509)) {
3425 ca++;
3426 }
3427 break;
3428 case X509_LU_CRL:
3429 crl++;
3430 break;
3431 case X509_LU_PKEY:
3432 pkey++;
3433 break;
3434 default:
3435 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3436 * As far as I can tell they are internal states and never
3437 * stored in a cert store */
3438 break;
3439 }
3440 }
3441 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3442 "x509_ca", ca);
3443}
3444
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003445/*[clinic input]
3446_ssl._SSLContext.get_ca_certs
3447 binary_form: bool = False
3448
3449Returns a list of dicts with information of loaded CA certs.
3450
3451If the optional argument is True, returns a DER-encoded copy of the CA
3452certificate.
3453
3454NOTE: Certificates in a capath directory aren't loaded unless they have
3455been used at least once.
3456[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003457
3458static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003459_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3460/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003461{
3462 X509_STORE *store;
3463 PyObject *ci = NULL, *rlist = NULL;
3464 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003465
3466 if ((rlist = PyList_New(0)) == NULL) {
3467 return NULL;
3468 }
3469
3470 store = SSL_CTX_get_cert_store(self->ctx);
3471 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3472 X509_OBJECT *obj;
3473 X509 *cert;
3474
3475 obj = sk_X509_OBJECT_value(store->objs, i);
3476 if (obj->type != X509_LU_X509) {
3477 /* not a x509 cert */
3478 continue;
3479 }
3480 /* CA for any purpose */
3481 cert = obj->data.x509;
3482 if (!X509_check_ca(cert)) {
3483 continue;
3484 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003485 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003486 ci = _certificate_to_der(cert);
3487 } else {
3488 ci = _decode_certificate(cert);
3489 }
3490 if (ci == NULL) {
3491 goto error;
3492 }
3493 if (PyList_Append(rlist, ci) == -1) {
3494 goto error;
3495 }
3496 Py_CLEAR(ci);
3497 }
3498 return rlist;
3499
3500 error:
3501 Py_XDECREF(ci);
3502 Py_XDECREF(rlist);
3503 return NULL;
3504}
3505
3506
Antoine Pitrou152efa22010-05-16 18:19:27 +00003507static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003508 {"check_hostname", (getter) get_check_hostname,
3509 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003510 {"options", (getter) get_options,
3511 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003512 {"verify_flags", (getter) get_verify_flags,
3513 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003514 {"verify_mode", (getter) get_verify_mode,
3515 (setter) set_verify_mode, NULL},
3516 {NULL}, /* sentinel */
3517};
3518
3519static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003520 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
3521 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
3522 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
3523 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
3524 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
3525 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
3526 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
3527 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
3528 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
3529 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
3530 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
3531 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
3532 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
3533 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00003534 {NULL, NULL} /* sentinel */
3535};
3536
3537static PyTypeObject PySSLContext_Type = {
3538 PyVarObject_HEAD_INIT(NULL, 0)
3539 "_ssl._SSLContext", /*tp_name*/
3540 sizeof(PySSLContext), /*tp_basicsize*/
3541 0, /*tp_itemsize*/
3542 (destructor)context_dealloc, /*tp_dealloc*/
3543 0, /*tp_print*/
3544 0, /*tp_getattr*/
3545 0, /*tp_setattr*/
3546 0, /*tp_reserved*/
3547 0, /*tp_repr*/
3548 0, /*tp_as_number*/
3549 0, /*tp_as_sequence*/
3550 0, /*tp_as_mapping*/
3551 0, /*tp_hash*/
3552 0, /*tp_call*/
3553 0, /*tp_str*/
3554 0, /*tp_getattro*/
3555 0, /*tp_setattro*/
3556 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003557 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003558 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003559 (traverseproc) context_traverse, /*tp_traverse*/
3560 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003561 0, /*tp_richcompare*/
3562 0, /*tp_weaklistoffset*/
3563 0, /*tp_iter*/
3564 0, /*tp_iternext*/
3565 context_methods, /*tp_methods*/
3566 0, /*tp_members*/
3567 context_getsetlist, /*tp_getset*/
3568 0, /*tp_base*/
3569 0, /*tp_dict*/
3570 0, /*tp_descr_get*/
3571 0, /*tp_descr_set*/
3572 0, /*tp_dictoffset*/
3573 0, /*tp_init*/
3574 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003575 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003576};
3577
3578
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003579/*
3580 * MemoryBIO objects
3581 */
3582
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003583/*[clinic input]
3584@classmethod
3585_ssl.MemoryBIO.__new__
3586
3587[clinic start generated code]*/
3588
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003589static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003590_ssl_MemoryBIO_impl(PyTypeObject *type)
3591/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003592{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003593 BIO *bio;
3594 PySSLMemoryBIO *self;
3595
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003596 bio = BIO_new(BIO_s_mem());
3597 if (bio == NULL) {
3598 PyErr_SetString(PySSLErrorObject,
3599 "failed to allocate BIO");
3600 return NULL;
3601 }
3602 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3603 * just that no data is currently available. The SSL routines should retry
3604 * the read, which we can achieve by calling BIO_set_retry_read(). */
3605 BIO_set_retry_read(bio);
3606 BIO_set_mem_eof_return(bio, -1);
3607
3608 assert(type != NULL && type->tp_alloc != NULL);
3609 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3610 if (self == NULL) {
3611 BIO_free(bio);
3612 return NULL;
3613 }
3614 self->bio = bio;
3615 self->eof_written = 0;
3616
3617 return (PyObject *) self;
3618}
3619
3620static void
3621memory_bio_dealloc(PySSLMemoryBIO *self)
3622{
3623 BIO_free(self->bio);
3624 Py_TYPE(self)->tp_free(self);
3625}
3626
3627static PyObject *
3628memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3629{
3630 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3631}
3632
3633PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3634"The number of bytes pending in the memory BIO.");
3635
3636static PyObject *
3637memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3638{
3639 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3640 && self->eof_written);
3641}
3642
3643PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3644"Whether the memory BIO is at EOF.");
3645
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003646/*[clinic input]
3647_ssl.MemoryBIO.read
3648 size as len: int = -1
3649 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003650
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003651Read up to size bytes from the memory BIO.
3652
3653If size is not specified, read the entire buffer.
3654If the return value is an empty bytes instance, this means either
3655EOF or that no data is available. Use the "eof" property to
3656distinguish between the two.
3657[clinic start generated code]*/
3658
3659static PyObject *
3660_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
3661/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
3662{
3663 int avail, nbytes;
3664 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003665
3666 avail = BIO_ctrl_pending(self->bio);
3667 if ((len < 0) || (len > avail))
3668 len = avail;
3669
3670 result = PyBytes_FromStringAndSize(NULL, len);
3671 if ((result == NULL) || (len == 0))
3672 return result;
3673
3674 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3675 /* There should never be any short reads but check anyway. */
3676 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3677 Py_DECREF(result);
3678 return NULL;
3679 }
3680
3681 return result;
3682}
3683
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003684/*[clinic input]
3685_ssl.MemoryBIO.write
3686 b: Py_buffer
3687 /
3688
3689Writes the bytes b into the memory BIO.
3690
3691Returns the number of bytes written.
3692[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003693
3694static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003695_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
3696/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003697{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003698 int nbytes;
3699
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003700 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003701 PyErr_Format(PyExc_OverflowError,
3702 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003703 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003704 }
3705
3706 if (self->eof_written) {
3707 PyErr_SetString(PySSLErrorObject,
3708 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003709 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003710 }
3711
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003712 nbytes = BIO_write(self->bio, b->buf, b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003713 if (nbytes < 0) {
3714 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003715 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003716 }
3717
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003718 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003719}
3720
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003721/*[clinic input]
3722_ssl.MemoryBIO.write_eof
3723
3724Write an EOF marker to the memory BIO.
3725
3726When all data has been read, the "eof" property will be True.
3727[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003728
3729static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003730_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
3731/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003732{
3733 self->eof_written = 1;
3734 /* After an EOF is written, a zero return from read() should be a real EOF
3735 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3736 BIO_clear_retry_flags(self->bio);
3737 BIO_set_mem_eof_return(self->bio, 0);
3738
3739 Py_RETURN_NONE;
3740}
3741
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003742static PyGetSetDef memory_bio_getsetlist[] = {
3743 {"pending", (getter) memory_bio_get_pending, NULL,
3744 PySSL_memory_bio_pending_doc},
3745 {"eof", (getter) memory_bio_get_eof, NULL,
3746 PySSL_memory_bio_eof_doc},
3747 {NULL}, /* sentinel */
3748};
3749
3750static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003751 _SSL_MEMORYBIO_READ_METHODDEF
3752 _SSL_MEMORYBIO_WRITE_METHODDEF
3753 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003754 {NULL, NULL} /* sentinel */
3755};
3756
3757static PyTypeObject PySSLMemoryBIO_Type = {
3758 PyVarObject_HEAD_INIT(NULL, 0)
3759 "_ssl.MemoryBIO", /*tp_name*/
3760 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3761 0, /*tp_itemsize*/
3762 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3763 0, /*tp_print*/
3764 0, /*tp_getattr*/
3765 0, /*tp_setattr*/
3766 0, /*tp_reserved*/
3767 0, /*tp_repr*/
3768 0, /*tp_as_number*/
3769 0, /*tp_as_sequence*/
3770 0, /*tp_as_mapping*/
3771 0, /*tp_hash*/
3772 0, /*tp_call*/
3773 0, /*tp_str*/
3774 0, /*tp_getattro*/
3775 0, /*tp_setattro*/
3776 0, /*tp_as_buffer*/
3777 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3778 0, /*tp_doc*/
3779 0, /*tp_traverse*/
3780 0, /*tp_clear*/
3781 0, /*tp_richcompare*/
3782 0, /*tp_weaklistoffset*/
3783 0, /*tp_iter*/
3784 0, /*tp_iternext*/
3785 memory_bio_methods, /*tp_methods*/
3786 0, /*tp_members*/
3787 memory_bio_getsetlist, /*tp_getset*/
3788 0, /*tp_base*/
3789 0, /*tp_dict*/
3790 0, /*tp_descr_get*/
3791 0, /*tp_descr_set*/
3792 0, /*tp_dictoffset*/
3793 0, /*tp_init*/
3794 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003795 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003796};
3797
Antoine Pitrou152efa22010-05-16 18:19:27 +00003798
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003799/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003800/*[clinic input]
3801_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07003802 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003803 entropy: double
3804 /
3805
3806Mix string into the OpenSSL PRNG state.
3807
3808entropy (a float) is a lower bound on the entropy contained in
3809string. See RFC 1750.
3810[clinic start generated code]*/
3811
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003812static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003813_ssl_RAND_add_impl(PyModuleDef *module, Py_buffer *view, double entropy)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07003814/*[clinic end generated code: output=0f8d5c8cce328958 input=580c85e6a3a4fe29]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003815{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02003816 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003817 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003818
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003819 buf = (const char *)view->buf;
3820 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003821 do {
3822 written = Py_MIN(len, INT_MAX);
3823 RAND_add(buf, (int)written, entropy);
3824 buf += written;
3825 len -= written;
3826 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003827 Py_INCREF(Py_None);
3828 return Py_None;
3829}
3830
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003831static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003832PySSL_RAND(int len, int pseudo)
3833{
3834 int ok;
3835 PyObject *bytes;
3836 unsigned long err;
3837 const char *errstr;
3838 PyObject *v;
3839
Victor Stinner1e81a392013-12-19 16:47:04 +01003840 if (len < 0) {
3841 PyErr_SetString(PyExc_ValueError, "num must be positive");
3842 return NULL;
3843 }
3844
Victor Stinner99c8b162011-05-24 12:05:19 +02003845 bytes = PyBytes_FromStringAndSize(NULL, len);
3846 if (bytes == NULL)
3847 return NULL;
3848 if (pseudo) {
3849 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3850 if (ok == 0 || ok == 1)
3851 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3852 }
3853 else {
3854 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3855 if (ok == 1)
3856 return bytes;
3857 }
3858 Py_DECREF(bytes);
3859
3860 err = ERR_get_error();
3861 errstr = ERR_reason_error_string(err);
3862 v = Py_BuildValue("(ks)", err, errstr);
3863 if (v != NULL) {
3864 PyErr_SetObject(PySSLErrorObject, v);
3865 Py_DECREF(v);
3866 }
3867 return NULL;
3868}
3869
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003870/*[clinic input]
3871_ssl.RAND_bytes
3872 n: int
3873 /
3874
3875Generate n cryptographically strong pseudo-random bytes.
3876[clinic start generated code]*/
3877
Victor Stinner99c8b162011-05-24 12:05:19 +02003878static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003879_ssl_RAND_bytes_impl(PyModuleDef *module, int n)
3880/*[clinic end generated code: output=7d8741bdc1d435f3 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003881{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003882 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02003883}
3884
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003885/*[clinic input]
3886_ssl.RAND_pseudo_bytes
3887 n: int
3888 /
3889
3890Generate n pseudo-random bytes.
3891
3892Return a pair (bytes, is_cryptographic). is_cryptographic is True
3893if the bytes generated are cryptographically strong.
3894[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003895
3896static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003897_ssl_RAND_pseudo_bytes_impl(PyModuleDef *module, int n)
3898/*[clinic end generated code: output=dd673813107f3875 input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003899{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003900 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02003901}
3902
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003903/*[clinic input]
3904_ssl.RAND_status
3905
3906Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
3907
3908It is necessary to seed the PRNG with RAND_add() on some platforms before
3909using the ssl() function.
3910[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02003911
3912static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003913_ssl_RAND_status_impl(PyModuleDef *module)
3914/*[clinic end generated code: output=7f7ef57bc7dd1d1c input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003915{
Christian Heimes217cfd12007-12-02 14:31:20 +00003916 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003917}
3918
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003919#ifdef HAVE_RAND_EGD
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003920/*[clinic input]
3921_ssl.RAND_egd
3922 path: object(converter="PyUnicode_FSConverter")
3923 /
3924
3925Queries the entropy gather daemon (EGD) on the socket named by 'path'.
3926
3927Returns number of bytes read. Raises SSLError if connection to EGD
3928fails or if it does not provide enough data to seed PRNG.
3929[clinic start generated code]*/
3930
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003931static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003932_ssl_RAND_egd_impl(PyModuleDef *module, PyObject *path)
3933/*[clinic end generated code: output=8e728e501e28541b input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003934{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003935 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003936 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003937 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003938 PyErr_SetString(PySSLErrorObject,
3939 "EGD connection failed or EGD did not return "
3940 "enough data to seed the PRNG");
3941 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003942 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003943 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003944}
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003945#endif /* HAVE_RAND_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003946
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003947
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003948
3949/*[clinic input]
3950_ssl.get_default_verify_paths
3951
3952Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
3953
3954The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
3955[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02003956
3957static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003958_ssl_get_default_verify_paths_impl(PyModuleDef *module)
3959/*[clinic end generated code: output=5a2820ce7e3304d3 input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02003960{
3961 PyObject *ofile_env = NULL;
3962 PyObject *ofile = NULL;
3963 PyObject *odir_env = NULL;
3964 PyObject *odir = NULL;
3965
Benjamin Petersond113c962015-07-18 10:59:13 -07003966#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02003967 const char *tmp = (info); \
3968 target = NULL; \
3969 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3970 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3971 target = PyBytes_FromString(tmp); } \
3972 if (!target) goto error; \
Benjamin Petersond113c962015-07-18 10:59:13 -07003973 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02003974
Benjamin Petersond113c962015-07-18 10:59:13 -07003975 CONVERT(X509_get_default_cert_file_env(), ofile_env);
3976 CONVERT(X509_get_default_cert_file(), ofile);
3977 CONVERT(X509_get_default_cert_dir_env(), odir_env);
3978 CONVERT(X509_get_default_cert_dir(), odir);
3979#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02003980
Christian Heimes200bb1b2013-06-14 15:14:29 +02003981 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003982
3983 error:
3984 Py_XDECREF(ofile_env);
3985 Py_XDECREF(ofile);
3986 Py_XDECREF(odir_env);
3987 Py_XDECREF(odir);
3988 return NULL;
3989}
3990
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003991static PyObject*
3992asn1obj2py(ASN1_OBJECT *obj)
3993{
3994 int nid;
3995 const char *ln, *sn;
3996 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02003997 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003998
3999 nid = OBJ_obj2nid(obj);
4000 if (nid == NID_undef) {
4001 PyErr_Format(PyExc_ValueError, "Unknown object");
4002 return NULL;
4003 }
4004 sn = OBJ_nid2sn(nid);
4005 ln = OBJ_nid2ln(nid);
4006 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4007 if (buflen < 0) {
4008 _setSSLError(NULL, 0, __FILE__, __LINE__);
4009 return NULL;
4010 }
4011 if (buflen) {
4012 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4013 } else {
4014 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4015 }
4016}
4017
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004018/*[clinic input]
4019_ssl.txt2obj
4020 txt: str
4021 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004022
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004023Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4024
4025By default objects are looked up by OID. With name=True short and
4026long name are also matched.
4027[clinic start generated code]*/
4028
4029static PyObject *
4030_ssl_txt2obj_impl(PyModuleDef *module, const char *txt, int name)
4031/*[clinic end generated code: output=2ae2c30531b8809f input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004032{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004033 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004034 ASN1_OBJECT *obj;
4035
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004036 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4037 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004038 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004039 return NULL;
4040 }
4041 result = asn1obj2py(obj);
4042 ASN1_OBJECT_free(obj);
4043 return result;
4044}
4045
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004046/*[clinic input]
4047_ssl.nid2obj
4048 nid: int
4049 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004050
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004051Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4052[clinic start generated code]*/
4053
4054static PyObject *
4055_ssl_nid2obj_impl(PyModuleDef *module, int nid)
4056/*[clinic end generated code: output=8db1df89e44badb8 input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004057{
4058 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004059 ASN1_OBJECT *obj;
4060
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004061 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004062 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004063 return NULL;
4064 }
4065 obj = OBJ_nid2obj(nid);
4066 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004067 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004068 return NULL;
4069 }
4070 result = asn1obj2py(obj);
4071 ASN1_OBJECT_free(obj);
4072 return result;
4073}
4074
Christian Heimes46bebee2013-06-09 19:03:31 +02004075#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004076
4077static PyObject*
4078certEncodingType(DWORD encodingType)
4079{
4080 static PyObject *x509_asn = NULL;
4081 static PyObject *pkcs_7_asn = NULL;
4082
4083 if (x509_asn == NULL) {
4084 x509_asn = PyUnicode_InternFromString("x509_asn");
4085 if (x509_asn == NULL)
4086 return NULL;
4087 }
4088 if (pkcs_7_asn == NULL) {
4089 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4090 if (pkcs_7_asn == NULL)
4091 return NULL;
4092 }
4093 switch(encodingType) {
4094 case X509_ASN_ENCODING:
4095 Py_INCREF(x509_asn);
4096 return x509_asn;
4097 case PKCS_7_ASN_ENCODING:
4098 Py_INCREF(pkcs_7_asn);
4099 return pkcs_7_asn;
4100 default:
4101 return PyLong_FromLong(encodingType);
4102 }
4103}
4104
4105static PyObject*
4106parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4107{
4108 CERT_ENHKEY_USAGE *usage;
4109 DWORD size, error, i;
4110 PyObject *retval;
4111
4112 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4113 error = GetLastError();
4114 if (error == CRYPT_E_NOT_FOUND) {
4115 Py_RETURN_TRUE;
4116 }
4117 return PyErr_SetFromWindowsErr(error);
4118 }
4119
4120 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4121 if (usage == NULL) {
4122 return PyErr_NoMemory();
4123 }
4124
4125 /* Now get the actual enhanced usage property */
4126 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4127 PyMem_Free(usage);
4128 error = GetLastError();
4129 if (error == CRYPT_E_NOT_FOUND) {
4130 Py_RETURN_TRUE;
4131 }
4132 return PyErr_SetFromWindowsErr(error);
4133 }
4134 retval = PySet_New(NULL);
4135 if (retval == NULL) {
4136 goto error;
4137 }
4138 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4139 if (usage->rgpszUsageIdentifier[i]) {
4140 PyObject *oid;
4141 int err;
4142 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4143 if (oid == NULL) {
4144 Py_CLEAR(retval);
4145 goto error;
4146 }
4147 err = PySet_Add(retval, oid);
4148 Py_DECREF(oid);
4149 if (err == -1) {
4150 Py_CLEAR(retval);
4151 goto error;
4152 }
4153 }
4154 }
4155 error:
4156 PyMem_Free(usage);
4157 return retval;
4158}
4159
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004160/*[clinic input]
4161_ssl.enum_certificates
4162 store_name: str
4163
4164Retrieve certificates from Windows' cert store.
4165
4166store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4167more cert storages, too. The function returns a list of (bytes,
4168encoding_type, trust) tuples. The encoding_type flag can be interpreted
4169with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4170a set of OIDs or the boolean True.
4171[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004172
Christian Heimes46bebee2013-06-09 19:03:31 +02004173static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004174_ssl_enum_certificates_impl(PyModuleDef *module, const char *store_name)
4175/*[clinic end generated code: output=cc4ebc10b8adacfc input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004176{
Christian Heimes46bebee2013-06-09 19:03:31 +02004177 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004178 PCCERT_CONTEXT pCertCtx = NULL;
4179 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004180 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004181
Christian Heimes44109d72013-11-22 01:51:30 +01004182 result = PyList_New(0);
4183 if (result == NULL) {
4184 return NULL;
4185 }
4186 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4187 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004188 Py_DECREF(result);
4189 return PyErr_SetFromWindowsErr(GetLastError());
4190 }
4191
Christian Heimes44109d72013-11-22 01:51:30 +01004192 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4193 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4194 pCertCtx->cbCertEncoded);
4195 if (!cert) {
4196 Py_CLEAR(result);
4197 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004198 }
Christian Heimes44109d72013-11-22 01:51:30 +01004199 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4200 Py_CLEAR(result);
4201 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004202 }
Christian Heimes44109d72013-11-22 01:51:30 +01004203 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4204 if (keyusage == Py_True) {
4205 Py_DECREF(keyusage);
4206 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004207 }
Christian Heimes44109d72013-11-22 01:51:30 +01004208 if (keyusage == NULL) {
4209 Py_CLEAR(result);
4210 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004211 }
Christian Heimes44109d72013-11-22 01:51:30 +01004212 if ((tup = PyTuple_New(3)) == NULL) {
4213 Py_CLEAR(result);
4214 break;
4215 }
4216 PyTuple_SET_ITEM(tup, 0, cert);
4217 cert = NULL;
4218 PyTuple_SET_ITEM(tup, 1, enc);
4219 enc = NULL;
4220 PyTuple_SET_ITEM(tup, 2, keyusage);
4221 keyusage = NULL;
4222 if (PyList_Append(result, tup) < 0) {
4223 Py_CLEAR(result);
4224 break;
4225 }
4226 Py_CLEAR(tup);
4227 }
4228 if (pCertCtx) {
4229 /* loop ended with an error, need to clean up context manually */
4230 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004231 }
4232
4233 /* In error cases cert, enc and tup may not be NULL */
4234 Py_XDECREF(cert);
4235 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004236 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004237 Py_XDECREF(tup);
4238
4239 if (!CertCloseStore(hStore, 0)) {
4240 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004241 Py_XDECREF(result);
4242 return PyErr_SetFromWindowsErr(GetLastError());
4243 }
4244 return result;
4245}
4246
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004247/*[clinic input]
4248_ssl.enum_crls
4249 store_name: str
4250
4251Retrieve CRLs from Windows' cert store.
4252
4253store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4254more cert storages, too. The function returns a list of (bytes,
4255encoding_type) tuples. The encoding_type flag can be interpreted with
4256X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4257[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004258
4259static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004260_ssl_enum_crls_impl(PyModuleDef *module, const char *store_name)
4261/*[clinic end generated code: output=763490a2aa1c50d5 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004262{
Christian Heimes44109d72013-11-22 01:51:30 +01004263 HCERTSTORE hStore = NULL;
4264 PCCRL_CONTEXT pCrlCtx = NULL;
4265 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4266 PyObject *result = NULL;
4267
Christian Heimes44109d72013-11-22 01:51:30 +01004268 result = PyList_New(0);
4269 if (result == NULL) {
4270 return NULL;
4271 }
4272 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4273 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004274 Py_DECREF(result);
4275 return PyErr_SetFromWindowsErr(GetLastError());
4276 }
Christian Heimes44109d72013-11-22 01:51:30 +01004277
4278 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4279 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4280 pCrlCtx->cbCrlEncoded);
4281 if (!crl) {
4282 Py_CLEAR(result);
4283 break;
4284 }
4285 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4286 Py_CLEAR(result);
4287 break;
4288 }
4289 if ((tup = PyTuple_New(2)) == NULL) {
4290 Py_CLEAR(result);
4291 break;
4292 }
4293 PyTuple_SET_ITEM(tup, 0, crl);
4294 crl = NULL;
4295 PyTuple_SET_ITEM(tup, 1, enc);
4296 enc = NULL;
4297
4298 if (PyList_Append(result, tup) < 0) {
4299 Py_CLEAR(result);
4300 break;
4301 }
4302 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004303 }
Christian Heimes44109d72013-11-22 01:51:30 +01004304 if (pCrlCtx) {
4305 /* loop ended with an error, need to clean up context manually */
4306 CertFreeCRLContext(pCrlCtx);
4307 }
4308
4309 /* In error cases cert, enc and tup may not be NULL */
4310 Py_XDECREF(crl);
4311 Py_XDECREF(enc);
4312 Py_XDECREF(tup);
4313
4314 if (!CertCloseStore(hStore, 0)) {
4315 /* This error case might shadow another exception.*/
4316 Py_XDECREF(result);
4317 return PyErr_SetFromWindowsErr(GetLastError());
4318 }
4319 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004320}
Christian Heimes44109d72013-11-22 01:51:30 +01004321
4322#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004323
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004324/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004325static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004326 _SSL__TEST_DECODE_CERT_METHODDEF
4327 _SSL_RAND_ADD_METHODDEF
4328 _SSL_RAND_BYTES_METHODDEF
4329 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4330 _SSL_RAND_EGD_METHODDEF
4331 _SSL_RAND_STATUS_METHODDEF
4332 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
4333 _SSL_ENUM_CERTIFICATES_METHODDEF
4334 _SSL_ENUM_CRLS_METHODDEF
4335 _SSL_TXT2OBJ_METHODDEF
4336 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004337 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004338};
4339
4340
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004341#ifdef WITH_THREAD
4342
4343/* an implementation of OpenSSL threading operations in terms
4344 of the Python C thread library */
4345
4346static PyThread_type_lock *_ssl_locks = NULL;
4347
Christian Heimes4d98ca92013-08-19 17:36:29 +02004348#if OPENSSL_VERSION_NUMBER >= 0x10000000
4349/* use new CRYPTO_THREADID API. */
4350static void
4351_ssl_threadid_callback(CRYPTO_THREADID *id)
4352{
4353 CRYPTO_THREADID_set_numeric(id,
4354 (unsigned long)PyThread_get_thread_ident());
4355}
4356#else
4357/* deprecated CRYPTO_set_id_callback() API. */
4358static unsigned long
4359_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004360 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004361}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004362#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004363
Bill Janssen6e027db2007-11-15 22:23:56 +00004364static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004365 (int mode, int n, const char *file, int line) {
4366 /* this function is needed to perform locking on shared data
4367 structures. (Note that OpenSSL uses a number of global data
4368 structures that will be implicitly shared whenever multiple
4369 threads use OpenSSL.) Multi-threaded applications will
4370 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004371
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004372 locking_function() must be able to handle up to
4373 CRYPTO_num_locks() different mutex locks. It sets the n-th
4374 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004375
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004376 file and line are the file number of the function setting the
4377 lock. They can be useful for debugging.
4378 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004379
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004380 if ((_ssl_locks == NULL) ||
4381 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4382 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004383
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004384 if (mode & CRYPTO_LOCK) {
4385 PyThread_acquire_lock(_ssl_locks[n], 1);
4386 } else {
4387 PyThread_release_lock(_ssl_locks[n]);
4388 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004389}
4390
4391static int _setup_ssl_threads(void) {
4392
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004393 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004394
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004395 if (_ssl_locks == NULL) {
4396 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004397 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4398 if (_ssl_locks == NULL) {
4399 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004400 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004401 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004402 memset(_ssl_locks, 0,
4403 sizeof(PyThread_type_lock) * _ssl_locks_count);
4404 for (i = 0; i < _ssl_locks_count; i++) {
4405 _ssl_locks[i] = PyThread_allocate_lock();
4406 if (_ssl_locks[i] == NULL) {
4407 unsigned int j;
4408 for (j = 0; j < i; j++) {
4409 PyThread_free_lock(_ssl_locks[j]);
4410 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004411 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004412 return 0;
4413 }
4414 }
4415 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004416#if OPENSSL_VERSION_NUMBER >= 0x10000000
4417 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4418#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004419 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004420#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004421 }
4422 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004423}
4424
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004425#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004426
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004427PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004428"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004429for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004430
Martin v. Löwis1a214512008-06-11 05:26:20 +00004431
4432static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004433 PyModuleDef_HEAD_INIT,
4434 "_ssl",
4435 module_doc,
4436 -1,
4437 PySSL_methods,
4438 NULL,
4439 NULL,
4440 NULL,
4441 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004442};
4443
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004444
4445static void
4446parse_openssl_version(unsigned long libver,
4447 unsigned int *major, unsigned int *minor,
4448 unsigned int *fix, unsigned int *patch,
4449 unsigned int *status)
4450{
4451 *status = libver & 0xF;
4452 libver >>= 4;
4453 *patch = libver & 0xFF;
4454 libver >>= 8;
4455 *fix = libver & 0xFF;
4456 libver >>= 8;
4457 *minor = libver & 0xFF;
4458 libver >>= 8;
4459 *major = libver & 0xFF;
4460}
4461
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004462PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004463PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004464{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004465 PyObject *m, *d, *r;
4466 unsigned long libver;
4467 unsigned int major, minor, fix, patch, status;
4468 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004469 struct py_ssl_error_code *errcode;
4470 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004471
Antoine Pitrou152efa22010-05-16 18:19:27 +00004472 if (PyType_Ready(&PySSLContext_Type) < 0)
4473 return NULL;
4474 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004475 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004476 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4477 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004478
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004479 m = PyModule_Create(&_sslmodule);
4480 if (m == NULL)
4481 return NULL;
4482 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004483
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004484 /* Load _socket module and its C API */
4485 socket_api = PySocketModule_ImportModuleAndAPI();
4486 if (!socket_api)
4487 return NULL;
4488 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004489
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004490 /* Init OpenSSL */
4491 SSL_load_error_strings();
4492 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004493#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004494 /* note that this will start threading if not already started */
4495 if (!_setup_ssl_threads()) {
4496 return NULL;
4497 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004498#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004499 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004500
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004501 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004502 sslerror_type_slots[0].pfunc = PyExc_OSError;
4503 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004504 if (PySSLErrorObject == NULL)
4505 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004506
Antoine Pitrou41032a62011-10-27 23:56:55 +02004507 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4508 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4509 PySSLErrorObject, NULL);
4510 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4511 "ssl.SSLWantReadError", SSLWantReadError_doc,
4512 PySSLErrorObject, NULL);
4513 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4514 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4515 PySSLErrorObject, NULL);
4516 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4517 "ssl.SSLSyscallError", SSLSyscallError_doc,
4518 PySSLErrorObject, NULL);
4519 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4520 "ssl.SSLEOFError", SSLEOFError_doc,
4521 PySSLErrorObject, NULL);
4522 if (PySSLZeroReturnErrorObject == NULL
4523 || PySSLWantReadErrorObject == NULL
4524 || PySSLWantWriteErrorObject == NULL
4525 || PySSLSyscallErrorObject == NULL
4526 || PySSLEOFErrorObject == NULL)
4527 return NULL;
4528 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4529 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4530 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4531 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4532 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4533 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004534 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004535 if (PyDict_SetItemString(d, "_SSLContext",
4536 (PyObject *)&PySSLContext_Type) != 0)
4537 return NULL;
4538 if (PyDict_SetItemString(d, "_SSLSocket",
4539 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004540 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004541 if (PyDict_SetItemString(d, "MemoryBIO",
4542 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4543 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004544 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4545 PY_SSL_ERROR_ZERO_RETURN);
4546 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4547 PY_SSL_ERROR_WANT_READ);
4548 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4549 PY_SSL_ERROR_WANT_WRITE);
4550 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4551 PY_SSL_ERROR_WANT_X509_LOOKUP);
4552 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4553 PY_SSL_ERROR_SYSCALL);
4554 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4555 PY_SSL_ERROR_SSL);
4556 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4557 PY_SSL_ERROR_WANT_CONNECT);
4558 /* non ssl.h errorcodes */
4559 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4560 PY_SSL_ERROR_EOF);
4561 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4562 PY_SSL_ERROR_INVALID_ERROR_CODE);
4563 /* cert requirements */
4564 PyModule_AddIntConstant(m, "CERT_NONE",
4565 PY_SSL_CERT_NONE);
4566 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4567 PY_SSL_CERT_OPTIONAL);
4568 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4569 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004570 /* CRL verification for verification_flags */
4571 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4572 0);
4573 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4574 X509_V_FLAG_CRL_CHECK);
4575 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4576 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4577 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4578 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05004579#ifdef X509_V_FLAG_TRUSTED_FIRST
4580 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4581 X509_V_FLAG_TRUSTED_FIRST);
4582#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004583
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004584 /* Alert Descriptions from ssl.h */
4585 /* note RESERVED constants no longer intended for use have been removed */
4586 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4587
4588#define ADD_AD_CONSTANT(s) \
4589 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4590 SSL_AD_##s)
4591
4592 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4593 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4594 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4595 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4596 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4597 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4598 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4599 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4600 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4601 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4602 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4603 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4604 ADD_AD_CONSTANT(UNKNOWN_CA);
4605 ADD_AD_CONSTANT(ACCESS_DENIED);
4606 ADD_AD_CONSTANT(DECODE_ERROR);
4607 ADD_AD_CONSTANT(DECRYPT_ERROR);
4608 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4609 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4610 ADD_AD_CONSTANT(INTERNAL_ERROR);
4611 ADD_AD_CONSTANT(USER_CANCELLED);
4612 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004613 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004614#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4615 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4616#endif
4617#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4618 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4619#endif
4620#ifdef SSL_AD_UNRECOGNIZED_NAME
4621 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4622#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004623#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4624 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4625#endif
4626#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4627 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4628#endif
4629#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4630 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4631#endif
4632
4633#undef ADD_AD_CONSTANT
4634
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004635 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004636#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004637 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4638 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004639#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004640#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004641 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4642 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004643#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004644 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4645 PY_SSL_VERSION_SSL23);
4646 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4647 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004648#if HAVE_TLSv1_2
4649 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4650 PY_SSL_VERSION_TLS1_1);
4651 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4652 PY_SSL_VERSION_TLS1_2);
4653#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004654
Antoine Pitroub5218772010-05-21 09:56:06 +00004655 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004656 PyModule_AddIntConstant(m, "OP_ALL",
4657 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004658 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4659 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4660 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004661#if HAVE_TLSv1_2
4662 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4663 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4664#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004665 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4666 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004667 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004668#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004669 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004670#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004671#ifdef SSL_OP_NO_COMPRESSION
4672 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4673 SSL_OP_NO_COMPRESSION);
4674#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004675
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004676#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004677 r = Py_True;
4678#else
4679 r = Py_False;
4680#endif
4681 Py_INCREF(r);
4682 PyModule_AddObject(m, "HAS_SNI", r);
4683
Antoine Pitroud6494802011-07-21 01:11:30 +02004684 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004685 Py_INCREF(r);
4686 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4687
Antoine Pitrou501da612011-12-21 09:27:41 +01004688#ifdef OPENSSL_NO_ECDH
4689 r = Py_False;
4690#else
4691 r = Py_True;
4692#endif
4693 Py_INCREF(r);
4694 PyModule_AddObject(m, "HAS_ECDH", r);
4695
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004696#ifdef OPENSSL_NPN_NEGOTIATED
4697 r = Py_True;
4698#else
4699 r = Py_False;
4700#endif
4701 Py_INCREF(r);
4702 PyModule_AddObject(m, "HAS_NPN", r);
4703
Benjamin Petersoncca27322015-01-23 16:35:37 -05004704#ifdef HAVE_ALPN
4705 r = Py_True;
4706#else
4707 r = Py_False;
4708#endif
4709 Py_INCREF(r);
4710 PyModule_AddObject(m, "HAS_ALPN", r);
4711
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004712 /* Mappings for error codes */
4713 err_codes_to_names = PyDict_New();
4714 err_names_to_codes = PyDict_New();
4715 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4716 return NULL;
4717 errcode = error_codes;
4718 while (errcode->mnemonic != NULL) {
4719 PyObject *mnemo, *key;
4720 mnemo = PyUnicode_FromString(errcode->mnemonic);
4721 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4722 if (mnemo == NULL || key == NULL)
4723 return NULL;
4724 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4725 return NULL;
4726 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4727 return NULL;
4728 Py_DECREF(key);
4729 Py_DECREF(mnemo);
4730 errcode++;
4731 }
4732 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4733 return NULL;
4734 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4735 return NULL;
4736
4737 lib_codes_to_names = PyDict_New();
4738 if (lib_codes_to_names == NULL)
4739 return NULL;
4740 libcode = library_codes;
4741 while (libcode->library != NULL) {
4742 PyObject *mnemo, *key;
4743 key = PyLong_FromLong(libcode->code);
4744 mnemo = PyUnicode_FromString(libcode->library);
4745 if (key == NULL || mnemo == NULL)
4746 return NULL;
4747 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4748 return NULL;
4749 Py_DECREF(key);
4750 Py_DECREF(mnemo);
4751 libcode++;
4752 }
4753 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4754 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004755
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004756 /* OpenSSL version */
4757 /* SSLeay() gives us the version of the library linked against,
4758 which could be different from the headers version.
4759 */
4760 libver = SSLeay();
4761 r = PyLong_FromUnsignedLong(libver);
4762 if (r == NULL)
4763 return NULL;
4764 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4765 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004766 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004767 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4768 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4769 return NULL;
4770 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4771 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4772 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004773
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004774 libver = OPENSSL_VERSION_NUMBER;
4775 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4776 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4777 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4778 return NULL;
4779
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004780 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004781}