blob: b7b39dd37236c3059ed5320c34f21458c3b2f750 [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
224static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
225static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Victor Stinner14690702015-04-06 22:46:13 +0200226static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000227static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
228static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000229
Antoine Pitrou152efa22010-05-16 18:19:27 +0000230#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
231#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200232#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000233
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000234typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000235 SOCKET_IS_NONBLOCKING,
236 SOCKET_IS_BLOCKING,
237 SOCKET_HAS_TIMED_OUT,
238 SOCKET_HAS_BEEN_CLOSED,
239 SOCKET_TOO_LARGE_FOR_SELECT,
240 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000241} timeout_state;
242
Thomas Woutersed03b412007-08-28 21:37:11 +0000243/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000244#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200245#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000246
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200247/* Get the socket from a PySSLSocket, if it has one */
248#define GET_SOCKET(obj) ((obj)->Socket ? \
249 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200250
Victor Stinner14690702015-04-06 22:46:13 +0200251/* If sock is NULL, use a timeout of 0 second */
252#define GET_SOCKET_TIMEOUT(sock) \
253 ((sock != NULL) ? (sock)->sock_timeout : 0)
254
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200255/*
256 * SSL errors.
257 */
258
259PyDoc_STRVAR(SSLError_doc,
260"An error occurred in the SSL implementation.");
261
262PyDoc_STRVAR(SSLZeroReturnError_doc,
263"SSL/TLS session closed cleanly.");
264
265PyDoc_STRVAR(SSLWantReadError_doc,
266"Non-blocking SSL socket needs to read more data\n"
267"before the requested operation can be completed.");
268
269PyDoc_STRVAR(SSLWantWriteError_doc,
270"Non-blocking SSL socket needs to write more data\n"
271"before the requested operation can be completed.");
272
273PyDoc_STRVAR(SSLSyscallError_doc,
274"System error when attempting SSL operation.");
275
276PyDoc_STRVAR(SSLEOFError_doc,
277"SSL/TLS connection terminated abruptly.");
278
279static PyObject *
280SSLError_str(PyOSErrorObject *self)
281{
282 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
283 Py_INCREF(self->strerror);
284 return self->strerror;
285 }
286 else
287 return PyObject_Str(self->args);
288}
289
290static PyType_Slot sslerror_type_slots[] = {
291 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
292 {Py_tp_doc, SSLError_doc},
293 {Py_tp_str, SSLError_str},
294 {0, 0},
295};
296
297static PyType_Spec sslerror_type_spec = {
298 "ssl.SSLError",
299 sizeof(PyOSErrorObject),
300 0,
301 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
302 sslerror_type_slots
303};
304
305static void
306fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
307 int lineno, unsigned long errcode)
308{
309 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
310 PyObject *init_value, *msg, *key;
311 _Py_IDENTIFIER(reason);
312 _Py_IDENTIFIER(library);
313
314 if (errcode != 0) {
315 int lib, reason;
316
317 lib = ERR_GET_LIB(errcode);
318 reason = ERR_GET_REASON(errcode);
319 key = Py_BuildValue("ii", lib, reason);
320 if (key == NULL)
321 goto fail;
322 reason_obj = PyDict_GetItem(err_codes_to_names, key);
323 Py_DECREF(key);
324 if (reason_obj == NULL) {
325 /* XXX if reason < 100, it might reflect a library number (!!) */
326 PyErr_Clear();
327 }
328 key = PyLong_FromLong(lib);
329 if (key == NULL)
330 goto fail;
331 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
332 Py_DECREF(key);
333 if (lib_obj == NULL) {
334 PyErr_Clear();
335 }
336 if (errstr == NULL)
337 errstr = ERR_reason_error_string(errcode);
338 }
339 if (errstr == NULL)
340 errstr = "unknown error";
341
342 if (reason_obj && lib_obj)
343 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
344 lib_obj, reason_obj, errstr, lineno);
345 else if (lib_obj)
346 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
347 lib_obj, errstr, lineno);
348 else
349 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200350 if (msg == NULL)
351 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100352
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200353 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100354 if (init_value == NULL)
355 goto fail;
356
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200357 err_value = PyObject_CallObject(type, init_value);
358 Py_DECREF(init_value);
359 if (err_value == NULL)
360 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100361
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200362 if (reason_obj == NULL)
363 reason_obj = Py_None;
364 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
365 goto fail;
366 if (lib_obj == NULL)
367 lib_obj = Py_None;
368 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
369 goto fail;
370 PyErr_SetObject(type, err_value);
371fail:
372 Py_XDECREF(err_value);
373}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000374
375static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000376PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000377{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200378 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200379 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000380 int err;
381 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200382 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000383
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000384 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200385 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000386
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000387 if (obj->ssl != NULL) {
388 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000389
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000390 switch (err) {
391 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200392 errstr = "TLS/SSL connection has been closed (EOF)";
393 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000394 p = PY_SSL_ERROR_ZERO_RETURN;
395 break;
396 case SSL_ERROR_WANT_READ:
397 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200398 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000399 p = PY_SSL_ERROR_WANT_READ;
400 break;
401 case SSL_ERROR_WANT_WRITE:
402 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200403 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000404 errstr = "The operation did not complete (write)";
405 break;
406 case SSL_ERROR_WANT_X509_LOOKUP:
407 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000408 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000409 break;
410 case SSL_ERROR_WANT_CONNECT:
411 p = PY_SSL_ERROR_WANT_CONNECT;
412 errstr = "The operation did not complete (connect)";
413 break;
414 case SSL_ERROR_SYSCALL:
415 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000416 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200417 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000418 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000419 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200420 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000421 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200422 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000423 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000424 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000425 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200426 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000427 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200428 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000429 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000430 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200431 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000432 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000433 }
434 } else {
435 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000436 }
437 break;
438 }
439 case SSL_ERROR_SSL:
440 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000441 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200442 if (e == 0)
443 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000444 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000445 break;
446 }
447 default:
448 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
449 errstr = "Invalid error code";
450 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000451 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200452 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000453 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000454 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000455}
456
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000457static PyObject *
458_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
459
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200460 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000461 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200462 else
463 errcode = 0;
464 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000465 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000466 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000467}
468
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200469/*
470 * SSL objects
471 */
472
Antoine Pitrou152efa22010-05-16 18:19:27 +0000473static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100474newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000475 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200476 char *server_hostname,
477 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000478{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000479 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100480 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200481 PyObject *hostname;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200482 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000483
Antoine Pitrou152efa22010-05-16 18:19:27 +0000484 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000485 if (self == NULL)
486 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000487
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000488 self->peer_cert = NULL;
489 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000490 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100491 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200492 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200493 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200494 self->owner = NULL;
495 if (server_hostname != NULL) {
496 hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
497 "idna", "strict");
498 if (hostname == NULL) {
499 Py_DECREF(self);
500 return NULL;
501 }
502 self->server_hostname = hostname;
503 } else
504 self->server_hostname = NULL;
505
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100506 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000507
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000508 /* Make sure the SSL error state is initialized */
509 (void) ERR_get_state();
510 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000511
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000512 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000513 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000514 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200515 SSL_set_app_data(self->ssl, self);
516 if (sock) {
517 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
518 } else {
519 /* BIOs are reference counted and SSL_set_bio borrows our reference.
520 * To prevent a double free in memory_bio_dealloc() we need to take an
521 * extra reference here. */
522 CRYPTO_add(&inbio->bio->references, 1, CRYPTO_LOCK_BIO);
523 CRYPTO_add(&outbio->bio->references, 1, CRYPTO_LOCK_BIO);
524 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
525 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200526 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000527#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200528 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000529#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200530 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000531
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100532#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000533 if (server_hostname != NULL)
534 SSL_set_tlsext_host_name(self->ssl, server_hostname);
535#endif
536
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000537 /* If the socket is in non-blocking mode or timeout mode, set the BIO
538 * to non-blocking mode (blocking is the default)
539 */
Victor Stinnere2452312015-03-28 03:00:46 +0100540 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000541 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
542 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
543 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000544
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000545 PySSL_BEGIN_ALLOW_THREADS
546 if (socket_type == PY_SSL_CLIENT)
547 SSL_set_connect_state(self->ssl);
548 else
549 SSL_set_accept_state(self->ssl);
550 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000551
Antoine Pitroud6494802011-07-21 01:11:30 +0200552 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200553 if (sock != NULL) {
554 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
555 if (self->Socket == NULL) {
556 Py_DECREF(self);
557 Py_XDECREF(self->server_hostname);
558 return NULL;
559 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100560 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000561 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000562}
563
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000564/* SSL object methods */
565
Antoine Pitrou152efa22010-05-16 18:19:27 +0000566static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000567{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000568 int ret;
569 int err;
570 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200571 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200572 _PyTime_t timeout, deadline = 0;
573 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000574
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200575 if (sock) {
576 if (((PyObject*)sock) == Py_None) {
577 _setSSLError("Underlying socket connection gone",
578 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
579 return NULL;
580 }
581 Py_INCREF(sock);
582
583 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100584 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200585 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
586 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000587 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000588
Victor Stinner14690702015-04-06 22:46:13 +0200589 timeout = GET_SOCKET_TIMEOUT(sock);
590 has_timeout = (timeout > 0);
591 if (has_timeout)
592 deadline = _PyTime_GetMonotonicClock() + timeout;
593
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000594 /* Actually negotiate SSL connection */
595 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000596 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000597 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000598 ret = SSL_do_handshake(self->ssl);
599 err = SSL_get_error(self->ssl, ret);
600 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200601
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000602 if (PyErr_CheckSignals())
603 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200604
Victor Stinner14690702015-04-06 22:46:13 +0200605 if (has_timeout)
606 timeout = deadline - _PyTime_GetMonotonicClock();
607
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000608 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200609 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000610 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200611 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000612 } else {
613 sockstate = SOCKET_OPERATION_OK;
614 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200615
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000616 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000617 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000618 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000619 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000620 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
621 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000622 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000623 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000624 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
625 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000626 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000627 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000628 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
629 break;
630 }
631 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200632 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000633 if (ret < 1)
634 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000635
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000636 if (self->peer_cert)
637 X509_free (self->peer_cert);
638 PySSL_BEGIN_ALLOW_THREADS
639 self->peer_cert = SSL_get_peer_certificate(self->ssl);
640 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200641 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000642
643 Py_INCREF(Py_None);
644 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000645
646error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200647 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000648 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000649}
650
Thomas Woutersed03b412007-08-28 21:37:11 +0000651static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000652_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000653
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000654 char namebuf[X509_NAME_MAXLEN];
655 int buflen;
656 PyObject *name_obj;
657 PyObject *value_obj;
658 PyObject *attr;
659 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000660
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000661 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
662 if (buflen < 0) {
663 _setSSLError(NULL, 0, __FILE__, __LINE__);
664 goto fail;
665 }
666 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
667 if (name_obj == NULL)
668 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000669
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000670 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
671 if (buflen < 0) {
672 _setSSLError(NULL, 0, __FILE__, __LINE__);
673 Py_DECREF(name_obj);
674 goto fail;
675 }
676 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000677 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000678 OPENSSL_free(valuebuf);
679 if (value_obj == NULL) {
680 Py_DECREF(name_obj);
681 goto fail;
682 }
683 attr = PyTuple_New(2);
684 if (attr == NULL) {
685 Py_DECREF(name_obj);
686 Py_DECREF(value_obj);
687 goto fail;
688 }
689 PyTuple_SET_ITEM(attr, 0, name_obj);
690 PyTuple_SET_ITEM(attr, 1, value_obj);
691 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000692
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000693 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000694 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000695}
696
697static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000698_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000699{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000700 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
701 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
702 PyObject *rdnt;
703 PyObject *attr = NULL; /* tuple to hold an attribute */
704 int entry_count = X509_NAME_entry_count(xname);
705 X509_NAME_ENTRY *entry;
706 ASN1_OBJECT *name;
707 ASN1_STRING *value;
708 int index_counter;
709 int rdn_level = -1;
710 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000711
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000712 dn = PyList_New(0);
713 if (dn == NULL)
714 return NULL;
715 /* now create another tuple to hold the top-level RDN */
716 rdn = PyList_New(0);
717 if (rdn == NULL)
718 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000719
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000720 for (index_counter = 0;
721 index_counter < entry_count;
722 index_counter++)
723 {
724 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000725
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000726 /* check to see if we've gotten to a new RDN */
727 if (rdn_level >= 0) {
728 if (rdn_level != entry->set) {
729 /* yes, new RDN */
730 /* add old RDN to DN */
731 rdnt = PyList_AsTuple(rdn);
732 Py_DECREF(rdn);
733 if (rdnt == NULL)
734 goto fail0;
735 retcode = PyList_Append(dn, rdnt);
736 Py_DECREF(rdnt);
737 if (retcode < 0)
738 goto fail0;
739 /* create new RDN */
740 rdn = PyList_New(0);
741 if (rdn == NULL)
742 goto fail0;
743 }
744 }
745 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000746
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000747 /* now add this attribute to the current RDN */
748 name = X509_NAME_ENTRY_get_object(entry);
749 value = X509_NAME_ENTRY_get_data(entry);
750 attr = _create_tuple_for_attribute(name, value);
751 /*
752 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
753 entry->set,
754 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
755 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
756 */
757 if (attr == NULL)
758 goto fail1;
759 retcode = PyList_Append(rdn, attr);
760 Py_DECREF(attr);
761 if (retcode < 0)
762 goto fail1;
763 }
764 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100765 if (rdn != NULL) {
766 if (PyList_GET_SIZE(rdn) > 0) {
767 rdnt = PyList_AsTuple(rdn);
768 Py_DECREF(rdn);
769 if (rdnt == NULL)
770 goto fail0;
771 retcode = PyList_Append(dn, rdnt);
772 Py_DECREF(rdnt);
773 if (retcode < 0)
774 goto fail0;
775 }
776 else {
777 Py_DECREF(rdn);
778 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000780
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000781 /* convert list to tuple */
782 rdnt = PyList_AsTuple(dn);
783 Py_DECREF(dn);
784 if (rdnt == NULL)
785 return NULL;
786 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000787
788 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000789 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000790
791 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 Py_XDECREF(dn);
793 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000794}
795
796static PyObject *
797_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000798
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000799 /* this code follows the procedure outlined in
800 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
801 function to extract the STACK_OF(GENERAL_NAME),
802 then iterates through the stack to add the
803 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000804
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000805 int i, j;
806 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200807 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000808 X509_EXTENSION *ext = NULL;
809 GENERAL_NAMES *names = NULL;
810 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000811 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 BIO *biobuf = NULL;
813 char buf[2048];
814 char *vptr;
815 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000816 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000817
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000818 if (certificate == NULL)
819 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000820
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000821 /* get a memory buffer */
822 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000823
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200824 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 while ((i = X509_get_ext_by_NID(
826 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000827
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000828 if (peer_alt_names == Py_None) {
829 peer_alt_names = PyList_New(0);
830 if (peer_alt_names == NULL)
831 goto fail;
832 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000833
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 /* now decode the altName */
835 ext = X509_get_ext(certificate, i);
836 if(!(method = X509V3_EXT_get(ext))) {
837 PyErr_SetString
838 (PySSLErrorObject,
839 ERRSTR("No method for internalizing subjectAltName!"));
840 goto fail;
841 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000842
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000843 p = ext->value->data;
844 if (method->it)
845 names = (GENERAL_NAMES*)
846 (ASN1_item_d2i(NULL,
847 &p,
848 ext->value->length,
849 ASN1_ITEM_ptr(method->it)));
850 else
851 names = (GENERAL_NAMES*)
852 (method->d2i(NULL,
853 &p,
854 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000855
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000856 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000857 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200858 int gntype;
859 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000860
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000861 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200862 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200863 switch (gntype) {
864 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000865 /* we special-case DirName as a tuple of
866 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000867
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000868 t = PyTuple_New(2);
869 if (t == NULL) {
870 goto fail;
871 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000872
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000873 v = PyUnicode_FromString("DirName");
874 if (v == NULL) {
875 Py_DECREF(t);
876 goto fail;
877 }
878 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000879
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000880 v = _create_tuple_for_X509_NAME (name->d.dirn);
881 if (v == NULL) {
882 Py_DECREF(t);
883 goto fail;
884 }
885 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200886 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000887
Christian Heimes824f7f32013-08-17 00:54:47 +0200888 case GEN_EMAIL:
889 case GEN_DNS:
890 case GEN_URI:
891 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
892 correctly, CVE-2013-4238 */
893 t = PyTuple_New(2);
894 if (t == NULL)
895 goto fail;
896 switch (gntype) {
897 case GEN_EMAIL:
898 v = PyUnicode_FromString("email");
899 as = name->d.rfc822Name;
900 break;
901 case GEN_DNS:
902 v = PyUnicode_FromString("DNS");
903 as = name->d.dNSName;
904 break;
905 case GEN_URI:
906 v = PyUnicode_FromString("URI");
907 as = name->d.uniformResourceIdentifier;
908 break;
909 }
910 if (v == NULL) {
911 Py_DECREF(t);
912 goto fail;
913 }
914 PyTuple_SET_ITEM(t, 0, v);
915 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
916 ASN1_STRING_length(as));
917 if (v == NULL) {
918 Py_DECREF(t);
919 goto fail;
920 }
921 PyTuple_SET_ITEM(t, 1, v);
922 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923
Christian Heimes824f7f32013-08-17 00:54:47 +0200924 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000925 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200926 switch (gntype) {
927 /* check for new general name type */
928 case GEN_OTHERNAME:
929 case GEN_X400:
930 case GEN_EDIPARTY:
931 case GEN_IPADD:
932 case GEN_RID:
933 break;
934 default:
935 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
936 "Unknown general name type %d",
937 gntype) == -1) {
938 goto fail;
939 }
940 break;
941 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 (void) BIO_reset(biobuf);
943 GENERAL_NAME_print(biobuf, name);
944 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
945 if (len < 0) {
946 _setSSLError(NULL, 0, __FILE__, __LINE__);
947 goto fail;
948 }
949 vptr = strchr(buf, ':');
950 if (vptr == NULL)
951 goto fail;
952 t = PyTuple_New(2);
953 if (t == NULL)
954 goto fail;
955 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
956 if (v == NULL) {
957 Py_DECREF(t);
958 goto fail;
959 }
960 PyTuple_SET_ITEM(t, 0, v);
961 v = PyUnicode_FromStringAndSize((vptr + 1),
962 (len - (vptr - buf + 1)));
963 if (v == NULL) {
964 Py_DECREF(t);
965 goto fail;
966 }
967 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200968 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000969 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000970
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000971 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000972
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000973 if (PyList_Append(peer_alt_names, t) < 0) {
974 Py_DECREF(t);
975 goto fail;
976 }
977 Py_DECREF(t);
978 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100979 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000980 }
981 BIO_free(biobuf);
982 if (peer_alt_names != Py_None) {
983 v = PyList_AsTuple(peer_alt_names);
984 Py_DECREF(peer_alt_names);
985 return v;
986 } else {
987 return peer_alt_names;
988 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000989
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000990
991 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000992 if (biobuf != NULL)
993 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000994
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000995 if (peer_alt_names != Py_None) {
996 Py_XDECREF(peer_alt_names);
997 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000998
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000999 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001000}
1001
1002static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001003_get_aia_uri(X509 *certificate, int nid) {
1004 PyObject *lst = NULL, *ostr = NULL;
1005 int i, result;
1006 AUTHORITY_INFO_ACCESS *info;
1007
1008 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
1009 if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
1010 return Py_None;
1011 }
1012
1013 if ((lst = PyList_New(0)) == NULL) {
1014 goto fail;
1015 }
1016
1017 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1018 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1019 ASN1_IA5STRING *uri;
1020
1021 if ((OBJ_obj2nid(ad->method) != nid) ||
1022 (ad->location->type != GEN_URI)) {
1023 continue;
1024 }
1025 uri = ad->location->d.uniformResourceIdentifier;
1026 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1027 uri->length);
1028 if (ostr == NULL) {
1029 goto fail;
1030 }
1031 result = PyList_Append(lst, ostr);
1032 Py_DECREF(ostr);
1033 if (result < 0) {
1034 goto fail;
1035 }
1036 }
1037 AUTHORITY_INFO_ACCESS_free(info);
1038
1039 /* convert to tuple or None */
1040 if (PyList_Size(lst) == 0) {
1041 Py_DECREF(lst);
1042 return Py_None;
1043 } else {
1044 PyObject *tup;
1045 tup = PyList_AsTuple(lst);
1046 Py_DECREF(lst);
1047 return tup;
1048 }
1049
1050 fail:
1051 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001052 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001053 return NULL;
1054}
1055
1056static PyObject *
1057_get_crl_dp(X509 *certificate) {
1058 STACK_OF(DIST_POINT) *dps;
1059 int i, j, result;
1060 PyObject *lst;
1061
Christian Heimes949ec142013-11-21 16:26:51 +01001062#if OPENSSL_VERSION_NUMBER < 0x10001000L
1063 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points,
1064 NULL, NULL);
1065#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001066 /* Calls x509v3_cache_extensions and sets up crldp */
1067 X509_check_ca(certificate);
1068 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001069#endif
1070
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001071 if (dps == NULL) {
1072 return Py_None;
1073 }
1074
1075 if ((lst = PyList_New(0)) == NULL) {
1076 return NULL;
1077 }
1078
1079 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1080 DIST_POINT *dp;
1081 STACK_OF(GENERAL_NAME) *gns;
1082
1083 dp = sk_DIST_POINT_value(dps, i);
1084 gns = dp->distpoint->name.fullname;
1085
1086 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1087 GENERAL_NAME *gn;
1088 ASN1_IA5STRING *uri;
1089 PyObject *ouri;
1090
1091 gn = sk_GENERAL_NAME_value(gns, j);
1092 if (gn->type != GEN_URI) {
1093 continue;
1094 }
1095 uri = gn->d.uniformResourceIdentifier;
1096 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1097 uri->length);
1098 if (ouri == NULL) {
1099 Py_DECREF(lst);
1100 return NULL;
1101 }
1102 result = PyList_Append(lst, ouri);
1103 Py_DECREF(ouri);
1104 if (result < 0) {
1105 Py_DECREF(lst);
1106 return NULL;
1107 }
1108 }
1109 }
1110 /* convert to tuple or None */
1111 if (PyList_Size(lst) == 0) {
1112 Py_DECREF(lst);
1113 return Py_None;
1114 } else {
1115 PyObject *tup;
1116 tup = PyList_AsTuple(lst);
1117 Py_DECREF(lst);
1118 return tup;
1119 }
1120}
1121
1122static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001123_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001124
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001125 PyObject *retval = NULL;
1126 BIO *biobuf = NULL;
1127 PyObject *peer;
1128 PyObject *peer_alt_names = NULL;
1129 PyObject *issuer;
1130 PyObject *version;
1131 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001132 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001133 ASN1_INTEGER *serialNumber;
1134 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001135 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001136 ASN1_TIME *notBefore, *notAfter;
1137 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001138
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001139 retval = PyDict_New();
1140 if (retval == NULL)
1141 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001142
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001143 peer = _create_tuple_for_X509_NAME(
1144 X509_get_subject_name(certificate));
1145 if (peer == NULL)
1146 goto fail0;
1147 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1148 Py_DECREF(peer);
1149 goto fail0;
1150 }
1151 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001152
Antoine Pitroufb046912010-11-09 20:21:19 +00001153 issuer = _create_tuple_for_X509_NAME(
1154 X509_get_issuer_name(certificate));
1155 if (issuer == NULL)
1156 goto fail0;
1157 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001158 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001159 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001160 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001161 Py_DECREF(issuer);
1162
1163 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001164 if (version == NULL)
1165 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001166 if (PyDict_SetItemString(retval, "version", version) < 0) {
1167 Py_DECREF(version);
1168 goto fail0;
1169 }
1170 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001171
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001172 /* get a memory buffer */
1173 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001174
Antoine Pitroufb046912010-11-09 20:21:19 +00001175 (void) BIO_reset(biobuf);
1176 serialNumber = X509_get_serialNumber(certificate);
1177 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1178 i2a_ASN1_INTEGER(biobuf, serialNumber);
1179 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1180 if (len < 0) {
1181 _setSSLError(NULL, 0, __FILE__, __LINE__);
1182 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001183 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001184 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1185 if (sn_obj == NULL)
1186 goto fail1;
1187 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1188 Py_DECREF(sn_obj);
1189 goto fail1;
1190 }
1191 Py_DECREF(sn_obj);
1192
1193 (void) BIO_reset(biobuf);
1194 notBefore = X509_get_notBefore(certificate);
1195 ASN1_TIME_print(biobuf, notBefore);
1196 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1197 if (len < 0) {
1198 _setSSLError(NULL, 0, __FILE__, __LINE__);
1199 goto fail1;
1200 }
1201 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1202 if (pnotBefore == NULL)
1203 goto fail1;
1204 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1205 Py_DECREF(pnotBefore);
1206 goto fail1;
1207 }
1208 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001209
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001210 (void) BIO_reset(biobuf);
1211 notAfter = X509_get_notAfter(certificate);
1212 ASN1_TIME_print(biobuf, notAfter);
1213 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1214 if (len < 0) {
1215 _setSSLError(NULL, 0, __FILE__, __LINE__);
1216 goto fail1;
1217 }
1218 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1219 if (pnotAfter == NULL)
1220 goto fail1;
1221 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1222 Py_DECREF(pnotAfter);
1223 goto fail1;
1224 }
1225 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001226
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001227 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001228
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001229 peer_alt_names = _get_peer_alt_names(certificate);
1230 if (peer_alt_names == NULL)
1231 goto fail1;
1232 else if (peer_alt_names != Py_None) {
1233 if (PyDict_SetItemString(retval, "subjectAltName",
1234 peer_alt_names) < 0) {
1235 Py_DECREF(peer_alt_names);
1236 goto fail1;
1237 }
1238 Py_DECREF(peer_alt_names);
1239 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001240
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001241 /* Authority Information Access: OCSP URIs */
1242 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1243 if (obj == NULL) {
1244 goto fail1;
1245 } else if (obj != Py_None) {
1246 result = PyDict_SetItemString(retval, "OCSP", obj);
1247 Py_DECREF(obj);
1248 if (result < 0) {
1249 goto fail1;
1250 }
1251 }
1252
1253 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1254 if (obj == NULL) {
1255 goto fail1;
1256 } else if (obj != Py_None) {
1257 result = PyDict_SetItemString(retval, "caIssuers", obj);
1258 Py_DECREF(obj);
1259 if (result < 0) {
1260 goto fail1;
1261 }
1262 }
1263
1264 /* CDP (CRL distribution points) */
1265 obj = _get_crl_dp(certificate);
1266 if (obj == NULL) {
1267 goto fail1;
1268 } else if (obj != Py_None) {
1269 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1270 Py_DECREF(obj);
1271 if (result < 0) {
1272 goto fail1;
1273 }
1274 }
1275
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 BIO_free(biobuf);
1277 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001278
1279 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 if (biobuf != NULL)
1281 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001282 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001283 Py_XDECREF(retval);
1284 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001285}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001286
Christian Heimes9a5395a2013-06-17 15:44:12 +02001287static PyObject *
1288_certificate_to_der(X509 *certificate)
1289{
1290 unsigned char *bytes_buf = NULL;
1291 int len;
1292 PyObject *retval;
1293
1294 bytes_buf = NULL;
1295 len = i2d_X509(certificate, &bytes_buf);
1296 if (len < 0) {
1297 _setSSLError(NULL, 0, __FILE__, __LINE__);
1298 return NULL;
1299 }
1300 /* this is actually an immutable bytes sequence */
1301 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1302 OPENSSL_free(bytes_buf);
1303 return retval;
1304}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001305
1306static PyObject *
1307PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1308
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001309 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001310 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001311 X509 *x=NULL;
1312 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001313
Antoine Pitroufb046912010-11-09 20:21:19 +00001314 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1315 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001316 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001317
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001318 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1319 PyErr_SetString(PySSLErrorObject,
1320 "Can't malloc memory to read file");
1321 goto fail0;
1322 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001323
Victor Stinner3800e1e2010-05-16 21:23:48 +00001324 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001325 PyErr_SetString(PySSLErrorObject,
1326 "Can't open file");
1327 goto fail0;
1328 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001329
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1331 if (x == NULL) {
1332 PyErr_SetString(PySSLErrorObject,
1333 "Error decoding PEM-encoded file");
1334 goto fail0;
1335 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001336
Antoine Pitroufb046912010-11-09 20:21:19 +00001337 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001338 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001339
1340 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001341 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001342 if (cert != NULL) BIO_free(cert);
1343 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001344}
1345
1346
1347static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001348PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001349{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001350 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001351 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001352
Antoine Pitrou721738f2012-08-15 23:20:39 +02001353 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001354 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001355
Antoine Pitrou20b85552013-09-29 19:50:53 +02001356 if (!self->handshake_done) {
1357 PyErr_SetString(PyExc_ValueError,
1358 "handshake not done yet");
1359 return NULL;
1360 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 if (!self->peer_cert)
1362 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001363
Antoine Pitrou721738f2012-08-15 23:20:39 +02001364 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001365 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001366 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001367 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001368 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001369 if ((verification & SSL_VERIFY_PEER) == 0)
1370 return PyDict_New();
1371 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001372 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001373 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001374}
1375
1376PyDoc_STRVAR(PySSL_peercert_doc,
1377"peer_certificate([der=False]) -> certificate\n\
1378\n\
1379Returns the certificate for the peer. If no certificate was provided,\n\
1380returns None. If a certificate was provided, but not validated, returns\n\
1381an empty dictionary. Otherwise returns a dict containing information\n\
1382about the peer certificate.\n\
1383\n\
1384If the optional argument is True, returns a DER-encoded copy of the\n\
1385peer certificate, or None if no certificate was provided. This will\n\
1386return the certificate even if it wasn't validated.");
1387
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001388static PyObject *
1389cipher_to_tuple(const SSL_CIPHER *cipher)
1390{
1391 const char *cipher_name, *cipher_protocol;
1392 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001393 if (retval == NULL)
1394 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001395
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001396 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001398 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001399 PyTuple_SET_ITEM(retval, 0, Py_None);
1400 } else {
1401 v = PyUnicode_FromString(cipher_name);
1402 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001403 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001404 PyTuple_SET_ITEM(retval, 0, v);
1405 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001406
1407 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001408 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001409 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001410 PyTuple_SET_ITEM(retval, 1, Py_None);
1411 } else {
1412 v = PyUnicode_FromString(cipher_protocol);
1413 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001414 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001415 PyTuple_SET_ITEM(retval, 1, v);
1416 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001417
1418 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001419 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001420 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001421 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001422
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001423 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001424
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001425 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001426 Py_DECREF(retval);
1427 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001428}
1429
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001430static PyObject *PySSL_shared_ciphers(PySSLSocket *self)
1431{
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001432 SSL_SESSION *sess = SSL_get_session(self->ssl);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001433 STACK_OF(SSL_CIPHER) *ciphers;
1434 int i;
1435 PyObject *res;
1436
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001437 if (!sess || !sess->ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001438 Py_RETURN_NONE;
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001439 ciphers = sess->ciphers;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001440 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1441 if (!res)
1442 return NULL;
1443 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1444 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1445 if (!tup) {
1446 Py_DECREF(res);
1447 return NULL;
1448 }
1449 PyList_SET_ITEM(res, i, tup);
1450 }
1451 return res;
1452}
1453
1454static PyObject *PySSL_cipher (PySSLSocket *self)
1455{
1456 const SSL_CIPHER *current;
1457
1458 if (self->ssl == NULL)
1459 Py_RETURN_NONE;
1460 current = SSL_get_current_cipher(self->ssl);
1461 if (current == NULL)
1462 Py_RETURN_NONE;
1463 return cipher_to_tuple(current);
1464}
1465
Antoine Pitrou47e40422014-09-04 21:00:10 +02001466static PyObject *PySSL_version(PySSLSocket *self)
1467{
1468 const char *version;
1469
1470 if (self->ssl == NULL)
1471 Py_RETURN_NONE;
1472 version = SSL_get_version(self->ssl);
1473 if (!strcmp(version, "unknown"))
1474 Py_RETURN_NONE;
1475 return PyUnicode_FromString(version);
1476}
1477
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001478#ifdef OPENSSL_NPN_NEGOTIATED
1479static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1480 const unsigned char *out;
1481 unsigned int outlen;
1482
Victor Stinner4569cd52013-06-23 14:58:43 +02001483 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001484 &out, &outlen);
1485
1486 if (out == NULL)
1487 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001488 return PyUnicode_FromStringAndSize((char *)out, outlen);
1489}
1490#endif
1491
1492#ifdef HAVE_ALPN
1493static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1494 const unsigned char *out;
1495 unsigned int outlen;
1496
1497 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1498
1499 if (out == NULL)
1500 Py_RETURN_NONE;
1501 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001502}
1503#endif
1504
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001505static PyObject *PySSL_compression(PySSLSocket *self) {
1506#ifdef OPENSSL_NO_COMP
1507 Py_RETURN_NONE;
1508#else
1509 const COMP_METHOD *comp_method;
1510 const char *short_name;
1511
1512 if (self->ssl == NULL)
1513 Py_RETURN_NONE;
1514 comp_method = SSL_get_current_compression(self->ssl);
1515 if (comp_method == NULL || comp_method->type == NID_undef)
1516 Py_RETURN_NONE;
1517 short_name = OBJ_nid2sn(comp_method->type);
1518 if (short_name == NULL)
1519 Py_RETURN_NONE;
1520 return PyUnicode_DecodeFSDefault(short_name);
1521#endif
1522}
1523
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001524static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1525 Py_INCREF(self->ctx);
1526 return self->ctx;
1527}
1528
1529static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1530 void *closure) {
1531
1532 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001533#if !HAVE_SNI
1534 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1535 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001536 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001537#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001538 Py_INCREF(value);
1539 Py_DECREF(self->ctx);
1540 self->ctx = (PySSLContext *) value;
1541 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001542#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001543 } else {
1544 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1545 return -1;
1546 }
1547
1548 return 0;
1549}
1550
1551PyDoc_STRVAR(PySSL_set_context_doc,
1552"_setter_context(ctx)\n\
1553\
1554This changes the context associated with the SSLSocket. This is typically\n\
1555used from within a callback function set by the set_servername_callback\n\
1556on the SSLContext to change the certificate information associated with the\n\
1557SSLSocket before the cryptographic exchange handshake messages\n");
1558
1559
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001560static PyObject *
1561PySSL_get_server_side(PySSLSocket *self, void *c)
1562{
1563 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1564}
1565
1566PyDoc_STRVAR(PySSL_get_server_side_doc,
1567"Whether this is a server-side socket.");
1568
1569static PyObject *
1570PySSL_get_server_hostname(PySSLSocket *self, void *c)
1571{
1572 if (self->server_hostname == NULL)
1573 Py_RETURN_NONE;
1574 Py_INCREF(self->server_hostname);
1575 return self->server_hostname;
1576}
1577
1578PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1579"The currently set server hostname (for SNI).");
1580
1581static PyObject *
1582PySSL_get_owner(PySSLSocket *self, void *c)
1583{
1584 PyObject *owner;
1585
1586 if (self->owner == NULL)
1587 Py_RETURN_NONE;
1588
1589 owner = PyWeakref_GetObject(self->owner);
1590 Py_INCREF(owner);
1591 return owner;
1592}
1593
1594static int
1595PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1596{
1597 Py_XDECREF(self->owner);
1598 self->owner = PyWeakref_NewRef(value, NULL);
1599 if (self->owner == NULL)
1600 return -1;
1601 return 0;
1602}
1603
1604PyDoc_STRVAR(PySSL_get_owner_doc,
1605"The Python-level owner of this object.\
1606Passed as \"self\" in servername callback.");
1607
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001608
Antoine Pitrou152efa22010-05-16 18:19:27 +00001609static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001610{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001611 if (self->peer_cert) /* Possible not to have one? */
1612 X509_free (self->peer_cert);
1613 if (self->ssl)
1614 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001615 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001616 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001617 Py_XDECREF(self->server_hostname);
1618 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001619 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001620}
1621
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001622/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001623 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001624 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001625 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001626
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001627static int
Victor Stinner14690702015-04-06 22:46:13 +02001628PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001629{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001630 int rc;
1631#ifdef HAVE_POLL
1632 struct pollfd pollfd;
1633 _PyTime_t ms;
1634#else
1635 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001636 fd_set fds;
1637 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001638#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001639
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001640 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001641 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001642 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001643 else if (timeout < 0) {
1644 if (s->sock_timeout > 0)
1645 return SOCKET_HAS_TIMED_OUT;
1646 else
1647 return SOCKET_IS_BLOCKING;
1648 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001649
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001650 /* Guard against closed socket */
1651 if (s->sock_fd < 0)
1652 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001653
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001654 /* Prefer poll, if available, since you can poll() any fd
1655 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001656#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001657 pollfd.fd = s->sock_fd;
1658 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001659
Victor Stinner14690702015-04-06 22:46:13 +02001660 /* timeout is in seconds, poll() uses milliseconds */
1661 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001662 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001663
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001664 PySSL_BEGIN_ALLOW_THREADS
1665 rc = poll(&pollfd, 1, (int)ms);
1666 PySSL_END_ALLOW_THREADS
1667#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001668 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001669 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001670 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001671
Victor Stinner14690702015-04-06 22:46:13 +02001672 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001673
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001674 FD_ZERO(&fds);
1675 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001676
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001677 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001678 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001679 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001680 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001681 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001682 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001683 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001684 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001685#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001686
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001687 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1688 (when we are able to write or when there's something to read) */
1689 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001690}
1691
Antoine Pitrou152efa22010-05-16 18:19:27 +00001692static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001693{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001694 Py_buffer buf;
1695 int len;
1696 int sockstate;
1697 int err;
1698 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001699 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001700 _PyTime_t timeout, deadline = 0;
1701 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001702
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001703 if (sock != NULL) {
1704 if (((PyObject*)sock) == Py_None) {
1705 _setSSLError("Underlying socket connection gone",
1706 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1707 return NULL;
1708 }
1709 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001710 }
1711
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001712 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001713 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001714 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001715 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001716
Victor Stinner6efa9652013-06-25 00:42:31 +02001717 if (buf.len > INT_MAX) {
1718 PyErr_Format(PyExc_OverflowError,
1719 "string longer than %d bytes", INT_MAX);
1720 goto error;
1721 }
1722
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001723 if (sock != NULL) {
1724 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001725 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001726 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1727 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1728 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001729
Victor Stinner14690702015-04-06 22:46:13 +02001730 timeout = GET_SOCKET_TIMEOUT(sock);
1731 has_timeout = (timeout > 0);
1732 if (has_timeout)
1733 deadline = _PyTime_GetMonotonicClock() + timeout;
1734
1735 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001736 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001737 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001738 "The write operation timed out");
1739 goto error;
1740 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1741 PyErr_SetString(PySSLErrorObject,
1742 "Underlying socket has been closed.");
1743 goto error;
1744 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1745 PyErr_SetString(PySSLErrorObject,
1746 "Underlying socket too large for select().");
1747 goto error;
1748 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001749
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001750 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001751 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001752 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001753 err = SSL_get_error(self->ssl, len);
1754 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001755
1756 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001757 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001758
Victor Stinner14690702015-04-06 22:46:13 +02001759 if (has_timeout)
1760 timeout = deadline - _PyTime_GetMonotonicClock();
1761
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001762 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001763 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001764 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001765 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001766 } else {
1767 sockstate = SOCKET_OPERATION_OK;
1768 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001769
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001770 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001771 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001772 "The write operation timed out");
1773 goto error;
1774 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1775 PyErr_SetString(PySSLErrorObject,
1776 "Underlying socket has been closed.");
1777 goto error;
1778 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1779 break;
1780 }
1781 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001782
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001783 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001784 PyBuffer_Release(&buf);
1785 if (len > 0)
1786 return PyLong_FromLong(len);
1787 else
1788 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001789
1790error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001791 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001792 PyBuffer_Release(&buf);
1793 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001794}
1795
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001796PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001797"write(s) -> len\n\
1798\n\
1799Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001800of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001801
Antoine Pitrou152efa22010-05-16 18:19:27 +00001802static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001803{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001804 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001805
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001806 PySSL_BEGIN_ALLOW_THREADS
1807 count = SSL_pending(self->ssl);
1808 PySSL_END_ALLOW_THREADS
1809 if (count < 0)
1810 return PySSL_SetError(self, count, __FILE__, __LINE__);
1811 else
1812 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001813}
1814
1815PyDoc_STRVAR(PySSL_SSLpending_doc,
1816"pending() -> count\n\
1817\n\
1818Returns the number of already decrypted bytes available for read,\n\
1819pending on the connection.\n");
1820
Antoine Pitrou152efa22010-05-16 18:19:27 +00001821static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001822{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 PyObject *dest = NULL;
1824 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001826 int len, count;
1827 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001828 int sockstate;
1829 int err;
1830 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001831 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001832 _PyTime_t timeout, deadline = 0;
1833 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001834
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001835 if (sock != NULL) {
1836 if (((PyObject*)sock) == Py_None) {
1837 _setSSLError("Underlying socket connection gone",
1838 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1839 return NULL;
1840 }
1841 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001842 }
1843
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001844 buf.obj = NULL;
1845 buf.buf = NULL;
1846 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001847 goto error;
1848
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001849 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1850 dest = PyBytes_FromStringAndSize(NULL, len);
1851 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001852 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001853 mem = PyBytes_AS_STRING(dest);
1854 }
1855 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001857 mem = buf.buf;
1858 if (len <= 0 || len > buf.len) {
1859 len = (int) buf.len;
1860 if (buf.len != len) {
1861 PyErr_SetString(PyExc_OverflowError,
1862 "maximum length can't fit in a C 'int'");
1863 goto error;
1864 }
1865 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001866 }
1867
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001868 if (sock != NULL) {
1869 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001870 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001871 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1872 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1873 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001874
Victor Stinner14690702015-04-06 22:46:13 +02001875 timeout = GET_SOCKET_TIMEOUT(sock);
1876 has_timeout = (timeout > 0);
1877 if (has_timeout)
1878 deadline = _PyTime_GetMonotonicClock() + timeout;
1879
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001880 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001881 PySSL_BEGIN_ALLOW_THREADS
1882 count = SSL_read(self->ssl, mem, len);
1883 err = SSL_get_error(self->ssl, count);
1884 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001885
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001886 if (PyErr_CheckSignals())
1887 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001888
Victor Stinner14690702015-04-06 22:46:13 +02001889 if (has_timeout)
1890 timeout = deadline - _PyTime_GetMonotonicClock();
1891
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001892 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001893 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001894 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001895 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001896 } else if (err == SSL_ERROR_ZERO_RETURN &&
1897 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001898 {
1899 count = 0;
1900 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001901 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001902 else
1903 sockstate = SOCKET_OPERATION_OK;
1904
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001905 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001906 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001907 "The read operation timed out");
1908 goto error;
1909 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1910 break;
1911 }
1912 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001913
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001914 if (count <= 0) {
1915 PySSL_SetError(self, count, __FILE__, __LINE__);
1916 goto error;
1917 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001918
1919done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001920 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001921 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001922 _PyBytes_Resize(&dest, count);
1923 return dest;
1924 }
1925 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001926 PyBuffer_Release(&buf);
1927 return PyLong_FromLong(count);
1928 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001929
1930error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001931 Py_XDECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001932 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001933 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001934 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001935 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001936 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001937}
1938
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001939PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001940"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001941\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001942Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001943
Antoine Pitrou152efa22010-05-16 18:19:27 +00001944static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001945{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001946 int err, ssl_err, sockstate, nonblocking;
1947 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001948 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001949 _PyTime_t timeout, deadline = 0;
1950 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00001951
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001952 if (sock != NULL) {
1953 /* Guard against closed socket */
1954 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1955 _setSSLError("Underlying socket connection gone",
1956 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1957 return NULL;
1958 }
1959 Py_INCREF(sock);
1960
1961 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001962 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001963 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1964 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001965 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001966
Victor Stinner14690702015-04-06 22:46:13 +02001967 timeout = GET_SOCKET_TIMEOUT(sock);
1968 has_timeout = (timeout > 0);
1969 if (has_timeout)
1970 deadline = _PyTime_GetMonotonicClock() + timeout;
1971
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001972 while (1) {
1973 PySSL_BEGIN_ALLOW_THREADS
1974 /* Disable read-ahead so that unwrap can work correctly.
1975 * Otherwise OpenSSL might read in too much data,
1976 * eating clear text data that happens to be
1977 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001978 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001979 * function is used and the shutdown_seen_zero != 0
1980 * condition is met.
1981 */
1982 if (self->shutdown_seen_zero)
1983 SSL_set_read_ahead(self->ssl, 0);
1984 err = SSL_shutdown(self->ssl);
1985 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001986
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001987 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1988 if (err > 0)
1989 break;
1990 if (err == 0) {
1991 /* Don't loop endlessly; instead preserve legacy
1992 behaviour of trying SSL_shutdown() only twice.
1993 This looks necessary for OpenSSL < 0.9.8m */
1994 if (++zeros > 1)
1995 break;
1996 /* Shutdown was sent, now try receiving */
1997 self->shutdown_seen_zero = 1;
1998 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001999 }
2000
Victor Stinner14690702015-04-06 22:46:13 +02002001 if (has_timeout)
2002 timeout = deadline - _PyTime_GetMonotonicClock();
2003
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002004 /* Possibly retry shutdown until timeout or failure */
2005 ssl_err = SSL_get_error(self->ssl, err);
2006 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002007 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002008 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002009 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002010 else
2011 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002012
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002013 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2014 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002015 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002016 "The read operation timed out");
2017 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002018 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002019 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002020 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002021 }
2022 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2023 PyErr_SetString(PySSLErrorObject,
2024 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002025 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002026 }
2027 else if (sockstate != SOCKET_OPERATION_OK)
2028 /* Retain the SSL error code */
2029 break;
2030 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002031
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002032 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002033 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002034 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002035 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002036 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002037 /* It's already INCREF'ed */
2038 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002039 else
2040 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002041
2042error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002043 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002044 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002045}
2046
2047PyDoc_STRVAR(PySSL_SSLshutdown_doc,
2048"shutdown(s) -> socket\n\
2049\n\
2050Does the SSL shutdown handshake with the remote end, and returns\n\
2051the underlying socket object.");
2052
Antoine Pitroud6494802011-07-21 01:11:30 +02002053static PyObject *
2054PySSL_tls_unique_cb(PySSLSocket *self)
2055{
2056 PyObject *retval = NULL;
2057 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002058 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002059
2060 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2061 /* if session is resumed XOR we are the client */
2062 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2063 }
2064 else {
2065 /* if a new session XOR we are the server */
2066 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2067 }
2068
2069 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002070 if (len == 0)
2071 Py_RETURN_NONE;
2072
2073 retval = PyBytes_FromStringAndSize(buf, len);
2074
2075 return retval;
2076}
2077
2078PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2079"tls_unique_cb() -> bytes\n\
2080\n\
2081Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2082\n\
2083If the TLS handshake is not yet complete, None is returned");
2084
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002085static PyGetSetDef ssl_getsetlist[] = {
2086 {"context", (getter) PySSL_get_context,
2087 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002088 {"server_side", (getter) PySSL_get_server_side, NULL,
2089 PySSL_get_server_side_doc},
2090 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2091 PySSL_get_server_hostname_doc},
2092 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2093 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002094 {NULL}, /* sentinel */
2095};
2096
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002097static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002098 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2099 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2100 PySSL_SSLwrite_doc},
2101 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2102 PySSL_SSLread_doc},
2103 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2104 PySSL_SSLpending_doc},
2105 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2106 PySSL_peercert_doc},
2107 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002108 {"shared_ciphers", (PyCFunction)PySSL_shared_ciphers, METH_NOARGS},
Antoine Pitrou47e40422014-09-04 21:00:10 +02002109 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002110#ifdef OPENSSL_NPN_NEGOTIATED
2111 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2112#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002113#ifdef HAVE_ALPN
2114 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2115#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002116 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002117 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2118 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02002119 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2120 PySSL_tls_unique_cb_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002121 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002122};
2123
Antoine Pitrou152efa22010-05-16 18:19:27 +00002124static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002125 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002126 "_ssl._SSLSocket", /*tp_name*/
2127 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002128 0, /*tp_itemsize*/
2129 /* methods */
2130 (destructor)PySSL_dealloc, /*tp_dealloc*/
2131 0, /*tp_print*/
2132 0, /*tp_getattr*/
2133 0, /*tp_setattr*/
2134 0, /*tp_reserved*/
2135 0, /*tp_repr*/
2136 0, /*tp_as_number*/
2137 0, /*tp_as_sequence*/
2138 0, /*tp_as_mapping*/
2139 0, /*tp_hash*/
2140 0, /*tp_call*/
2141 0, /*tp_str*/
2142 0, /*tp_getattro*/
2143 0, /*tp_setattro*/
2144 0, /*tp_as_buffer*/
2145 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2146 0, /*tp_doc*/
2147 0, /*tp_traverse*/
2148 0, /*tp_clear*/
2149 0, /*tp_richcompare*/
2150 0, /*tp_weaklistoffset*/
2151 0, /*tp_iter*/
2152 0, /*tp_iternext*/
2153 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002154 0, /*tp_members*/
2155 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002156};
2157
Antoine Pitrou152efa22010-05-16 18:19:27 +00002158
2159/*
2160 * _SSLContext objects
2161 */
2162
2163static PyObject *
2164context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2165{
2166 char *kwlist[] = {"protocol", NULL};
2167 PySSLContext *self;
2168 int proto_version = PY_SSL_VERSION_SSL23;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002169 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002170 SSL_CTX *ctx = NULL;
2171
2172 if (!PyArg_ParseTupleAndKeywords(
2173 args, kwds, "i:_SSLContext", kwlist,
2174 &proto_version))
2175 return NULL;
2176
2177 PySSL_BEGIN_ALLOW_THREADS
2178 if (proto_version == PY_SSL_VERSION_TLS1)
2179 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002180#if HAVE_TLSv1_2
2181 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2182 ctx = SSL_CTX_new(TLSv1_1_method());
2183 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2184 ctx = SSL_CTX_new(TLSv1_2_method());
2185#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002186#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002187 else if (proto_version == PY_SSL_VERSION_SSL3)
2188 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002189#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002190#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002191 else if (proto_version == PY_SSL_VERSION_SSL2)
2192 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002193#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002194 else if (proto_version == PY_SSL_VERSION_SSL23)
2195 ctx = SSL_CTX_new(SSLv23_method());
2196 else
2197 proto_version = -1;
2198 PySSL_END_ALLOW_THREADS
2199
2200 if (proto_version == -1) {
2201 PyErr_SetString(PyExc_ValueError,
2202 "invalid protocol version");
2203 return NULL;
2204 }
2205 if (ctx == NULL) {
2206 PyErr_SetString(PySSLErrorObject,
2207 "failed to allocate SSL context");
2208 return NULL;
2209 }
2210
2211 assert(type != NULL && type->tp_alloc != NULL);
2212 self = (PySSLContext *) type->tp_alloc(type, 0);
2213 if (self == NULL) {
2214 SSL_CTX_free(ctx);
2215 return NULL;
2216 }
2217 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002218#ifdef OPENSSL_NPN_NEGOTIATED
2219 self->npn_protocols = NULL;
2220#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002221#ifdef HAVE_ALPN
2222 self->alpn_protocols = NULL;
2223#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002224#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002225 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002226#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002227 /* Don't check host name by default */
2228 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002229 /* Defaults */
2230 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002231 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2232 if (proto_version != PY_SSL_VERSION_SSL2)
2233 options |= SSL_OP_NO_SSLv2;
2234 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002235
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002236#ifndef OPENSSL_NO_ECDH
2237 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2238 prime256v1 by default. This is Apache mod_ssl's initialization
2239 policy, so we should be safe. */
2240#if defined(SSL_CTX_set_ecdh_auto)
2241 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2242#else
2243 {
2244 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2245 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2246 EC_KEY_free(key);
2247 }
2248#endif
2249#endif
2250
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002251#define SID_CTX "Python"
2252 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2253 sizeof(SID_CTX));
2254#undef SID_CTX
2255
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002256#ifdef X509_V_FLAG_TRUSTED_FIRST
2257 {
2258 /* Improve trust chain building when cross-signed intermediate
2259 certificates are present. See https://bugs.python.org/issue23476. */
2260 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2261 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2262 }
2263#endif
2264
Antoine Pitrou152efa22010-05-16 18:19:27 +00002265 return (PyObject *)self;
2266}
2267
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002268static int
2269context_traverse(PySSLContext *self, visitproc visit, void *arg)
2270{
2271#ifndef OPENSSL_NO_TLSEXT
2272 Py_VISIT(self->set_hostname);
2273#endif
2274 return 0;
2275}
2276
2277static int
2278context_clear(PySSLContext *self)
2279{
2280#ifndef OPENSSL_NO_TLSEXT
2281 Py_CLEAR(self->set_hostname);
2282#endif
2283 return 0;
2284}
2285
Antoine Pitrou152efa22010-05-16 18:19:27 +00002286static void
2287context_dealloc(PySSLContext *self)
2288{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002289 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002290 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002291#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002292 PyMem_FREE(self->npn_protocols);
2293#endif
2294#ifdef HAVE_ALPN
2295 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002296#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002297 Py_TYPE(self)->tp_free(self);
2298}
2299
2300static PyObject *
2301set_ciphers(PySSLContext *self, PyObject *args)
2302{
2303 int ret;
2304 const char *cipherlist;
2305
2306 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2307 return NULL;
2308 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2309 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002310 /* Clearing the error queue is necessary on some OpenSSL versions,
2311 otherwise the error will be reported again when another SSL call
2312 is done. */
2313 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002314 PyErr_SetString(PySSLErrorObject,
2315 "No cipher can be selected.");
2316 return NULL;
2317 }
2318 Py_RETURN_NONE;
2319}
2320
Benjamin Petersonc54de472015-01-28 12:06:39 -05002321#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002322static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002323do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2324 const unsigned char *server_protocols, unsigned int server_protocols_len,
2325 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002326{
Benjamin Peterson88615022015-01-23 17:30:26 -05002327 int ret;
2328 if (client_protocols == NULL) {
2329 client_protocols = (unsigned char *)"";
2330 client_protocols_len = 0;
2331 }
2332 if (server_protocols == NULL) {
2333 server_protocols = (unsigned char *)"";
2334 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002335 }
2336
Benjamin Peterson88615022015-01-23 17:30:26 -05002337 ret = SSL_select_next_proto(out, outlen,
2338 server_protocols, server_protocols_len,
2339 client_protocols, client_protocols_len);
2340 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2341 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002342
2343 return SSL_TLSEXT_ERR_OK;
2344}
2345
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002346/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2347static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002348_advertiseNPN_cb(SSL *s,
2349 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002350 void *args)
2351{
2352 PySSLContext *ssl_ctx = (PySSLContext *) args;
2353
2354 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002355 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002356 *len = 0;
2357 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002358 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002359 *len = ssl_ctx->npn_protocols_len;
2360 }
2361
2362 return SSL_TLSEXT_ERR_OK;
2363}
2364/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2365static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002366_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002367 unsigned char **out, unsigned char *outlen,
2368 const unsigned char *server, unsigned int server_len,
2369 void *args)
2370{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002371 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002372 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002373 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002374}
2375#endif
2376
2377static PyObject *
2378_set_npn_protocols(PySSLContext *self, PyObject *args)
2379{
2380#ifdef OPENSSL_NPN_NEGOTIATED
2381 Py_buffer protos;
2382
2383 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2384 return NULL;
2385
Christian Heimes5cb31c92012-09-20 12:42:54 +02002386 if (self->npn_protocols != NULL) {
2387 PyMem_Free(self->npn_protocols);
2388 }
2389
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002390 self->npn_protocols = PyMem_Malloc(protos.len);
2391 if (self->npn_protocols == NULL) {
2392 PyBuffer_Release(&protos);
2393 return PyErr_NoMemory();
2394 }
2395 memcpy(self->npn_protocols, protos.buf, protos.len);
2396 self->npn_protocols_len = (int) protos.len;
2397
2398 /* set both server and client callbacks, because the context can
2399 * be used to create both types of sockets */
2400 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2401 _advertiseNPN_cb,
2402 self);
2403 SSL_CTX_set_next_proto_select_cb(self->ctx,
2404 _selectNPN_cb,
2405 self);
2406
2407 PyBuffer_Release(&protos);
2408 Py_RETURN_NONE;
2409#else
2410 PyErr_SetString(PyExc_NotImplementedError,
2411 "The NPN extension requires OpenSSL 1.0.1 or later.");
2412 return NULL;
2413#endif
2414}
2415
Benjamin Petersoncca27322015-01-23 16:35:37 -05002416#ifdef HAVE_ALPN
2417static int
2418_selectALPN_cb(SSL *s,
2419 const unsigned char **out, unsigned char *outlen,
2420 const unsigned char *client_protocols, unsigned int client_protocols_len,
2421 void *args)
2422{
2423 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002424 return do_protocol_selection(1, (unsigned char **)out, outlen,
2425 ctx->alpn_protocols, ctx->alpn_protocols_len,
2426 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002427}
2428#endif
2429
2430static PyObject *
2431_set_alpn_protocols(PySSLContext *self, PyObject *args)
2432{
2433#ifdef HAVE_ALPN
2434 Py_buffer protos;
2435
2436 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2437 return NULL;
2438
2439 PyMem_FREE(self->alpn_protocols);
2440 self->alpn_protocols = PyMem_Malloc(protos.len);
2441 if (!self->alpn_protocols)
2442 return PyErr_NoMemory();
2443 memcpy(self->alpn_protocols, protos.buf, protos.len);
2444 self->alpn_protocols_len = protos.len;
2445 PyBuffer_Release(&protos);
2446
2447 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2448 return PyErr_NoMemory();
2449 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2450
2451 PyBuffer_Release(&protos);
2452 Py_RETURN_NONE;
2453#else
2454 PyErr_SetString(PyExc_NotImplementedError,
2455 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2456 return NULL;
2457#endif
2458}
2459
Antoine Pitrou152efa22010-05-16 18:19:27 +00002460static PyObject *
2461get_verify_mode(PySSLContext *self, void *c)
2462{
2463 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2464 case SSL_VERIFY_NONE:
2465 return PyLong_FromLong(PY_SSL_CERT_NONE);
2466 case SSL_VERIFY_PEER:
2467 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2468 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2469 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2470 }
2471 PyErr_SetString(PySSLErrorObject,
2472 "invalid return value from SSL_CTX_get_verify_mode");
2473 return NULL;
2474}
2475
2476static int
2477set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2478{
2479 int n, mode;
2480 if (!PyArg_Parse(arg, "i", &n))
2481 return -1;
2482 if (n == PY_SSL_CERT_NONE)
2483 mode = SSL_VERIFY_NONE;
2484 else if (n == PY_SSL_CERT_OPTIONAL)
2485 mode = SSL_VERIFY_PEER;
2486 else if (n == PY_SSL_CERT_REQUIRED)
2487 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2488 else {
2489 PyErr_SetString(PyExc_ValueError,
2490 "invalid value for verify_mode");
2491 return -1;
2492 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002493 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2494 PyErr_SetString(PyExc_ValueError,
2495 "Cannot set verify_mode to CERT_NONE when "
2496 "check_hostname is enabled.");
2497 return -1;
2498 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002499 SSL_CTX_set_verify(self->ctx, mode, NULL);
2500 return 0;
2501}
2502
2503static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002504get_verify_flags(PySSLContext *self, void *c)
2505{
2506 X509_STORE *store;
2507 unsigned long flags;
2508
2509 store = SSL_CTX_get_cert_store(self->ctx);
2510 flags = X509_VERIFY_PARAM_get_flags(store->param);
2511 return PyLong_FromUnsignedLong(flags);
2512}
2513
2514static int
2515set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2516{
2517 X509_STORE *store;
2518 unsigned long new_flags, flags, set, clear;
2519
2520 if (!PyArg_Parse(arg, "k", &new_flags))
2521 return -1;
2522 store = SSL_CTX_get_cert_store(self->ctx);
2523 flags = X509_VERIFY_PARAM_get_flags(store->param);
2524 clear = flags & ~new_flags;
2525 set = ~flags & new_flags;
2526 if (clear) {
2527 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2528 _setSSLError(NULL, 0, __FILE__, __LINE__);
2529 return -1;
2530 }
2531 }
2532 if (set) {
2533 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2534 _setSSLError(NULL, 0, __FILE__, __LINE__);
2535 return -1;
2536 }
2537 }
2538 return 0;
2539}
2540
2541static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002542get_options(PySSLContext *self, void *c)
2543{
2544 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2545}
2546
2547static int
2548set_options(PySSLContext *self, PyObject *arg, void *c)
2549{
2550 long new_opts, opts, set, clear;
2551 if (!PyArg_Parse(arg, "l", &new_opts))
2552 return -1;
2553 opts = SSL_CTX_get_options(self->ctx);
2554 clear = opts & ~new_opts;
2555 set = ~opts & new_opts;
2556 if (clear) {
2557#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2558 SSL_CTX_clear_options(self->ctx, clear);
2559#else
2560 PyErr_SetString(PyExc_ValueError,
2561 "can't clear options before OpenSSL 0.9.8m");
2562 return -1;
2563#endif
2564 }
2565 if (set)
2566 SSL_CTX_set_options(self->ctx, set);
2567 return 0;
2568}
2569
Christian Heimes1aa9a752013-12-02 02:41:19 +01002570static PyObject *
2571get_check_hostname(PySSLContext *self, void *c)
2572{
2573 return PyBool_FromLong(self->check_hostname);
2574}
2575
2576static int
2577set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2578{
2579 int check_hostname;
2580 if (!PyArg_Parse(arg, "p", &check_hostname))
2581 return -1;
2582 if (check_hostname &&
2583 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2584 PyErr_SetString(PyExc_ValueError,
2585 "check_hostname needs a SSL context with either "
2586 "CERT_OPTIONAL or CERT_REQUIRED");
2587 return -1;
2588 }
2589 self->check_hostname = check_hostname;
2590 return 0;
2591}
2592
2593
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002594typedef struct {
2595 PyThreadState *thread_state;
2596 PyObject *callable;
2597 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002598 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002599 int error;
2600} _PySSLPasswordInfo;
2601
2602static int
2603_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2604 const char *bad_type_error)
2605{
2606 /* Set the password and size fields of a _PySSLPasswordInfo struct
2607 from a unicode, bytes, or byte array object.
2608 The password field will be dynamically allocated and must be freed
2609 by the caller */
2610 PyObject *password_bytes = NULL;
2611 const char *data = NULL;
2612 Py_ssize_t size;
2613
2614 if (PyUnicode_Check(password)) {
2615 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2616 if (!password_bytes) {
2617 goto error;
2618 }
2619 data = PyBytes_AS_STRING(password_bytes);
2620 size = PyBytes_GET_SIZE(password_bytes);
2621 } else if (PyBytes_Check(password)) {
2622 data = PyBytes_AS_STRING(password);
2623 size = PyBytes_GET_SIZE(password);
2624 } else if (PyByteArray_Check(password)) {
2625 data = PyByteArray_AS_STRING(password);
2626 size = PyByteArray_GET_SIZE(password);
2627 } else {
2628 PyErr_SetString(PyExc_TypeError, bad_type_error);
2629 goto error;
2630 }
2631
Victor Stinner9ee02032013-06-23 15:08:23 +02002632 if (size > (Py_ssize_t)INT_MAX) {
2633 PyErr_Format(PyExc_ValueError,
2634 "password cannot be longer than %d bytes", INT_MAX);
2635 goto error;
2636 }
2637
Victor Stinner11ebff22013-07-07 17:07:52 +02002638 PyMem_Free(pw_info->password);
2639 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002640 if (!pw_info->password) {
2641 PyErr_SetString(PyExc_MemoryError,
2642 "unable to allocate password buffer");
2643 goto error;
2644 }
2645 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002646 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002647
2648 Py_XDECREF(password_bytes);
2649 return 1;
2650
2651error:
2652 Py_XDECREF(password_bytes);
2653 return 0;
2654}
2655
2656static int
2657_password_callback(char *buf, int size, int rwflag, void *userdata)
2658{
2659 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2660 PyObject *fn_ret = NULL;
2661
2662 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2663
2664 if (pw_info->callable) {
2665 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2666 if (!fn_ret) {
2667 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2668 core python API, so we could use it to add a frame here */
2669 goto error;
2670 }
2671
2672 if (!_pwinfo_set(pw_info, fn_ret,
2673 "password callback must return a string")) {
2674 goto error;
2675 }
2676 Py_CLEAR(fn_ret);
2677 }
2678
2679 if (pw_info->size > size) {
2680 PyErr_Format(PyExc_ValueError,
2681 "password cannot be longer than %d bytes", size);
2682 goto error;
2683 }
2684
2685 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2686 memcpy(buf, pw_info->password, pw_info->size);
2687 return pw_info->size;
2688
2689error:
2690 Py_XDECREF(fn_ret);
2691 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2692 pw_info->error = 1;
2693 return -1;
2694}
2695
Antoine Pitroub5218772010-05-21 09:56:06 +00002696static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002697load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2698{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002699 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2700 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002701 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002702 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2703 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2704 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002705 int r;
2706
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002707 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002708 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002709 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002710 "O|OO:load_cert_chain", kwlist,
2711 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002712 return NULL;
2713 if (keyfile == Py_None)
2714 keyfile = NULL;
2715 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2716 PyErr_SetString(PyExc_TypeError,
2717 "certfile should be a valid filesystem path");
2718 return NULL;
2719 }
2720 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2721 PyErr_SetString(PyExc_TypeError,
2722 "keyfile should be a valid filesystem path");
2723 goto error;
2724 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002725 if (password && password != Py_None) {
2726 if (PyCallable_Check(password)) {
2727 pw_info.callable = password;
2728 } else if (!_pwinfo_set(&pw_info, password,
2729 "password should be a string or callable")) {
2730 goto error;
2731 }
2732 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2733 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2734 }
2735 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002736 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2737 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002738 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002739 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002740 if (pw_info.error) {
2741 ERR_clear_error();
2742 /* the password callback has already set the error information */
2743 }
2744 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002745 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002746 PyErr_SetFromErrno(PyExc_IOError);
2747 }
2748 else {
2749 _setSSLError(NULL, 0, __FILE__, __LINE__);
2750 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002751 goto error;
2752 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002753 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002754 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002755 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2756 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002757 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2758 Py_CLEAR(keyfile_bytes);
2759 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002760 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002761 if (pw_info.error) {
2762 ERR_clear_error();
2763 /* the password callback has already set the error information */
2764 }
2765 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002766 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002767 PyErr_SetFromErrno(PyExc_IOError);
2768 }
2769 else {
2770 _setSSLError(NULL, 0, __FILE__, __LINE__);
2771 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002772 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002773 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002774 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002775 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002776 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002777 if (r != 1) {
2778 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002779 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002780 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002781 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2782 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002783 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002784 Py_RETURN_NONE;
2785
2786error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002787 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2788 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002789 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002790 Py_XDECREF(keyfile_bytes);
2791 Py_XDECREF(certfile_bytes);
2792 return NULL;
2793}
2794
Christian Heimesefff7062013-11-21 03:35:02 +01002795/* internal helper function, returns -1 on error
2796 */
2797static int
2798_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2799 int filetype)
2800{
2801 BIO *biobuf = NULL;
2802 X509_STORE *store;
2803 int retval = 0, err, loaded = 0;
2804
2805 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2806
2807 if (len <= 0) {
2808 PyErr_SetString(PyExc_ValueError,
2809 "Empty certificate data");
2810 return -1;
2811 } else if (len > INT_MAX) {
2812 PyErr_SetString(PyExc_OverflowError,
2813 "Certificate data is too long.");
2814 return -1;
2815 }
2816
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002817 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002818 if (biobuf == NULL) {
2819 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2820 return -1;
2821 }
2822
2823 store = SSL_CTX_get_cert_store(self->ctx);
2824 assert(store != NULL);
2825
2826 while (1) {
2827 X509 *cert = NULL;
2828 int r;
2829
2830 if (filetype == SSL_FILETYPE_ASN1) {
2831 cert = d2i_X509_bio(biobuf, NULL);
2832 } else {
2833 cert = PEM_read_bio_X509(biobuf, NULL,
2834 self->ctx->default_passwd_callback,
2835 self->ctx->default_passwd_callback_userdata);
2836 }
2837 if (cert == NULL) {
2838 break;
2839 }
2840 r = X509_STORE_add_cert(store, cert);
2841 X509_free(cert);
2842 if (!r) {
2843 err = ERR_peek_last_error();
2844 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2845 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2846 /* cert already in hash table, not an error */
2847 ERR_clear_error();
2848 } else {
2849 break;
2850 }
2851 }
2852 loaded++;
2853 }
2854
2855 err = ERR_peek_last_error();
2856 if ((filetype == SSL_FILETYPE_ASN1) &&
2857 (loaded > 0) &&
2858 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2859 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2860 /* EOF ASN1 file, not an error */
2861 ERR_clear_error();
2862 retval = 0;
2863 } else if ((filetype == SSL_FILETYPE_PEM) &&
2864 (loaded > 0) &&
2865 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2866 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2867 /* EOF PEM file, not an error */
2868 ERR_clear_error();
2869 retval = 0;
2870 } else {
2871 _setSSLError(NULL, 0, __FILE__, __LINE__);
2872 retval = -1;
2873 }
2874
2875 BIO_free(biobuf);
2876 return retval;
2877}
2878
2879
Antoine Pitrou152efa22010-05-16 18:19:27 +00002880static PyObject *
2881load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2882{
Christian Heimesefff7062013-11-21 03:35:02 +01002883 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2884 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002885 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2886 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002887 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002888
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002889 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002890 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002891 "|OOO:load_verify_locations", kwlist,
2892 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002893 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002894
Antoine Pitrou152efa22010-05-16 18:19:27 +00002895 if (cafile == Py_None)
2896 cafile = NULL;
2897 if (capath == Py_None)
2898 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002899 if (cadata == Py_None)
2900 cadata = NULL;
2901
2902 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002903 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002904 "cafile, capath and cadata cannot be all omitted");
2905 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002906 }
2907 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2908 PyErr_SetString(PyExc_TypeError,
2909 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002910 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002911 }
2912 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002913 PyErr_SetString(PyExc_TypeError,
2914 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002915 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002916 }
Christian Heimesefff7062013-11-21 03:35:02 +01002917
2918 /* validata cadata type and load cadata */
2919 if (cadata) {
2920 Py_buffer buf;
2921 PyObject *cadata_ascii = NULL;
2922
2923 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2924 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2925 PyBuffer_Release(&buf);
2926 PyErr_SetString(PyExc_TypeError,
2927 "cadata should be a contiguous buffer with "
2928 "a single dimension");
2929 goto error;
2930 }
2931 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2932 PyBuffer_Release(&buf);
2933 if (r == -1) {
2934 goto error;
2935 }
2936 } else {
2937 PyErr_Clear();
2938 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2939 if (cadata_ascii == NULL) {
2940 PyErr_SetString(PyExc_TypeError,
2941 "cadata should be a ASCII string or a "
2942 "bytes-like object");
2943 goto error;
2944 }
2945 r = _add_ca_certs(self,
2946 PyBytes_AS_STRING(cadata_ascii),
2947 PyBytes_GET_SIZE(cadata_ascii),
2948 SSL_FILETYPE_PEM);
2949 Py_DECREF(cadata_ascii);
2950 if (r == -1) {
2951 goto error;
2952 }
2953 }
2954 }
2955
2956 /* load cafile or capath */
2957 if (cafile || capath) {
2958 if (cafile)
2959 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2960 if (capath)
2961 capath_buf = PyBytes_AS_STRING(capath_bytes);
2962 PySSL_BEGIN_ALLOW_THREADS
2963 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2964 PySSL_END_ALLOW_THREADS
2965 if (r != 1) {
2966 ok = 0;
2967 if (errno != 0) {
2968 ERR_clear_error();
2969 PyErr_SetFromErrno(PyExc_IOError);
2970 }
2971 else {
2972 _setSSLError(NULL, 0, __FILE__, __LINE__);
2973 }
2974 goto error;
2975 }
2976 }
2977 goto end;
2978
2979 error:
2980 ok = 0;
2981 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002982 Py_XDECREF(cafile_bytes);
2983 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002984 if (ok) {
2985 Py_RETURN_NONE;
2986 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002987 return NULL;
2988 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002989}
2990
2991static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002992load_dh_params(PySSLContext *self, PyObject *filepath)
2993{
2994 FILE *f;
2995 DH *dh;
2996
Victor Stinnerdaf45552013-08-28 00:53:59 +02002997 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01002998 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002999 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003000
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003001 errno = 0;
3002 PySSL_BEGIN_ALLOW_THREADS
3003 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003004 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003005 PySSL_END_ALLOW_THREADS
3006 if (dh == NULL) {
3007 if (errno != 0) {
3008 ERR_clear_error();
3009 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3010 }
3011 else {
3012 _setSSLError(NULL, 0, __FILE__, __LINE__);
3013 }
3014 return NULL;
3015 }
3016 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3017 _setSSLError(NULL, 0, __FILE__, __LINE__);
3018 DH_free(dh);
3019 Py_RETURN_NONE;
3020}
3021
3022static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00003023context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
3024{
Antoine Pitroud5323212010-10-22 18:19:07 +00003025 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00003026 PySocketSockObject *sock;
3027 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00003028 char *hostname = NULL;
3029 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003030
Antoine Pitroud5323212010-10-22 18:19:07 +00003031 /* server_hostname is either None (or absent), or to be encoded
3032 using the idna encoding. */
3033 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003034 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00003035 &sock, &server_side,
3036 Py_TYPE(Py_None), &hostname_obj)) {
3037 PyErr_Clear();
3038 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
3039 PySocketModule.Sock_Type,
3040 &sock, &server_side,
3041 "idna", &hostname))
3042 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003043 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003044
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003045 res = (PyObject *) newPySSLSocket(self, sock, server_side, hostname,
3046 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003047 if (hostname != NULL)
3048 PyMem_Free(hostname);
3049 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003050}
3051
Antoine Pitroub0182c82010-10-12 20:09:02 +00003052static PyObject *
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003053context_wrap_bio(PySSLContext *self, PyObject *args, PyObject *kwds)
3054{
3055 char *kwlist[] = {"incoming", "outgoing", "server_side",
3056 "server_hostname", NULL};
3057 int server_side;
3058 char *hostname = NULL;
3059 PyObject *hostname_obj = Py_None, *res;
3060 PySSLMemoryBIO *incoming, *outgoing;
3061
3062 /* server_hostname is either None (or absent), or to be encoded
3063 using the idna encoding. */
3064 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!O!i|O:_wrap_bio", kwlist,
3065 &PySSLMemoryBIO_Type, &incoming,
3066 &PySSLMemoryBIO_Type, &outgoing,
3067 &server_side, &hostname_obj))
3068 return NULL;
3069 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003070 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3071 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003072 }
3073
3074 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3075 incoming, outgoing);
3076
3077 PyMem_Free(hostname);
3078 return res;
3079}
3080
3081static PyObject *
Antoine Pitroub0182c82010-10-12 20:09:02 +00003082session_stats(PySSLContext *self, PyObject *unused)
3083{
3084 int r;
3085 PyObject *value, *stats = PyDict_New();
3086 if (!stats)
3087 return NULL;
3088
3089#define ADD_STATS(SSL_NAME, KEY_NAME) \
3090 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3091 if (value == NULL) \
3092 goto error; \
3093 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3094 Py_DECREF(value); \
3095 if (r < 0) \
3096 goto error;
3097
3098 ADD_STATS(number, "number");
3099 ADD_STATS(connect, "connect");
3100 ADD_STATS(connect_good, "connect_good");
3101 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3102 ADD_STATS(accept, "accept");
3103 ADD_STATS(accept_good, "accept_good");
3104 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3105 ADD_STATS(accept, "accept");
3106 ADD_STATS(hits, "hits");
3107 ADD_STATS(misses, "misses");
3108 ADD_STATS(timeouts, "timeouts");
3109 ADD_STATS(cache_full, "cache_full");
3110
3111#undef ADD_STATS
3112
3113 return stats;
3114
3115error:
3116 Py_DECREF(stats);
3117 return NULL;
3118}
3119
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003120static PyObject *
3121set_default_verify_paths(PySSLContext *self, PyObject *unused)
3122{
3123 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3124 _setSSLError(NULL, 0, __FILE__, __LINE__);
3125 return NULL;
3126 }
3127 Py_RETURN_NONE;
3128}
3129
Antoine Pitrou501da612011-12-21 09:27:41 +01003130#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003131static PyObject *
3132set_ecdh_curve(PySSLContext *self, PyObject *name)
3133{
3134 PyObject *name_bytes;
3135 int nid;
3136 EC_KEY *key;
3137
3138 if (!PyUnicode_FSConverter(name, &name_bytes))
3139 return NULL;
3140 assert(PyBytes_Check(name_bytes));
3141 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3142 Py_DECREF(name_bytes);
3143 if (nid == 0) {
3144 PyErr_Format(PyExc_ValueError,
3145 "unknown elliptic curve name %R", name);
3146 return NULL;
3147 }
3148 key = EC_KEY_new_by_curve_name(nid);
3149 if (key == NULL) {
3150 _setSSLError(NULL, 0, __FILE__, __LINE__);
3151 return NULL;
3152 }
3153 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3154 EC_KEY_free(key);
3155 Py_RETURN_NONE;
3156}
Antoine Pitrou501da612011-12-21 09:27:41 +01003157#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003158
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003159#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003160static int
3161_servername_callback(SSL *s, int *al, void *args)
3162{
3163 int ret;
3164 PySSLContext *ssl_ctx = (PySSLContext *) args;
3165 PySSLSocket *ssl;
3166 PyObject *servername_o;
3167 PyObject *servername_idna;
3168 PyObject *result;
3169 /* The high-level ssl.SSLSocket object */
3170 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003171 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003172#ifdef WITH_THREAD
3173 PyGILState_STATE gstate = PyGILState_Ensure();
3174#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003175
3176 if (ssl_ctx->set_hostname == NULL) {
3177 /* remove race condition in this the call back while if removing the
3178 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003179#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003180 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003181#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003182 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003183 }
3184
3185 ssl = SSL_get_app_data(s);
3186 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003187
3188 /* The servername callback expects a argument that represents the current
3189 * SSL connection and that has a .context attribute that can be changed to
3190 * identify the requested hostname. Since the official API is the Python
3191 * level API we want to pass the callback a Python level object rather than
3192 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3193 * SSLObject) that will be passed. Otherwise if there's a socket then that
3194 * will be passed. If both do not exist only then the C-level object is
3195 * passed. */
3196 if (ssl->owner)
3197 ssl_socket = PyWeakref_GetObject(ssl->owner);
3198 else if (ssl->Socket)
3199 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3200 else
3201 ssl_socket = (PyObject *) ssl;
3202
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003203 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003204 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003205 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003206
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003207 if (servername == NULL) {
3208 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3209 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003210 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003211 else {
3212 servername_o = PyBytes_FromString(servername);
3213 if (servername_o == NULL) {
3214 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3215 goto error;
3216 }
3217 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3218 if (servername_idna == NULL) {
3219 PyErr_WriteUnraisable(servername_o);
3220 Py_DECREF(servername_o);
3221 goto error;
3222 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003223 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003224 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3225 servername_idna, ssl_ctx, NULL);
3226 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003227 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003228 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003229
3230 if (result == NULL) {
3231 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3232 *al = SSL_AD_HANDSHAKE_FAILURE;
3233 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3234 }
3235 else {
3236 if (result != Py_None) {
3237 *al = (int) PyLong_AsLong(result);
3238 if (PyErr_Occurred()) {
3239 PyErr_WriteUnraisable(result);
3240 *al = SSL_AD_INTERNAL_ERROR;
3241 }
3242 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3243 }
3244 else {
3245 ret = SSL_TLSEXT_ERR_OK;
3246 }
3247 Py_DECREF(result);
3248 }
3249
Stefan Krah20d60802013-01-17 17:07:17 +01003250#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003251 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003252#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003253 return ret;
3254
3255error:
3256 Py_DECREF(ssl_socket);
3257 *al = SSL_AD_INTERNAL_ERROR;
3258 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003259#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003260 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003261#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003262 return ret;
3263}
Antoine Pitroua5963382013-03-30 16:39:00 +01003264#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003265
3266PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3267"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003268\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003269This sets a callback that will be called when a server name is provided by\n\
3270the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003271\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003272If the argument is None then the callback is disabled. The method is called\n\
3273with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003274See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003275
3276static PyObject *
3277set_servername_callback(PySSLContext *self, PyObject *args)
3278{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003279#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003280 PyObject *cb;
3281
3282 if (!PyArg_ParseTuple(args, "O", &cb))
3283 return NULL;
3284
3285 Py_CLEAR(self->set_hostname);
3286 if (cb == Py_None) {
3287 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3288 }
3289 else {
3290 if (!PyCallable_Check(cb)) {
3291 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3292 PyErr_SetString(PyExc_TypeError,
3293 "not a callable object");
3294 return NULL;
3295 }
3296 Py_INCREF(cb);
3297 self->set_hostname = cb;
3298 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3299 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3300 }
3301 Py_RETURN_NONE;
3302#else
3303 PyErr_SetString(PyExc_NotImplementedError,
3304 "The TLS extension servername callback, "
3305 "SSL_CTX_set_tlsext_servername_callback, "
3306 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003307 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003308#endif
3309}
3310
Christian Heimes9a5395a2013-06-17 15:44:12 +02003311PyDoc_STRVAR(PySSL_get_stats_doc,
3312"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3313\n\
3314Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3315CA extension and certificate revocation lists inside the context's cert\n\
3316store.\n\
3317NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3318been used at least once.");
3319
3320static PyObject *
3321cert_store_stats(PySSLContext *self)
3322{
3323 X509_STORE *store;
3324 X509_OBJECT *obj;
3325 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3326
3327 store = SSL_CTX_get_cert_store(self->ctx);
3328 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3329 obj = sk_X509_OBJECT_value(store->objs, i);
3330 switch (obj->type) {
3331 case X509_LU_X509:
3332 x509++;
3333 if (X509_check_ca(obj->data.x509)) {
3334 ca++;
3335 }
3336 break;
3337 case X509_LU_CRL:
3338 crl++;
3339 break;
3340 case X509_LU_PKEY:
3341 pkey++;
3342 break;
3343 default:
3344 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3345 * As far as I can tell they are internal states and never
3346 * stored in a cert store */
3347 break;
3348 }
3349 }
3350 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3351 "x509_ca", ca);
3352}
3353
3354PyDoc_STRVAR(PySSL_get_ca_certs_doc,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003355"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
Christian Heimes9a5395a2013-06-17 15:44:12 +02003356\n\
3357Returns a list of dicts with information of loaded CA certs. If the\n\
3358optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3359NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3360been used at least once.");
3361
3362static PyObject *
Christian Heimesf22e8e52013-11-22 02:22:51 +01003363get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
Christian Heimes9a5395a2013-06-17 15:44:12 +02003364{
Christian Heimesf22e8e52013-11-22 02:22:51 +01003365 char *kwlist[] = {"binary_form", NULL};
Christian Heimes9a5395a2013-06-17 15:44:12 +02003366 X509_STORE *store;
3367 PyObject *ci = NULL, *rlist = NULL;
3368 int i;
3369 int binary_mode = 0;
3370
Christian Heimesf22e8e52013-11-22 02:22:51 +01003371 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|p:get_ca_certs",
3372 kwlist, &binary_mode)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003373 return NULL;
3374 }
3375
3376 if ((rlist = PyList_New(0)) == NULL) {
3377 return NULL;
3378 }
3379
3380 store = SSL_CTX_get_cert_store(self->ctx);
3381 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3382 X509_OBJECT *obj;
3383 X509 *cert;
3384
3385 obj = sk_X509_OBJECT_value(store->objs, i);
3386 if (obj->type != X509_LU_X509) {
3387 /* not a x509 cert */
3388 continue;
3389 }
3390 /* CA for any purpose */
3391 cert = obj->data.x509;
3392 if (!X509_check_ca(cert)) {
3393 continue;
3394 }
3395 if (binary_mode) {
3396 ci = _certificate_to_der(cert);
3397 } else {
3398 ci = _decode_certificate(cert);
3399 }
3400 if (ci == NULL) {
3401 goto error;
3402 }
3403 if (PyList_Append(rlist, ci) == -1) {
3404 goto error;
3405 }
3406 Py_CLEAR(ci);
3407 }
3408 return rlist;
3409
3410 error:
3411 Py_XDECREF(ci);
3412 Py_XDECREF(rlist);
3413 return NULL;
3414}
3415
3416
Antoine Pitrou152efa22010-05-16 18:19:27 +00003417static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003418 {"check_hostname", (getter) get_check_hostname,
3419 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003420 {"options", (getter) get_options,
3421 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003422 {"verify_flags", (getter) get_verify_flags,
3423 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003424 {"verify_mode", (getter) get_verify_mode,
3425 (setter) set_verify_mode, NULL},
3426 {NULL}, /* sentinel */
3427};
3428
3429static struct PyMethodDef context_methods[] = {
3430 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3431 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003432 {"_wrap_bio", (PyCFunction) context_wrap_bio,
3433 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003434 {"set_ciphers", (PyCFunction) set_ciphers,
3435 METH_VARARGS, NULL},
Benjamin Petersoncca27322015-01-23 16:35:37 -05003436 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3437 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003438 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3439 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003440 {"load_cert_chain", (PyCFunction) load_cert_chain,
3441 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003442 {"load_dh_params", (PyCFunction) load_dh_params,
3443 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003444 {"load_verify_locations", (PyCFunction) load_verify_locations,
3445 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00003446 {"session_stats", (PyCFunction) session_stats,
3447 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003448 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3449 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003450#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003451 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3452 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003453#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003454 {"set_servername_callback", (PyCFunction) set_servername_callback,
3455 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02003456 {"cert_store_stats", (PyCFunction) cert_store_stats,
3457 METH_NOARGS, PySSL_get_stats_doc},
3458 {"get_ca_certs", (PyCFunction) get_ca_certs,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003459 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003460 {NULL, NULL} /* sentinel */
3461};
3462
3463static PyTypeObject PySSLContext_Type = {
3464 PyVarObject_HEAD_INIT(NULL, 0)
3465 "_ssl._SSLContext", /*tp_name*/
3466 sizeof(PySSLContext), /*tp_basicsize*/
3467 0, /*tp_itemsize*/
3468 (destructor)context_dealloc, /*tp_dealloc*/
3469 0, /*tp_print*/
3470 0, /*tp_getattr*/
3471 0, /*tp_setattr*/
3472 0, /*tp_reserved*/
3473 0, /*tp_repr*/
3474 0, /*tp_as_number*/
3475 0, /*tp_as_sequence*/
3476 0, /*tp_as_mapping*/
3477 0, /*tp_hash*/
3478 0, /*tp_call*/
3479 0, /*tp_str*/
3480 0, /*tp_getattro*/
3481 0, /*tp_setattro*/
3482 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003483 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003484 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003485 (traverseproc) context_traverse, /*tp_traverse*/
3486 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003487 0, /*tp_richcompare*/
3488 0, /*tp_weaklistoffset*/
3489 0, /*tp_iter*/
3490 0, /*tp_iternext*/
3491 context_methods, /*tp_methods*/
3492 0, /*tp_members*/
3493 context_getsetlist, /*tp_getset*/
3494 0, /*tp_base*/
3495 0, /*tp_dict*/
3496 0, /*tp_descr_get*/
3497 0, /*tp_descr_set*/
3498 0, /*tp_dictoffset*/
3499 0, /*tp_init*/
3500 0, /*tp_alloc*/
3501 context_new, /*tp_new*/
3502};
3503
3504
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003505/*
3506 * MemoryBIO objects
3507 */
3508
3509static PyObject *
3510memory_bio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3511{
3512 char *kwlist[] = {NULL};
3513 BIO *bio;
3514 PySSLMemoryBIO *self;
3515
3516 if (!PyArg_ParseTupleAndKeywords(args, kwds, ":MemoryBIO", kwlist))
3517 return NULL;
3518
3519 bio = BIO_new(BIO_s_mem());
3520 if (bio == NULL) {
3521 PyErr_SetString(PySSLErrorObject,
3522 "failed to allocate BIO");
3523 return NULL;
3524 }
3525 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3526 * just that no data is currently available. The SSL routines should retry
3527 * the read, which we can achieve by calling BIO_set_retry_read(). */
3528 BIO_set_retry_read(bio);
3529 BIO_set_mem_eof_return(bio, -1);
3530
3531 assert(type != NULL && type->tp_alloc != NULL);
3532 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3533 if (self == NULL) {
3534 BIO_free(bio);
3535 return NULL;
3536 }
3537 self->bio = bio;
3538 self->eof_written = 0;
3539
3540 return (PyObject *) self;
3541}
3542
3543static void
3544memory_bio_dealloc(PySSLMemoryBIO *self)
3545{
3546 BIO_free(self->bio);
3547 Py_TYPE(self)->tp_free(self);
3548}
3549
3550static PyObject *
3551memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3552{
3553 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3554}
3555
3556PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3557"The number of bytes pending in the memory BIO.");
3558
3559static PyObject *
3560memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3561{
3562 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3563 && self->eof_written);
3564}
3565
3566PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3567"Whether the memory BIO is at EOF.");
3568
3569static PyObject *
3570memory_bio_read(PySSLMemoryBIO *self, PyObject *args)
3571{
3572 int len = -1, avail, nbytes;
3573 PyObject *result;
3574
3575 if (!PyArg_ParseTuple(args, "|i:read", &len))
3576 return NULL;
3577
3578 avail = BIO_ctrl_pending(self->bio);
3579 if ((len < 0) || (len > avail))
3580 len = avail;
3581
3582 result = PyBytes_FromStringAndSize(NULL, len);
3583 if ((result == NULL) || (len == 0))
3584 return result;
3585
3586 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3587 /* There should never be any short reads but check anyway. */
3588 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3589 Py_DECREF(result);
3590 return NULL;
3591 }
3592
3593 return result;
3594}
3595
3596PyDoc_STRVAR(PySSL_memory_bio_read_doc,
3597"read([len]) -> bytes\n\
3598\n\
3599Read up to len bytes from the memory BIO.\n\
3600\n\
3601If len is not specified, read the entire buffer.\n\
3602If the return value is an empty bytes instance, this means either\n\
3603EOF or that no data is available. Use the \"eof\" property to\n\
3604distinguish between the two.");
3605
3606static PyObject *
3607memory_bio_write(PySSLMemoryBIO *self, PyObject *args)
3608{
3609 Py_buffer buf;
3610 int nbytes;
3611
3612 if (!PyArg_ParseTuple(args, "y*:write", &buf))
3613 return NULL;
3614
3615 if (buf.len > INT_MAX) {
3616 PyErr_Format(PyExc_OverflowError,
3617 "string longer than %d bytes", INT_MAX);
3618 goto error;
3619 }
3620
3621 if (self->eof_written) {
3622 PyErr_SetString(PySSLErrorObject,
3623 "cannot write() after write_eof()");
3624 goto error;
3625 }
3626
3627 nbytes = BIO_write(self->bio, buf.buf, buf.len);
3628 if (nbytes < 0) {
3629 _setSSLError(NULL, 0, __FILE__, __LINE__);
3630 goto error;
3631 }
3632
3633 PyBuffer_Release(&buf);
3634 return PyLong_FromLong(nbytes);
3635
3636error:
3637 PyBuffer_Release(&buf);
3638 return NULL;
3639}
3640
3641PyDoc_STRVAR(PySSL_memory_bio_write_doc,
3642"write(b) -> len\n\
3643\n\
3644Writes the bytes b into the memory BIO. Returns the number\n\
3645of bytes written.");
3646
3647static PyObject *
3648memory_bio_write_eof(PySSLMemoryBIO *self, PyObject *args)
3649{
3650 self->eof_written = 1;
3651 /* After an EOF is written, a zero return from read() should be a real EOF
3652 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3653 BIO_clear_retry_flags(self->bio);
3654 BIO_set_mem_eof_return(self->bio, 0);
3655
3656 Py_RETURN_NONE;
3657}
3658
3659PyDoc_STRVAR(PySSL_memory_bio_write_eof_doc,
3660"write_eof()\n\
3661\n\
3662Write an EOF marker to the memory BIO.\n\
3663When all data has been read, the \"eof\" property will be True.");
3664
3665static PyGetSetDef memory_bio_getsetlist[] = {
3666 {"pending", (getter) memory_bio_get_pending, NULL,
3667 PySSL_memory_bio_pending_doc},
3668 {"eof", (getter) memory_bio_get_eof, NULL,
3669 PySSL_memory_bio_eof_doc},
3670 {NULL}, /* sentinel */
3671};
3672
3673static struct PyMethodDef memory_bio_methods[] = {
3674 {"read", (PyCFunction) memory_bio_read,
3675 METH_VARARGS, PySSL_memory_bio_read_doc},
3676 {"write", (PyCFunction) memory_bio_write,
3677 METH_VARARGS, PySSL_memory_bio_write_doc},
3678 {"write_eof", (PyCFunction) memory_bio_write_eof,
3679 METH_NOARGS, PySSL_memory_bio_write_eof_doc},
3680 {NULL, NULL} /* sentinel */
3681};
3682
3683static PyTypeObject PySSLMemoryBIO_Type = {
3684 PyVarObject_HEAD_INIT(NULL, 0)
3685 "_ssl.MemoryBIO", /*tp_name*/
3686 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3687 0, /*tp_itemsize*/
3688 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3689 0, /*tp_print*/
3690 0, /*tp_getattr*/
3691 0, /*tp_setattr*/
3692 0, /*tp_reserved*/
3693 0, /*tp_repr*/
3694 0, /*tp_as_number*/
3695 0, /*tp_as_sequence*/
3696 0, /*tp_as_mapping*/
3697 0, /*tp_hash*/
3698 0, /*tp_call*/
3699 0, /*tp_str*/
3700 0, /*tp_getattro*/
3701 0, /*tp_setattro*/
3702 0, /*tp_as_buffer*/
3703 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3704 0, /*tp_doc*/
3705 0, /*tp_traverse*/
3706 0, /*tp_clear*/
3707 0, /*tp_richcompare*/
3708 0, /*tp_weaklistoffset*/
3709 0, /*tp_iter*/
3710 0, /*tp_iternext*/
3711 memory_bio_methods, /*tp_methods*/
3712 0, /*tp_members*/
3713 memory_bio_getsetlist, /*tp_getset*/
3714 0, /*tp_base*/
3715 0, /*tp_dict*/
3716 0, /*tp_descr_get*/
3717 0, /*tp_descr_set*/
3718 0, /*tp_dictoffset*/
3719 0, /*tp_init*/
3720 0, /*tp_alloc*/
3721 memory_bio_new, /*tp_new*/
3722};
3723
Antoine Pitrou152efa22010-05-16 18:19:27 +00003724
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003725/* helper routines for seeding the SSL PRNG */
3726static PyObject *
3727PySSL_RAND_add(PyObject *self, PyObject *args)
3728{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02003729 Py_buffer view;
3730 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003731 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003732 double entropy;
3733
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02003734 if (!PyArg_ParseTuple(args, "s*d:RAND_add", &view, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00003735 return NULL;
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02003736 buf = (const char *)view.buf;
3737 len = view.len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003738 do {
3739 written = Py_MIN(len, INT_MAX);
3740 RAND_add(buf, (int)written, entropy);
3741 buf += written;
3742 len -= written;
3743 } while (len);
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02003744 PyBuffer_Release(&view);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003745 Py_INCREF(Py_None);
3746 return Py_None;
3747}
3748
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003749PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003750"RAND_add(string, entropy)\n\
3751\n\
3752Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003753bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003754
3755static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003756PySSL_RAND(int len, int pseudo)
3757{
3758 int ok;
3759 PyObject *bytes;
3760 unsigned long err;
3761 const char *errstr;
3762 PyObject *v;
3763
Victor Stinner1e81a392013-12-19 16:47:04 +01003764 if (len < 0) {
3765 PyErr_SetString(PyExc_ValueError, "num must be positive");
3766 return NULL;
3767 }
3768
Victor Stinner99c8b162011-05-24 12:05:19 +02003769 bytes = PyBytes_FromStringAndSize(NULL, len);
3770 if (bytes == NULL)
3771 return NULL;
3772 if (pseudo) {
3773 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3774 if (ok == 0 || ok == 1)
3775 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3776 }
3777 else {
3778 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3779 if (ok == 1)
3780 return bytes;
3781 }
3782 Py_DECREF(bytes);
3783
3784 err = ERR_get_error();
3785 errstr = ERR_reason_error_string(err);
3786 v = Py_BuildValue("(ks)", err, errstr);
3787 if (v != NULL) {
3788 PyErr_SetObject(PySSLErrorObject, v);
3789 Py_DECREF(v);
3790 }
3791 return NULL;
3792}
3793
3794static PyObject *
3795PySSL_RAND_bytes(PyObject *self, PyObject *args)
3796{
3797 int len;
3798 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3799 return NULL;
3800 return PySSL_RAND(len, 0);
3801}
3802
3803PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3804"RAND_bytes(n) -> bytes\n\
3805\n\
3806Generate n cryptographically strong pseudo-random bytes.");
3807
3808static PyObject *
3809PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3810{
3811 int len;
3812 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3813 return NULL;
3814 return PySSL_RAND(len, 1);
3815}
3816
3817PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3818"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3819\n\
3820Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3821generated are cryptographically strong.");
3822
3823static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003824PySSL_RAND_status(PyObject *self)
3825{
Christian Heimes217cfd12007-12-02 14:31:20 +00003826 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003827}
3828
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003829PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003830"RAND_status() -> 0 or 1\n\
3831\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003832Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3833It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3834using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003835
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003836#ifdef HAVE_RAND_EGD
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003837static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003838PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003839{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003840 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003841 int bytes;
3842
Jesus Ceac8754a12012-09-11 02:00:58 +02003843 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003844 PyUnicode_FSConverter, &path))
3845 return NULL;
3846
3847 bytes = RAND_egd(PyBytes_AsString(path));
3848 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003849 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003850 PyErr_SetString(PySSLErrorObject,
3851 "EGD connection failed or EGD did not return "
3852 "enough data to seed the PRNG");
3853 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003854 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003855 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003856}
3857
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003858PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003859"RAND_egd(path) -> bytes\n\
3860\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003861Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3862Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003863fails or if it does not provide enough data to seed PRNG.");
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003864#endif /* HAVE_RAND_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003865
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003866
Christian Heimes6d7ad132013-06-09 18:02:55 +02003867PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3868"get_default_verify_paths() -> tuple\n\
3869\n\
3870Return search paths and environment vars that are used by SSLContext's\n\
3871set_default_verify_paths() to load default CAs. The values are\n\
3872'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3873
3874static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003875PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003876{
3877 PyObject *ofile_env = NULL;
3878 PyObject *ofile = NULL;
3879 PyObject *odir_env = NULL;
3880 PyObject *odir = NULL;
3881
3882#define convert(info, target) { \
3883 const char *tmp = (info); \
3884 target = NULL; \
3885 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3886 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3887 target = PyBytes_FromString(tmp); } \
3888 if (!target) goto error; \
3889 } while(0)
3890
3891 convert(X509_get_default_cert_file_env(), ofile_env);
3892 convert(X509_get_default_cert_file(), ofile);
3893 convert(X509_get_default_cert_dir_env(), odir_env);
3894 convert(X509_get_default_cert_dir(), odir);
3895#undef convert
3896
Christian Heimes200bb1b2013-06-14 15:14:29 +02003897 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003898
3899 error:
3900 Py_XDECREF(ofile_env);
3901 Py_XDECREF(ofile);
3902 Py_XDECREF(odir_env);
3903 Py_XDECREF(odir);
3904 return NULL;
3905}
3906
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003907static PyObject*
3908asn1obj2py(ASN1_OBJECT *obj)
3909{
3910 int nid;
3911 const char *ln, *sn;
3912 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02003913 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003914
3915 nid = OBJ_obj2nid(obj);
3916 if (nid == NID_undef) {
3917 PyErr_Format(PyExc_ValueError, "Unknown object");
3918 return NULL;
3919 }
3920 sn = OBJ_nid2sn(nid);
3921 ln = OBJ_nid2ln(nid);
3922 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3923 if (buflen < 0) {
3924 _setSSLError(NULL, 0, __FILE__, __LINE__);
3925 return NULL;
3926 }
3927 if (buflen) {
3928 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3929 } else {
3930 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3931 }
3932}
3933
3934PyDoc_STRVAR(PySSL_txt2obj_doc,
3935"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3936\n\
3937Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3938objects are looked up by OID. With name=True short and long name are also\n\
3939matched.");
3940
3941static PyObject*
3942PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3943{
3944 char *kwlist[] = {"txt", "name", NULL};
3945 PyObject *result = NULL;
3946 char *txt;
3947 int name = 0;
3948 ASN1_OBJECT *obj;
3949
3950 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3951 kwlist, &txt, &name)) {
3952 return NULL;
3953 }
3954 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3955 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003956 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003957 return NULL;
3958 }
3959 result = asn1obj2py(obj);
3960 ASN1_OBJECT_free(obj);
3961 return result;
3962}
3963
3964PyDoc_STRVAR(PySSL_nid2obj_doc,
3965"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3966\n\
3967Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3968
3969static PyObject*
3970PySSL_nid2obj(PyObject *self, PyObject *args)
3971{
3972 PyObject *result = NULL;
3973 int nid;
3974 ASN1_OBJECT *obj;
3975
3976 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3977 return NULL;
3978 }
3979 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003980 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003981 return NULL;
3982 }
3983 obj = OBJ_nid2obj(nid);
3984 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003985 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003986 return NULL;
3987 }
3988 result = asn1obj2py(obj);
3989 ASN1_OBJECT_free(obj);
3990 return result;
3991}
3992
Christian Heimes46bebee2013-06-09 19:03:31 +02003993#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003994
3995static PyObject*
3996certEncodingType(DWORD encodingType)
3997{
3998 static PyObject *x509_asn = NULL;
3999 static PyObject *pkcs_7_asn = NULL;
4000
4001 if (x509_asn == NULL) {
4002 x509_asn = PyUnicode_InternFromString("x509_asn");
4003 if (x509_asn == NULL)
4004 return NULL;
4005 }
4006 if (pkcs_7_asn == NULL) {
4007 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4008 if (pkcs_7_asn == NULL)
4009 return NULL;
4010 }
4011 switch(encodingType) {
4012 case X509_ASN_ENCODING:
4013 Py_INCREF(x509_asn);
4014 return x509_asn;
4015 case PKCS_7_ASN_ENCODING:
4016 Py_INCREF(pkcs_7_asn);
4017 return pkcs_7_asn;
4018 default:
4019 return PyLong_FromLong(encodingType);
4020 }
4021}
4022
4023static PyObject*
4024parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4025{
4026 CERT_ENHKEY_USAGE *usage;
4027 DWORD size, error, i;
4028 PyObject *retval;
4029
4030 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4031 error = GetLastError();
4032 if (error == CRYPT_E_NOT_FOUND) {
4033 Py_RETURN_TRUE;
4034 }
4035 return PyErr_SetFromWindowsErr(error);
4036 }
4037
4038 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4039 if (usage == NULL) {
4040 return PyErr_NoMemory();
4041 }
4042
4043 /* Now get the actual enhanced usage property */
4044 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4045 PyMem_Free(usage);
4046 error = GetLastError();
4047 if (error == CRYPT_E_NOT_FOUND) {
4048 Py_RETURN_TRUE;
4049 }
4050 return PyErr_SetFromWindowsErr(error);
4051 }
4052 retval = PySet_New(NULL);
4053 if (retval == NULL) {
4054 goto error;
4055 }
4056 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4057 if (usage->rgpszUsageIdentifier[i]) {
4058 PyObject *oid;
4059 int err;
4060 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4061 if (oid == NULL) {
4062 Py_CLEAR(retval);
4063 goto error;
4064 }
4065 err = PySet_Add(retval, oid);
4066 Py_DECREF(oid);
4067 if (err == -1) {
4068 Py_CLEAR(retval);
4069 goto error;
4070 }
4071 }
4072 }
4073 error:
4074 PyMem_Free(usage);
4075 return retval;
4076}
4077
4078PyDoc_STRVAR(PySSL_enum_certificates_doc,
4079"enum_certificates(store_name) -> []\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02004080\n\
4081Retrieve certificates from Windows' cert store. store_name may be one of\n\
4082'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
Christian Heimes44109d72013-11-22 01:51:30 +01004083The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02004084encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
Christian Heimes44109d72013-11-22 01:51:30 +01004085PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
4086boolean True.");
Bill Janssen40a0f662008-08-12 16:56:25 +00004087
Christian Heimes46bebee2013-06-09 19:03:31 +02004088static PyObject *
Christian Heimes44109d72013-11-22 01:51:30 +01004089PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes46bebee2013-06-09 19:03:31 +02004090{
Christian Heimes44109d72013-11-22 01:51:30 +01004091 char *kwlist[] = {"store_name", NULL};
Christian Heimes46bebee2013-06-09 19:03:31 +02004092 char *store_name;
Christian Heimes46bebee2013-06-09 19:03:31 +02004093 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004094 PCCERT_CONTEXT pCertCtx = NULL;
4095 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004096 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004097
Benjamin Peterson43b84272015-04-06 13:05:22 -04004098 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_certificates",
Christian Heimes44109d72013-11-22 01:51:30 +01004099 kwlist, &store_name)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004100 return NULL;
4101 }
Christian Heimes44109d72013-11-22 01:51:30 +01004102 result = PyList_New(0);
4103 if (result == NULL) {
4104 return NULL;
4105 }
4106 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4107 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004108 Py_DECREF(result);
4109 return PyErr_SetFromWindowsErr(GetLastError());
4110 }
4111
Christian Heimes44109d72013-11-22 01:51:30 +01004112 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4113 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4114 pCertCtx->cbCertEncoded);
4115 if (!cert) {
4116 Py_CLEAR(result);
4117 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004118 }
Christian Heimes44109d72013-11-22 01:51:30 +01004119 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4120 Py_CLEAR(result);
4121 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004122 }
Christian Heimes44109d72013-11-22 01:51:30 +01004123 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4124 if (keyusage == Py_True) {
4125 Py_DECREF(keyusage);
4126 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004127 }
Christian Heimes44109d72013-11-22 01:51:30 +01004128 if (keyusage == NULL) {
4129 Py_CLEAR(result);
4130 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004131 }
Christian Heimes44109d72013-11-22 01:51:30 +01004132 if ((tup = PyTuple_New(3)) == NULL) {
4133 Py_CLEAR(result);
4134 break;
4135 }
4136 PyTuple_SET_ITEM(tup, 0, cert);
4137 cert = NULL;
4138 PyTuple_SET_ITEM(tup, 1, enc);
4139 enc = NULL;
4140 PyTuple_SET_ITEM(tup, 2, keyusage);
4141 keyusage = NULL;
4142 if (PyList_Append(result, tup) < 0) {
4143 Py_CLEAR(result);
4144 break;
4145 }
4146 Py_CLEAR(tup);
4147 }
4148 if (pCertCtx) {
4149 /* loop ended with an error, need to clean up context manually */
4150 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004151 }
4152
4153 /* In error cases cert, enc and tup may not be NULL */
4154 Py_XDECREF(cert);
4155 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004156 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004157 Py_XDECREF(tup);
4158
4159 if (!CertCloseStore(hStore, 0)) {
4160 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004161 Py_XDECREF(result);
4162 return PyErr_SetFromWindowsErr(GetLastError());
4163 }
4164 return result;
4165}
4166
4167PyDoc_STRVAR(PySSL_enum_crls_doc,
4168"enum_crls(store_name) -> []\n\
4169\n\
4170Retrieve CRLs from Windows' cert store. store_name may be one of\n\
4171'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
4172The function returns a list of (bytes, encoding_type) tuples. The\n\
4173encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
4174PKCS_7_ASN_ENCODING.");
4175
4176static PyObject *
4177PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
4178{
4179 char *kwlist[] = {"store_name", NULL};
4180 char *store_name;
4181 HCERTSTORE hStore = NULL;
4182 PCCRL_CONTEXT pCrlCtx = NULL;
4183 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4184 PyObject *result = NULL;
4185
Benjamin Peterson43b84272015-04-06 13:05:22 -04004186 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:enum_crls",
Christian Heimes44109d72013-11-22 01:51:30 +01004187 kwlist, &store_name)) {
4188 return NULL;
4189 }
4190 result = PyList_New(0);
4191 if (result == NULL) {
4192 return NULL;
4193 }
4194 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4195 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004196 Py_DECREF(result);
4197 return PyErr_SetFromWindowsErr(GetLastError());
4198 }
Christian Heimes44109d72013-11-22 01:51:30 +01004199
4200 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4201 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4202 pCrlCtx->cbCrlEncoded);
4203 if (!crl) {
4204 Py_CLEAR(result);
4205 break;
4206 }
4207 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4208 Py_CLEAR(result);
4209 break;
4210 }
4211 if ((tup = PyTuple_New(2)) == NULL) {
4212 Py_CLEAR(result);
4213 break;
4214 }
4215 PyTuple_SET_ITEM(tup, 0, crl);
4216 crl = NULL;
4217 PyTuple_SET_ITEM(tup, 1, enc);
4218 enc = NULL;
4219
4220 if (PyList_Append(result, tup) < 0) {
4221 Py_CLEAR(result);
4222 break;
4223 }
4224 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004225 }
Christian Heimes44109d72013-11-22 01:51:30 +01004226 if (pCrlCtx) {
4227 /* loop ended with an error, need to clean up context manually */
4228 CertFreeCRLContext(pCrlCtx);
4229 }
4230
4231 /* In error cases cert, enc and tup may not be NULL */
4232 Py_XDECREF(crl);
4233 Py_XDECREF(enc);
4234 Py_XDECREF(tup);
4235
4236 if (!CertCloseStore(hStore, 0)) {
4237 /* This error case might shadow another exception.*/
4238 Py_XDECREF(result);
4239 return PyErr_SetFromWindowsErr(GetLastError());
4240 }
4241 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004242}
Christian Heimes44109d72013-11-22 01:51:30 +01004243
4244#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004245
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004246/* List of functions exported by this module. */
4247
4248static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004249 {"_test_decode_cert", PySSL_test_decode_certificate,
4250 METH_VARARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004251 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
4252 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02004253 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
4254 PySSL_RAND_bytes_doc},
4255 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
4256 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerbeeb5122014-11-28 13:28:25 +01004257#ifdef HAVE_RAND_EGD
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004258 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004259 PySSL_RAND_egd_doc},
Victor Stinnerbeeb5122014-11-28 13:28:25 +01004260#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004261 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
4262 PySSL_RAND_status_doc},
Christian Heimes200bb1b2013-06-14 15:14:29 +02004263 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02004264 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02004265#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004266 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
4267 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
4268 {"enum_crls", (PyCFunction)PySSL_enum_crls,
4269 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02004270#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004271 {"txt2obj", (PyCFunction)PySSL_txt2obj,
4272 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
4273 {"nid2obj", (PyCFunction)PySSL_nid2obj,
4274 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004275 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004276};
4277
4278
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004279#ifdef WITH_THREAD
4280
4281/* an implementation of OpenSSL threading operations in terms
4282 of the Python C thread library */
4283
4284static PyThread_type_lock *_ssl_locks = NULL;
4285
Christian Heimes4d98ca92013-08-19 17:36:29 +02004286#if OPENSSL_VERSION_NUMBER >= 0x10000000
4287/* use new CRYPTO_THREADID API. */
4288static void
4289_ssl_threadid_callback(CRYPTO_THREADID *id)
4290{
4291 CRYPTO_THREADID_set_numeric(id,
4292 (unsigned long)PyThread_get_thread_ident());
4293}
4294#else
4295/* deprecated CRYPTO_set_id_callback() API. */
4296static unsigned long
4297_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004298 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004299}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004300#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004301
Bill Janssen6e027db2007-11-15 22:23:56 +00004302static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004303 (int mode, int n, const char *file, int line) {
4304 /* this function is needed to perform locking on shared data
4305 structures. (Note that OpenSSL uses a number of global data
4306 structures that will be implicitly shared whenever multiple
4307 threads use OpenSSL.) Multi-threaded applications will
4308 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004309
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004310 locking_function() must be able to handle up to
4311 CRYPTO_num_locks() different mutex locks. It sets the n-th
4312 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004313
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004314 file and line are the file number of the function setting the
4315 lock. They can be useful for debugging.
4316 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004317
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004318 if ((_ssl_locks == NULL) ||
4319 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4320 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004321
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004322 if (mode & CRYPTO_LOCK) {
4323 PyThread_acquire_lock(_ssl_locks[n], 1);
4324 } else {
4325 PyThread_release_lock(_ssl_locks[n]);
4326 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004327}
4328
4329static int _setup_ssl_threads(void) {
4330
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004331 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004332
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004333 if (_ssl_locks == NULL) {
4334 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004335 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4336 if (_ssl_locks == NULL) {
4337 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004338 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004339 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004340 memset(_ssl_locks, 0,
4341 sizeof(PyThread_type_lock) * _ssl_locks_count);
4342 for (i = 0; i < _ssl_locks_count; i++) {
4343 _ssl_locks[i] = PyThread_allocate_lock();
4344 if (_ssl_locks[i] == NULL) {
4345 unsigned int j;
4346 for (j = 0; j < i; j++) {
4347 PyThread_free_lock(_ssl_locks[j]);
4348 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004349 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004350 return 0;
4351 }
4352 }
4353 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004354#if OPENSSL_VERSION_NUMBER >= 0x10000000
4355 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4356#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004357 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004358#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004359 }
4360 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004361}
4362
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004363#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004364
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004365PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004366"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004367for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004368
Martin v. Löwis1a214512008-06-11 05:26:20 +00004369
4370static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004371 PyModuleDef_HEAD_INIT,
4372 "_ssl",
4373 module_doc,
4374 -1,
4375 PySSL_methods,
4376 NULL,
4377 NULL,
4378 NULL,
4379 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004380};
4381
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004382
4383static void
4384parse_openssl_version(unsigned long libver,
4385 unsigned int *major, unsigned int *minor,
4386 unsigned int *fix, unsigned int *patch,
4387 unsigned int *status)
4388{
4389 *status = libver & 0xF;
4390 libver >>= 4;
4391 *patch = libver & 0xFF;
4392 libver >>= 8;
4393 *fix = libver & 0xFF;
4394 libver >>= 8;
4395 *minor = libver & 0xFF;
4396 libver >>= 8;
4397 *major = libver & 0xFF;
4398}
4399
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004400PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004401PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004402{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004403 PyObject *m, *d, *r;
4404 unsigned long libver;
4405 unsigned int major, minor, fix, patch, status;
4406 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004407 struct py_ssl_error_code *errcode;
4408 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004409
Antoine Pitrou152efa22010-05-16 18:19:27 +00004410 if (PyType_Ready(&PySSLContext_Type) < 0)
4411 return NULL;
4412 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004413 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004414 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4415 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004416
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004417 m = PyModule_Create(&_sslmodule);
4418 if (m == NULL)
4419 return NULL;
4420 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004421
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004422 /* Load _socket module and its C API */
4423 socket_api = PySocketModule_ImportModuleAndAPI();
4424 if (!socket_api)
4425 return NULL;
4426 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004427
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004428 /* Init OpenSSL */
4429 SSL_load_error_strings();
4430 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004431#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004432 /* note that this will start threading if not already started */
4433 if (!_setup_ssl_threads()) {
4434 return NULL;
4435 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004436#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004437 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004438
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004439 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004440 sslerror_type_slots[0].pfunc = PyExc_OSError;
4441 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004442 if (PySSLErrorObject == NULL)
4443 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004444
Antoine Pitrou41032a62011-10-27 23:56:55 +02004445 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4446 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4447 PySSLErrorObject, NULL);
4448 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4449 "ssl.SSLWantReadError", SSLWantReadError_doc,
4450 PySSLErrorObject, NULL);
4451 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4452 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4453 PySSLErrorObject, NULL);
4454 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4455 "ssl.SSLSyscallError", SSLSyscallError_doc,
4456 PySSLErrorObject, NULL);
4457 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4458 "ssl.SSLEOFError", SSLEOFError_doc,
4459 PySSLErrorObject, NULL);
4460 if (PySSLZeroReturnErrorObject == NULL
4461 || PySSLWantReadErrorObject == NULL
4462 || PySSLWantWriteErrorObject == NULL
4463 || PySSLSyscallErrorObject == NULL
4464 || PySSLEOFErrorObject == NULL)
4465 return NULL;
4466 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4467 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4468 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4469 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4470 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4471 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004472 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004473 if (PyDict_SetItemString(d, "_SSLContext",
4474 (PyObject *)&PySSLContext_Type) != 0)
4475 return NULL;
4476 if (PyDict_SetItemString(d, "_SSLSocket",
4477 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004478 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004479 if (PyDict_SetItemString(d, "MemoryBIO",
4480 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4481 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004482 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4483 PY_SSL_ERROR_ZERO_RETURN);
4484 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4485 PY_SSL_ERROR_WANT_READ);
4486 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4487 PY_SSL_ERROR_WANT_WRITE);
4488 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4489 PY_SSL_ERROR_WANT_X509_LOOKUP);
4490 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4491 PY_SSL_ERROR_SYSCALL);
4492 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4493 PY_SSL_ERROR_SSL);
4494 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4495 PY_SSL_ERROR_WANT_CONNECT);
4496 /* non ssl.h errorcodes */
4497 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4498 PY_SSL_ERROR_EOF);
4499 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4500 PY_SSL_ERROR_INVALID_ERROR_CODE);
4501 /* cert requirements */
4502 PyModule_AddIntConstant(m, "CERT_NONE",
4503 PY_SSL_CERT_NONE);
4504 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4505 PY_SSL_CERT_OPTIONAL);
4506 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4507 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004508 /* CRL verification for verification_flags */
4509 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4510 0);
4511 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4512 X509_V_FLAG_CRL_CHECK);
4513 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4514 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4515 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4516 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05004517#ifdef X509_V_FLAG_TRUSTED_FIRST
4518 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4519 X509_V_FLAG_TRUSTED_FIRST);
4520#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004521
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004522 /* Alert Descriptions from ssl.h */
4523 /* note RESERVED constants no longer intended for use have been removed */
4524 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4525
4526#define ADD_AD_CONSTANT(s) \
4527 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4528 SSL_AD_##s)
4529
4530 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4531 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4532 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4533 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4534 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4535 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4536 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4537 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4538 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4539 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4540 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4541 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4542 ADD_AD_CONSTANT(UNKNOWN_CA);
4543 ADD_AD_CONSTANT(ACCESS_DENIED);
4544 ADD_AD_CONSTANT(DECODE_ERROR);
4545 ADD_AD_CONSTANT(DECRYPT_ERROR);
4546 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4547 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4548 ADD_AD_CONSTANT(INTERNAL_ERROR);
4549 ADD_AD_CONSTANT(USER_CANCELLED);
4550 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004551 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004552#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4553 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4554#endif
4555#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4556 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4557#endif
4558#ifdef SSL_AD_UNRECOGNIZED_NAME
4559 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4560#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004561#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4562 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4563#endif
4564#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4565 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4566#endif
4567#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4568 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4569#endif
4570
4571#undef ADD_AD_CONSTANT
4572
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004573 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004574#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004575 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4576 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004577#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004578#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004579 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4580 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004581#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004582 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4583 PY_SSL_VERSION_SSL23);
4584 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4585 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004586#if HAVE_TLSv1_2
4587 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4588 PY_SSL_VERSION_TLS1_1);
4589 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4590 PY_SSL_VERSION_TLS1_2);
4591#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004592
Antoine Pitroub5218772010-05-21 09:56:06 +00004593 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004594 PyModule_AddIntConstant(m, "OP_ALL",
4595 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004596 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4597 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4598 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004599#if HAVE_TLSv1_2
4600 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4601 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4602#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004603 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4604 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004605 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004606#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004607 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004608#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004609#ifdef SSL_OP_NO_COMPRESSION
4610 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4611 SSL_OP_NO_COMPRESSION);
4612#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004613
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004614#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004615 r = Py_True;
4616#else
4617 r = Py_False;
4618#endif
4619 Py_INCREF(r);
4620 PyModule_AddObject(m, "HAS_SNI", r);
4621
Antoine Pitroud6494802011-07-21 01:11:30 +02004622 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004623 Py_INCREF(r);
4624 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4625
Antoine Pitrou501da612011-12-21 09:27:41 +01004626#ifdef OPENSSL_NO_ECDH
4627 r = Py_False;
4628#else
4629 r = Py_True;
4630#endif
4631 Py_INCREF(r);
4632 PyModule_AddObject(m, "HAS_ECDH", r);
4633
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004634#ifdef OPENSSL_NPN_NEGOTIATED
4635 r = Py_True;
4636#else
4637 r = Py_False;
4638#endif
4639 Py_INCREF(r);
4640 PyModule_AddObject(m, "HAS_NPN", r);
4641
Benjamin Petersoncca27322015-01-23 16:35:37 -05004642#ifdef HAVE_ALPN
4643 r = Py_True;
4644#else
4645 r = Py_False;
4646#endif
4647 Py_INCREF(r);
4648 PyModule_AddObject(m, "HAS_ALPN", r);
4649
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004650 /* Mappings for error codes */
4651 err_codes_to_names = PyDict_New();
4652 err_names_to_codes = PyDict_New();
4653 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4654 return NULL;
4655 errcode = error_codes;
4656 while (errcode->mnemonic != NULL) {
4657 PyObject *mnemo, *key;
4658 mnemo = PyUnicode_FromString(errcode->mnemonic);
4659 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4660 if (mnemo == NULL || key == NULL)
4661 return NULL;
4662 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4663 return NULL;
4664 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4665 return NULL;
4666 Py_DECREF(key);
4667 Py_DECREF(mnemo);
4668 errcode++;
4669 }
4670 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4671 return NULL;
4672 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4673 return NULL;
4674
4675 lib_codes_to_names = PyDict_New();
4676 if (lib_codes_to_names == NULL)
4677 return NULL;
4678 libcode = library_codes;
4679 while (libcode->library != NULL) {
4680 PyObject *mnemo, *key;
4681 key = PyLong_FromLong(libcode->code);
4682 mnemo = PyUnicode_FromString(libcode->library);
4683 if (key == NULL || mnemo == NULL)
4684 return NULL;
4685 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4686 return NULL;
4687 Py_DECREF(key);
4688 Py_DECREF(mnemo);
4689 libcode++;
4690 }
4691 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4692 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004693
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004694 /* OpenSSL version */
4695 /* SSLeay() gives us the version of the library linked against,
4696 which could be different from the headers version.
4697 */
4698 libver = SSLeay();
4699 r = PyLong_FromUnsignedLong(libver);
4700 if (r == NULL)
4701 return NULL;
4702 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4703 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004704 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004705 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4706 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4707 return NULL;
4708 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4709 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4710 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004711
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004712 libver = OPENSSL_VERSION_NUMBER;
4713 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4714 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4715 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4716 return NULL;
4717
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004718 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004719}