blob: 217c77c5933d3f29dc0a36d76452568b6c795c66 [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);
Thomas Woutersed03b412007-08-28 21:37:11 +0000226static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000227 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000228static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
229static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000230
Antoine Pitrou152efa22010-05-16 18:19:27 +0000231#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
232#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200233#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000234
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000235typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000236 SOCKET_IS_NONBLOCKING,
237 SOCKET_IS_BLOCKING,
238 SOCKET_HAS_TIMED_OUT,
239 SOCKET_HAS_BEEN_CLOSED,
240 SOCKET_TOO_LARGE_FOR_SELECT,
241 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000242} timeout_state;
243
Thomas Woutersed03b412007-08-28 21:37:11 +0000244/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000245#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200246#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000247
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200248/* Get the socket from a PySSLSocket, if it has one */
249#define GET_SOCKET(obj) ((obj)->Socket ? \
250 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200251
252/*
253 * SSL errors.
254 */
255
256PyDoc_STRVAR(SSLError_doc,
257"An error occurred in the SSL implementation.");
258
259PyDoc_STRVAR(SSLZeroReturnError_doc,
260"SSL/TLS session closed cleanly.");
261
262PyDoc_STRVAR(SSLWantReadError_doc,
263"Non-blocking SSL socket needs to read more data\n"
264"before the requested operation can be completed.");
265
266PyDoc_STRVAR(SSLWantWriteError_doc,
267"Non-blocking SSL socket needs to write more data\n"
268"before the requested operation can be completed.");
269
270PyDoc_STRVAR(SSLSyscallError_doc,
271"System error when attempting SSL operation.");
272
273PyDoc_STRVAR(SSLEOFError_doc,
274"SSL/TLS connection terminated abruptly.");
275
276static PyObject *
277SSLError_str(PyOSErrorObject *self)
278{
279 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
280 Py_INCREF(self->strerror);
281 return self->strerror;
282 }
283 else
284 return PyObject_Str(self->args);
285}
286
287static PyType_Slot sslerror_type_slots[] = {
288 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
289 {Py_tp_doc, SSLError_doc},
290 {Py_tp_str, SSLError_str},
291 {0, 0},
292};
293
294static PyType_Spec sslerror_type_spec = {
295 "ssl.SSLError",
296 sizeof(PyOSErrorObject),
297 0,
298 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
299 sslerror_type_slots
300};
301
302static void
303fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
304 int lineno, unsigned long errcode)
305{
306 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
307 PyObject *init_value, *msg, *key;
308 _Py_IDENTIFIER(reason);
309 _Py_IDENTIFIER(library);
310
311 if (errcode != 0) {
312 int lib, reason;
313
314 lib = ERR_GET_LIB(errcode);
315 reason = ERR_GET_REASON(errcode);
316 key = Py_BuildValue("ii", lib, reason);
317 if (key == NULL)
318 goto fail;
319 reason_obj = PyDict_GetItem(err_codes_to_names, key);
320 Py_DECREF(key);
321 if (reason_obj == NULL) {
322 /* XXX if reason < 100, it might reflect a library number (!!) */
323 PyErr_Clear();
324 }
325 key = PyLong_FromLong(lib);
326 if (key == NULL)
327 goto fail;
328 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
329 Py_DECREF(key);
330 if (lib_obj == NULL) {
331 PyErr_Clear();
332 }
333 if (errstr == NULL)
334 errstr = ERR_reason_error_string(errcode);
335 }
336 if (errstr == NULL)
337 errstr = "unknown error";
338
339 if (reason_obj && lib_obj)
340 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
341 lib_obj, reason_obj, errstr, lineno);
342 else if (lib_obj)
343 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
344 lib_obj, errstr, lineno);
345 else
346 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200347 if (msg == NULL)
348 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100349
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200350 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100351 if (init_value == NULL)
352 goto fail;
353
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200354 err_value = PyObject_CallObject(type, init_value);
355 Py_DECREF(init_value);
356 if (err_value == NULL)
357 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100358
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200359 if (reason_obj == NULL)
360 reason_obj = Py_None;
361 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
362 goto fail;
363 if (lib_obj == NULL)
364 lib_obj = Py_None;
365 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
366 goto fail;
367 PyErr_SetObject(type, err_value);
368fail:
369 Py_XDECREF(err_value);
370}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000371
372static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000373PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000374{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200375 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200376 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000377 int err;
378 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200379 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000380
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000381 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200382 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000383
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000384 if (obj->ssl != NULL) {
385 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000386
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000387 switch (err) {
388 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200389 errstr = "TLS/SSL connection has been closed (EOF)";
390 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000391 p = PY_SSL_ERROR_ZERO_RETURN;
392 break;
393 case SSL_ERROR_WANT_READ:
394 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200395 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000396 p = PY_SSL_ERROR_WANT_READ;
397 break;
398 case SSL_ERROR_WANT_WRITE:
399 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200400 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000401 errstr = "The operation did not complete (write)";
402 break;
403 case SSL_ERROR_WANT_X509_LOOKUP:
404 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000405 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000406 break;
407 case SSL_ERROR_WANT_CONNECT:
408 p = PY_SSL_ERROR_WANT_CONNECT;
409 errstr = "The operation did not complete (connect)";
410 break;
411 case SSL_ERROR_SYSCALL:
412 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000413 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200414 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000415 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000416 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200417 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000418 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200419 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000420 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000421 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000422 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200423 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000424 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200425 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000426 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000427 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200428 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000429 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000430 }
431 } else {
432 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000433 }
434 break;
435 }
436 case SSL_ERROR_SSL:
437 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000438 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200439 if (e == 0)
440 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000441 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000442 break;
443 }
444 default:
445 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
446 errstr = "Invalid error code";
447 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000448 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200449 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000450 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000451 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000452}
453
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000454static PyObject *
455_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
456
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200457 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000458 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200459 else
460 errcode = 0;
461 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000462 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000463 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000464}
465
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200466/*
467 * SSL objects
468 */
469
Antoine Pitrou152efa22010-05-16 18:19:27 +0000470static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100471newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000472 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200473 char *server_hostname,
474 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000475{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000476 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100477 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200478 PyObject *hostname;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200479 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000480
Antoine Pitrou152efa22010-05-16 18:19:27 +0000481 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000482 if (self == NULL)
483 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000484
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000485 self->peer_cert = NULL;
486 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000487 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100488 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200489 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200490 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200491 self->owner = NULL;
492 if (server_hostname != NULL) {
493 hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
494 "idna", "strict");
495 if (hostname == NULL) {
496 Py_DECREF(self);
497 return NULL;
498 }
499 self->server_hostname = hostname;
500 } else
501 self->server_hostname = NULL;
502
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100503 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000504
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000505 /* Make sure the SSL error state is initialized */
506 (void) ERR_get_state();
507 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000508
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000509 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000510 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000511 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200512 SSL_set_app_data(self->ssl, self);
513 if (sock) {
514 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
515 } else {
516 /* BIOs are reference counted and SSL_set_bio borrows our reference.
517 * To prevent a double free in memory_bio_dealloc() we need to take an
518 * extra reference here. */
519 CRYPTO_add(&inbio->bio->references, 1, CRYPTO_LOCK_BIO);
520 CRYPTO_add(&outbio->bio->references, 1, CRYPTO_LOCK_BIO);
521 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
522 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200523 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000524#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200525 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000526#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200527 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000528
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100529#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000530 if (server_hostname != NULL)
531 SSL_set_tlsext_host_name(self->ssl, server_hostname);
532#endif
533
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000534 /* If the socket is in non-blocking mode or timeout mode, set the BIO
535 * to non-blocking mode (blocking is the default)
536 */
Victor Stinnere2452312015-03-28 03:00:46 +0100537 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000538 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
539 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
540 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000541
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000542 PySSL_BEGIN_ALLOW_THREADS
543 if (socket_type == PY_SSL_CLIENT)
544 SSL_set_connect_state(self->ssl);
545 else
546 SSL_set_accept_state(self->ssl);
547 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000548
Antoine Pitroud6494802011-07-21 01:11:30 +0200549 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200550 if (sock != NULL) {
551 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
552 if (self->Socket == NULL) {
553 Py_DECREF(self);
554 Py_XDECREF(self->server_hostname);
555 return NULL;
556 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100557 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000558 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000559}
560
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000561/* SSL object methods */
562
Antoine Pitrou152efa22010-05-16 18:19:27 +0000563static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000564{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000565 int ret;
566 int err;
567 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200568 PySocketSockObject *sock = GET_SOCKET(self);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000569
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200570 if (sock) {
571 if (((PyObject*)sock) == Py_None) {
572 _setSSLError("Underlying socket connection gone",
573 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
574 return NULL;
575 }
576 Py_INCREF(sock);
577
578 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100579 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200580 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
581 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000582 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000583
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000584 /* Actually negotiate SSL connection */
585 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000586 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000587 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000588 ret = SSL_do_handshake(self->ssl);
589 err = SSL_get_error(self->ssl, ret);
590 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000591 if (PyErr_CheckSignals())
592 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000593 if (err == SSL_ERROR_WANT_READ) {
594 sockstate = check_socket_and_wait_for_timeout(sock, 0);
595 } else if (err == SSL_ERROR_WANT_WRITE) {
596 sockstate = check_socket_and_wait_for_timeout(sock, 1);
597 } else {
598 sockstate = SOCKET_OPERATION_OK;
599 }
600 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000601 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000602 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000603 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000604 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
605 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000606 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000607 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000608 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
609 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000610 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000611 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000612 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
613 break;
614 }
615 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200616 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000617 if (ret < 1)
618 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000620 if (self->peer_cert)
621 X509_free (self->peer_cert);
622 PySSL_BEGIN_ALLOW_THREADS
623 self->peer_cert = SSL_get_peer_certificate(self->ssl);
624 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200625 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000626
627 Py_INCREF(Py_None);
628 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000629
630error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200631 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000632 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000633}
634
Thomas Woutersed03b412007-08-28 21:37:11 +0000635static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000636_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000637
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000638 char namebuf[X509_NAME_MAXLEN];
639 int buflen;
640 PyObject *name_obj;
641 PyObject *value_obj;
642 PyObject *attr;
643 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000644
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000645 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
646 if (buflen < 0) {
647 _setSSLError(NULL, 0, __FILE__, __LINE__);
648 goto fail;
649 }
650 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
651 if (name_obj == NULL)
652 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000653
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000654 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
655 if (buflen < 0) {
656 _setSSLError(NULL, 0, __FILE__, __LINE__);
657 Py_DECREF(name_obj);
658 goto fail;
659 }
660 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000661 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000662 OPENSSL_free(valuebuf);
663 if (value_obj == NULL) {
664 Py_DECREF(name_obj);
665 goto fail;
666 }
667 attr = PyTuple_New(2);
668 if (attr == NULL) {
669 Py_DECREF(name_obj);
670 Py_DECREF(value_obj);
671 goto fail;
672 }
673 PyTuple_SET_ITEM(attr, 0, name_obj);
674 PyTuple_SET_ITEM(attr, 1, value_obj);
675 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000676
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000677 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000678 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000679}
680
681static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000682_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000683{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000684 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
685 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
686 PyObject *rdnt;
687 PyObject *attr = NULL; /* tuple to hold an attribute */
688 int entry_count = X509_NAME_entry_count(xname);
689 X509_NAME_ENTRY *entry;
690 ASN1_OBJECT *name;
691 ASN1_STRING *value;
692 int index_counter;
693 int rdn_level = -1;
694 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000695
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000696 dn = PyList_New(0);
697 if (dn == NULL)
698 return NULL;
699 /* now create another tuple to hold the top-level RDN */
700 rdn = PyList_New(0);
701 if (rdn == NULL)
702 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000703
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000704 for (index_counter = 0;
705 index_counter < entry_count;
706 index_counter++)
707 {
708 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000709
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000710 /* check to see if we've gotten to a new RDN */
711 if (rdn_level >= 0) {
712 if (rdn_level != entry->set) {
713 /* yes, new RDN */
714 /* add old RDN to DN */
715 rdnt = PyList_AsTuple(rdn);
716 Py_DECREF(rdn);
717 if (rdnt == NULL)
718 goto fail0;
719 retcode = PyList_Append(dn, rdnt);
720 Py_DECREF(rdnt);
721 if (retcode < 0)
722 goto fail0;
723 /* create new RDN */
724 rdn = PyList_New(0);
725 if (rdn == NULL)
726 goto fail0;
727 }
728 }
729 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000730
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000731 /* now add this attribute to the current RDN */
732 name = X509_NAME_ENTRY_get_object(entry);
733 value = X509_NAME_ENTRY_get_data(entry);
734 attr = _create_tuple_for_attribute(name, value);
735 /*
736 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
737 entry->set,
738 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
739 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
740 */
741 if (attr == NULL)
742 goto fail1;
743 retcode = PyList_Append(rdn, attr);
744 Py_DECREF(attr);
745 if (retcode < 0)
746 goto fail1;
747 }
748 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100749 if (rdn != NULL) {
750 if (PyList_GET_SIZE(rdn) > 0) {
751 rdnt = PyList_AsTuple(rdn);
752 Py_DECREF(rdn);
753 if (rdnt == NULL)
754 goto fail0;
755 retcode = PyList_Append(dn, rdnt);
756 Py_DECREF(rdnt);
757 if (retcode < 0)
758 goto fail0;
759 }
760 else {
761 Py_DECREF(rdn);
762 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000763 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000764
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000765 /* convert list to tuple */
766 rdnt = PyList_AsTuple(dn);
767 Py_DECREF(dn);
768 if (rdnt == NULL)
769 return NULL;
770 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000771
772 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000773 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000774
775 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000776 Py_XDECREF(dn);
777 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000778}
779
780static PyObject *
781_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000782
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 /* this code follows the procedure outlined in
784 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
785 function to extract the STACK_OF(GENERAL_NAME),
786 then iterates through the stack to add the
787 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000788
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000789 int i, j;
790 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200791 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 X509_EXTENSION *ext = NULL;
793 GENERAL_NAMES *names = NULL;
794 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000795 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 BIO *biobuf = NULL;
797 char buf[2048];
798 char *vptr;
799 int len;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000800 const unsigned char *p;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000801
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000802 if (certificate == NULL)
803 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000804
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000805 /* get a memory buffer */
806 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200808 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000809 while ((i = X509_get_ext_by_NID(
810 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 if (peer_alt_names == Py_None) {
813 peer_alt_names = PyList_New(0);
814 if (peer_alt_names == NULL)
815 goto fail;
816 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000817
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000818 /* now decode the altName */
819 ext = X509_get_ext(certificate, i);
820 if(!(method = X509V3_EXT_get(ext))) {
821 PyErr_SetString
822 (PySSLErrorObject,
823 ERRSTR("No method for internalizing subjectAltName!"));
824 goto fail;
825 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000826
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000827 p = ext->value->data;
828 if (method->it)
829 names = (GENERAL_NAMES*)
830 (ASN1_item_d2i(NULL,
831 &p,
832 ext->value->length,
833 ASN1_ITEM_ptr(method->it)));
834 else
835 names = (GENERAL_NAMES*)
836 (method->d2i(NULL,
837 &p,
838 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000839
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000841 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200842 int gntype;
843 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000844
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000845 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200846 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200847 switch (gntype) {
848 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000849 /* we special-case DirName as a tuple of
850 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000851
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000852 t = PyTuple_New(2);
853 if (t == NULL) {
854 goto fail;
855 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000856
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000857 v = PyUnicode_FromString("DirName");
858 if (v == NULL) {
859 Py_DECREF(t);
860 goto fail;
861 }
862 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000863
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000864 v = _create_tuple_for_X509_NAME (name->d.dirn);
865 if (v == NULL) {
866 Py_DECREF(t);
867 goto fail;
868 }
869 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200870 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000871
Christian Heimes824f7f32013-08-17 00:54:47 +0200872 case GEN_EMAIL:
873 case GEN_DNS:
874 case GEN_URI:
875 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
876 correctly, CVE-2013-4238 */
877 t = PyTuple_New(2);
878 if (t == NULL)
879 goto fail;
880 switch (gntype) {
881 case GEN_EMAIL:
882 v = PyUnicode_FromString("email");
883 as = name->d.rfc822Name;
884 break;
885 case GEN_DNS:
886 v = PyUnicode_FromString("DNS");
887 as = name->d.dNSName;
888 break;
889 case GEN_URI:
890 v = PyUnicode_FromString("URI");
891 as = name->d.uniformResourceIdentifier;
892 break;
893 }
894 if (v == NULL) {
895 Py_DECREF(t);
896 goto fail;
897 }
898 PyTuple_SET_ITEM(t, 0, v);
899 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
900 ASN1_STRING_length(as));
901 if (v == NULL) {
902 Py_DECREF(t);
903 goto fail;
904 }
905 PyTuple_SET_ITEM(t, 1, v);
906 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000907
Christian Heimes824f7f32013-08-17 00:54:47 +0200908 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000909 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200910 switch (gntype) {
911 /* check for new general name type */
912 case GEN_OTHERNAME:
913 case GEN_X400:
914 case GEN_EDIPARTY:
915 case GEN_IPADD:
916 case GEN_RID:
917 break;
918 default:
919 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
920 "Unknown general name type %d",
921 gntype) == -1) {
922 goto fail;
923 }
924 break;
925 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000926 (void) BIO_reset(biobuf);
927 GENERAL_NAME_print(biobuf, name);
928 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
929 if (len < 0) {
930 _setSSLError(NULL, 0, __FILE__, __LINE__);
931 goto fail;
932 }
933 vptr = strchr(buf, ':');
934 if (vptr == NULL)
935 goto fail;
936 t = PyTuple_New(2);
937 if (t == NULL)
938 goto fail;
939 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
940 if (v == NULL) {
941 Py_DECREF(t);
942 goto fail;
943 }
944 PyTuple_SET_ITEM(t, 0, v);
945 v = PyUnicode_FromStringAndSize((vptr + 1),
946 (len - (vptr - buf + 1)));
947 if (v == NULL) {
948 Py_DECREF(t);
949 goto fail;
950 }
951 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200952 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000953 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000954
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000956
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 if (PyList_Append(peer_alt_names, t) < 0) {
958 Py_DECREF(t);
959 goto fail;
960 }
961 Py_DECREF(t);
962 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100963 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000964 }
965 BIO_free(biobuf);
966 if (peer_alt_names != Py_None) {
967 v = PyList_AsTuple(peer_alt_names);
968 Py_DECREF(peer_alt_names);
969 return v;
970 } else {
971 return peer_alt_names;
972 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000973
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000974
975 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000976 if (biobuf != NULL)
977 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000978
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000979 if (peer_alt_names != Py_None) {
980 Py_XDECREF(peer_alt_names);
981 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000982
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000983 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000984}
985
986static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +0100987_get_aia_uri(X509 *certificate, int nid) {
988 PyObject *lst = NULL, *ostr = NULL;
989 int i, result;
990 AUTHORITY_INFO_ACCESS *info;
991
992 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
993 if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
994 return Py_None;
995 }
996
997 if ((lst = PyList_New(0)) == NULL) {
998 goto fail;
999 }
1000
1001 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1002 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1003 ASN1_IA5STRING *uri;
1004
1005 if ((OBJ_obj2nid(ad->method) != nid) ||
1006 (ad->location->type != GEN_URI)) {
1007 continue;
1008 }
1009 uri = ad->location->d.uniformResourceIdentifier;
1010 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1011 uri->length);
1012 if (ostr == NULL) {
1013 goto fail;
1014 }
1015 result = PyList_Append(lst, ostr);
1016 Py_DECREF(ostr);
1017 if (result < 0) {
1018 goto fail;
1019 }
1020 }
1021 AUTHORITY_INFO_ACCESS_free(info);
1022
1023 /* convert to tuple or None */
1024 if (PyList_Size(lst) == 0) {
1025 Py_DECREF(lst);
1026 return Py_None;
1027 } else {
1028 PyObject *tup;
1029 tup = PyList_AsTuple(lst);
1030 Py_DECREF(lst);
1031 return tup;
1032 }
1033
1034 fail:
1035 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001036 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001037 return NULL;
1038}
1039
1040static PyObject *
1041_get_crl_dp(X509 *certificate) {
1042 STACK_OF(DIST_POINT) *dps;
1043 int i, j, result;
1044 PyObject *lst;
1045
Christian Heimes949ec142013-11-21 16:26:51 +01001046#if OPENSSL_VERSION_NUMBER < 0x10001000L
1047 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points,
1048 NULL, NULL);
1049#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001050 /* Calls x509v3_cache_extensions and sets up crldp */
1051 X509_check_ca(certificate);
1052 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001053#endif
1054
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001055 if (dps == NULL) {
1056 return Py_None;
1057 }
1058
1059 if ((lst = PyList_New(0)) == NULL) {
1060 return NULL;
1061 }
1062
1063 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1064 DIST_POINT *dp;
1065 STACK_OF(GENERAL_NAME) *gns;
1066
1067 dp = sk_DIST_POINT_value(dps, i);
1068 gns = dp->distpoint->name.fullname;
1069
1070 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1071 GENERAL_NAME *gn;
1072 ASN1_IA5STRING *uri;
1073 PyObject *ouri;
1074
1075 gn = sk_GENERAL_NAME_value(gns, j);
1076 if (gn->type != GEN_URI) {
1077 continue;
1078 }
1079 uri = gn->d.uniformResourceIdentifier;
1080 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1081 uri->length);
1082 if (ouri == NULL) {
1083 Py_DECREF(lst);
1084 return NULL;
1085 }
1086 result = PyList_Append(lst, ouri);
1087 Py_DECREF(ouri);
1088 if (result < 0) {
1089 Py_DECREF(lst);
1090 return NULL;
1091 }
1092 }
1093 }
1094 /* convert to tuple or None */
1095 if (PyList_Size(lst) == 0) {
1096 Py_DECREF(lst);
1097 return Py_None;
1098 } else {
1099 PyObject *tup;
1100 tup = PyList_AsTuple(lst);
1101 Py_DECREF(lst);
1102 return tup;
1103 }
1104}
1105
1106static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001107_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001108
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 PyObject *retval = NULL;
1110 BIO *biobuf = NULL;
1111 PyObject *peer;
1112 PyObject *peer_alt_names = NULL;
1113 PyObject *issuer;
1114 PyObject *version;
1115 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001116 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001117 ASN1_INTEGER *serialNumber;
1118 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001119 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 ASN1_TIME *notBefore, *notAfter;
1121 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001122
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001123 retval = PyDict_New();
1124 if (retval == NULL)
1125 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001126
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 peer = _create_tuple_for_X509_NAME(
1128 X509_get_subject_name(certificate));
1129 if (peer == NULL)
1130 goto fail0;
1131 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1132 Py_DECREF(peer);
1133 goto fail0;
1134 }
1135 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001136
Antoine Pitroufb046912010-11-09 20:21:19 +00001137 issuer = _create_tuple_for_X509_NAME(
1138 X509_get_issuer_name(certificate));
1139 if (issuer == NULL)
1140 goto fail0;
1141 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001142 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001143 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001144 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001145 Py_DECREF(issuer);
1146
1147 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001148 if (version == NULL)
1149 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001150 if (PyDict_SetItemString(retval, "version", version) < 0) {
1151 Py_DECREF(version);
1152 goto fail0;
1153 }
1154 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001155
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001156 /* get a memory buffer */
1157 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001158
Antoine Pitroufb046912010-11-09 20:21:19 +00001159 (void) BIO_reset(biobuf);
1160 serialNumber = X509_get_serialNumber(certificate);
1161 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1162 i2a_ASN1_INTEGER(biobuf, serialNumber);
1163 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1164 if (len < 0) {
1165 _setSSLError(NULL, 0, __FILE__, __LINE__);
1166 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001167 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001168 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1169 if (sn_obj == NULL)
1170 goto fail1;
1171 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1172 Py_DECREF(sn_obj);
1173 goto fail1;
1174 }
1175 Py_DECREF(sn_obj);
1176
1177 (void) BIO_reset(biobuf);
1178 notBefore = X509_get_notBefore(certificate);
1179 ASN1_TIME_print(biobuf, notBefore);
1180 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1181 if (len < 0) {
1182 _setSSLError(NULL, 0, __FILE__, __LINE__);
1183 goto fail1;
1184 }
1185 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1186 if (pnotBefore == NULL)
1187 goto fail1;
1188 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1189 Py_DECREF(pnotBefore);
1190 goto fail1;
1191 }
1192 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001193
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001194 (void) BIO_reset(biobuf);
1195 notAfter = X509_get_notAfter(certificate);
1196 ASN1_TIME_print(biobuf, notAfter);
1197 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1198 if (len < 0) {
1199 _setSSLError(NULL, 0, __FILE__, __LINE__);
1200 goto fail1;
1201 }
1202 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1203 if (pnotAfter == NULL)
1204 goto fail1;
1205 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1206 Py_DECREF(pnotAfter);
1207 goto fail1;
1208 }
1209 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001210
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001211 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001212
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001213 peer_alt_names = _get_peer_alt_names(certificate);
1214 if (peer_alt_names == NULL)
1215 goto fail1;
1216 else if (peer_alt_names != Py_None) {
1217 if (PyDict_SetItemString(retval, "subjectAltName",
1218 peer_alt_names) < 0) {
1219 Py_DECREF(peer_alt_names);
1220 goto fail1;
1221 }
1222 Py_DECREF(peer_alt_names);
1223 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001224
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001225 /* Authority Information Access: OCSP URIs */
1226 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1227 if (obj == NULL) {
1228 goto fail1;
1229 } else if (obj != Py_None) {
1230 result = PyDict_SetItemString(retval, "OCSP", obj);
1231 Py_DECREF(obj);
1232 if (result < 0) {
1233 goto fail1;
1234 }
1235 }
1236
1237 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1238 if (obj == NULL) {
1239 goto fail1;
1240 } else if (obj != Py_None) {
1241 result = PyDict_SetItemString(retval, "caIssuers", obj);
1242 Py_DECREF(obj);
1243 if (result < 0) {
1244 goto fail1;
1245 }
1246 }
1247
1248 /* CDP (CRL distribution points) */
1249 obj = _get_crl_dp(certificate);
1250 if (obj == NULL) {
1251 goto fail1;
1252 } else if (obj != Py_None) {
1253 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1254 Py_DECREF(obj);
1255 if (result < 0) {
1256 goto fail1;
1257 }
1258 }
1259
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001260 BIO_free(biobuf);
1261 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001262
1263 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001264 if (biobuf != NULL)
1265 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001266 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001267 Py_XDECREF(retval);
1268 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001269}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001270
Christian Heimes9a5395a2013-06-17 15:44:12 +02001271static PyObject *
1272_certificate_to_der(X509 *certificate)
1273{
1274 unsigned char *bytes_buf = NULL;
1275 int len;
1276 PyObject *retval;
1277
1278 bytes_buf = NULL;
1279 len = i2d_X509(certificate, &bytes_buf);
1280 if (len < 0) {
1281 _setSSLError(NULL, 0, __FILE__, __LINE__);
1282 return NULL;
1283 }
1284 /* this is actually an immutable bytes sequence */
1285 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1286 OPENSSL_free(bytes_buf);
1287 return retval;
1288}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001289
1290static PyObject *
1291PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1292
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001293 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001294 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 X509 *x=NULL;
1296 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001297
Antoine Pitroufb046912010-11-09 20:21:19 +00001298 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1299 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001300 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001301
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001302 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1303 PyErr_SetString(PySSLErrorObject,
1304 "Can't malloc memory to read file");
1305 goto fail0;
1306 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001307
Victor Stinner3800e1e2010-05-16 21:23:48 +00001308 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001309 PyErr_SetString(PySSLErrorObject,
1310 "Can't open file");
1311 goto fail0;
1312 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001313
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001314 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1315 if (x == NULL) {
1316 PyErr_SetString(PySSLErrorObject,
1317 "Error decoding PEM-encoded file");
1318 goto fail0;
1319 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001320
Antoine Pitroufb046912010-11-09 20:21:19 +00001321 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001322 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001323
1324 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001325 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001326 if (cert != NULL) BIO_free(cert);
1327 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001328}
1329
1330
1331static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001332PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001333{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001335 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001336
Antoine Pitrou721738f2012-08-15 23:20:39 +02001337 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001339
Antoine Pitrou20b85552013-09-29 19:50:53 +02001340 if (!self->handshake_done) {
1341 PyErr_SetString(PyExc_ValueError,
1342 "handshake not done yet");
1343 return NULL;
1344 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001345 if (!self->peer_cert)
1346 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001347
Antoine Pitrou721738f2012-08-15 23:20:39 +02001348 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001349 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001350 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001351 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001352 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001353 if ((verification & SSL_VERIFY_PEER) == 0)
1354 return PyDict_New();
1355 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001356 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001357 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001358}
1359
1360PyDoc_STRVAR(PySSL_peercert_doc,
1361"peer_certificate([der=False]) -> certificate\n\
1362\n\
1363Returns the certificate for the peer. If no certificate was provided,\n\
1364returns None. If a certificate was provided, but not validated, returns\n\
1365an empty dictionary. Otherwise returns a dict containing information\n\
1366about the peer certificate.\n\
1367\n\
1368If the optional argument is True, returns a DER-encoded copy of the\n\
1369peer certificate, or None if no certificate was provided. This will\n\
1370return the certificate even if it wasn't validated.");
1371
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001372static PyObject *
1373cipher_to_tuple(const SSL_CIPHER *cipher)
1374{
1375 const char *cipher_name, *cipher_protocol;
1376 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001377 if (retval == NULL)
1378 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001379
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001380 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001381 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001382 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001383 PyTuple_SET_ITEM(retval, 0, Py_None);
1384 } else {
1385 v = PyUnicode_FromString(cipher_name);
1386 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001387 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001388 PyTuple_SET_ITEM(retval, 0, v);
1389 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001390
1391 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001392 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001393 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001394 PyTuple_SET_ITEM(retval, 1, Py_None);
1395 } else {
1396 v = PyUnicode_FromString(cipher_protocol);
1397 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001398 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001399 PyTuple_SET_ITEM(retval, 1, v);
1400 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001401
1402 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001403 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001404 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001405 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001406
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001407 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001408
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001409 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001410 Py_DECREF(retval);
1411 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001412}
1413
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001414static PyObject *PySSL_shared_ciphers(PySSLSocket *self)
1415{
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001416 SSL_SESSION *sess = SSL_get_session(self->ssl);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001417 STACK_OF(SSL_CIPHER) *ciphers;
1418 int i;
1419 PyObject *res;
1420
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001421 if (!sess || !sess->ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001422 Py_RETURN_NONE;
Benjamin Petersonbaf7c1e2015-01-07 11:32:00 -06001423 ciphers = sess->ciphers;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001424 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1425 if (!res)
1426 return NULL;
1427 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1428 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1429 if (!tup) {
1430 Py_DECREF(res);
1431 return NULL;
1432 }
1433 PyList_SET_ITEM(res, i, tup);
1434 }
1435 return res;
1436}
1437
1438static PyObject *PySSL_cipher (PySSLSocket *self)
1439{
1440 const SSL_CIPHER *current;
1441
1442 if (self->ssl == NULL)
1443 Py_RETURN_NONE;
1444 current = SSL_get_current_cipher(self->ssl);
1445 if (current == NULL)
1446 Py_RETURN_NONE;
1447 return cipher_to_tuple(current);
1448}
1449
Antoine Pitrou47e40422014-09-04 21:00:10 +02001450static PyObject *PySSL_version(PySSLSocket *self)
1451{
1452 const char *version;
1453
1454 if (self->ssl == NULL)
1455 Py_RETURN_NONE;
1456 version = SSL_get_version(self->ssl);
1457 if (!strcmp(version, "unknown"))
1458 Py_RETURN_NONE;
1459 return PyUnicode_FromString(version);
1460}
1461
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001462#ifdef OPENSSL_NPN_NEGOTIATED
1463static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1464 const unsigned char *out;
1465 unsigned int outlen;
1466
Victor Stinner4569cd52013-06-23 14:58:43 +02001467 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001468 &out, &outlen);
1469
1470 if (out == NULL)
1471 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001472 return PyUnicode_FromStringAndSize((char *)out, outlen);
1473}
1474#endif
1475
1476#ifdef HAVE_ALPN
1477static PyObject *PySSL_selected_alpn_protocol(PySSLSocket *self) {
1478 const unsigned char *out;
1479 unsigned int outlen;
1480
1481 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1482
1483 if (out == NULL)
1484 Py_RETURN_NONE;
1485 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001486}
1487#endif
1488
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001489static PyObject *PySSL_compression(PySSLSocket *self) {
1490#ifdef OPENSSL_NO_COMP
1491 Py_RETURN_NONE;
1492#else
1493 const COMP_METHOD *comp_method;
1494 const char *short_name;
1495
1496 if (self->ssl == NULL)
1497 Py_RETURN_NONE;
1498 comp_method = SSL_get_current_compression(self->ssl);
1499 if (comp_method == NULL || comp_method->type == NID_undef)
1500 Py_RETURN_NONE;
1501 short_name = OBJ_nid2sn(comp_method->type);
1502 if (short_name == NULL)
1503 Py_RETURN_NONE;
1504 return PyUnicode_DecodeFSDefault(short_name);
1505#endif
1506}
1507
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001508static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1509 Py_INCREF(self->ctx);
1510 return self->ctx;
1511}
1512
1513static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1514 void *closure) {
1515
1516 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001517#if !HAVE_SNI
1518 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1519 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001520 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001521#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001522 Py_INCREF(value);
1523 Py_DECREF(self->ctx);
1524 self->ctx = (PySSLContext *) value;
1525 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001526#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001527 } else {
1528 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1529 return -1;
1530 }
1531
1532 return 0;
1533}
1534
1535PyDoc_STRVAR(PySSL_set_context_doc,
1536"_setter_context(ctx)\n\
1537\
1538This changes the context associated with the SSLSocket. This is typically\n\
1539used from within a callback function set by the set_servername_callback\n\
1540on the SSLContext to change the certificate information associated with the\n\
1541SSLSocket before the cryptographic exchange handshake messages\n");
1542
1543
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001544static PyObject *
1545PySSL_get_server_side(PySSLSocket *self, void *c)
1546{
1547 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1548}
1549
1550PyDoc_STRVAR(PySSL_get_server_side_doc,
1551"Whether this is a server-side socket.");
1552
1553static PyObject *
1554PySSL_get_server_hostname(PySSLSocket *self, void *c)
1555{
1556 if (self->server_hostname == NULL)
1557 Py_RETURN_NONE;
1558 Py_INCREF(self->server_hostname);
1559 return self->server_hostname;
1560}
1561
1562PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1563"The currently set server hostname (for SNI).");
1564
1565static PyObject *
1566PySSL_get_owner(PySSLSocket *self, void *c)
1567{
1568 PyObject *owner;
1569
1570 if (self->owner == NULL)
1571 Py_RETURN_NONE;
1572
1573 owner = PyWeakref_GetObject(self->owner);
1574 Py_INCREF(owner);
1575 return owner;
1576}
1577
1578static int
1579PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1580{
1581 Py_XDECREF(self->owner);
1582 self->owner = PyWeakref_NewRef(value, NULL);
1583 if (self->owner == NULL)
1584 return -1;
1585 return 0;
1586}
1587
1588PyDoc_STRVAR(PySSL_get_owner_doc,
1589"The Python-level owner of this object.\
1590Passed as \"self\" in servername callback.");
1591
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001592
Antoine Pitrou152efa22010-05-16 18:19:27 +00001593static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001594{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001595 if (self->peer_cert) /* Possible not to have one? */
1596 X509_free (self->peer_cert);
1597 if (self->ssl)
1598 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001599 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001600 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001601 Py_XDECREF(self->server_hostname);
1602 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001603 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001604}
1605
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001606/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001607 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001608 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001609 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001610
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001611static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001612check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001613{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001614 fd_set fds;
1615 struct timeval tv;
1616 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001618 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinnere2452312015-03-28 03:00:46 +01001619 if ((s == NULL) || (s->sock_timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001620 return SOCKET_IS_NONBLOCKING;
Victor Stinnere2452312015-03-28 03:00:46 +01001621 else if (s->sock_timeout < 0)
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001622 return SOCKET_IS_BLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001623
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001624 /* Guard against closed socket */
1625 if (s->sock_fd < 0)
1626 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001627
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001628 /* Prefer poll, if available, since you can poll() any fd
1629 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001630#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001631 {
1632 struct pollfd pollfd;
1633 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001634
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001635 pollfd.fd = s->sock_fd;
1636 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001637
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001638 /* s->sock_timeout is in seconds, timeout in ms */
Victor Stinnere2452312015-03-28 03:00:46 +01001639 timeout = (int)_PyTime_AsMilliseconds(s->sock_timeout,
1640 _PyTime_ROUND_UP);
1641
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001642 PySSL_BEGIN_ALLOW_THREADS
1643 rc = poll(&pollfd, 1, timeout);
1644 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001645
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001646 goto normal_return;
1647 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001648#endif
1649
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001650 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001651 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001652 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001653
Victor Stinnerea9c0dd2015-03-30 02:51:13 +02001654 _PyTime_AsTimeval_noraise(s->sock_timeout, &tv, _PyTime_ROUND_UP);
Victor Stinnere2452312015-03-28 03:00:46 +01001655
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001656 FD_ZERO(&fds);
1657 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001658
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001659 /* See if the socket is ready */
1660 PySSL_BEGIN_ALLOW_THREADS
1661 if (writing)
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001662 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1663 NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001664 else
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001665 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1666 &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001667 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001668
Bill Janssen6e027db2007-11-15 22:23:56 +00001669#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001670normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001671#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001672 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1673 (when we are able to write or when there's something to read) */
1674 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001675}
1676
Antoine Pitrou152efa22010-05-16 18:19:27 +00001677static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001678{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001679 Py_buffer buf;
1680 int len;
1681 int sockstate;
1682 int err;
1683 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001684 PySocketSockObject *sock = GET_SOCKET(self);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001685
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001686 if (sock != NULL) {
1687 if (((PyObject*)sock) == Py_None) {
1688 _setSSLError("Underlying socket connection gone",
1689 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1690 return NULL;
1691 }
1692 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001693 }
1694
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001695 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001696 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001697 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001698 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001699
Victor Stinner6efa9652013-06-25 00:42:31 +02001700 if (buf.len > INT_MAX) {
1701 PyErr_Format(PyExc_OverflowError,
1702 "string longer than %d bytes", INT_MAX);
1703 goto error;
1704 }
1705
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001706 if (sock != NULL) {
1707 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001708 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001709 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1710 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1711 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001712
1713 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1714 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001715 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001716 "The write operation timed out");
1717 goto error;
1718 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1719 PyErr_SetString(PySSLErrorObject,
1720 "Underlying socket has been closed.");
1721 goto error;
1722 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1723 PyErr_SetString(PySSLErrorObject,
1724 "Underlying socket too large for select().");
1725 goto error;
1726 }
1727 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001728 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001729 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001730 err = SSL_get_error(self->ssl, len);
1731 PySSL_END_ALLOW_THREADS
1732 if (PyErr_CheckSignals()) {
1733 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001734 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001735 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001736 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001738 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001739 } else {
1740 sockstate = SOCKET_OPERATION_OK;
1741 }
1742 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001743 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001744 "The write operation timed out");
1745 goto error;
1746 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1747 PyErr_SetString(PySSLErrorObject,
1748 "Underlying socket has been closed.");
1749 goto error;
1750 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1751 break;
1752 }
1753 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001754
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001755 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001756 PyBuffer_Release(&buf);
1757 if (len > 0)
1758 return PyLong_FromLong(len);
1759 else
1760 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001761
1762error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001763 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001764 PyBuffer_Release(&buf);
1765 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001766}
1767
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001768PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001769"write(s) -> len\n\
1770\n\
1771Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001772of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001773
Antoine Pitrou152efa22010-05-16 18:19:27 +00001774static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001775{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001776 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001777
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001778 PySSL_BEGIN_ALLOW_THREADS
1779 count = SSL_pending(self->ssl);
1780 PySSL_END_ALLOW_THREADS
1781 if (count < 0)
1782 return PySSL_SetError(self, count, __FILE__, __LINE__);
1783 else
1784 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001785}
1786
1787PyDoc_STRVAR(PySSL_SSLpending_doc,
1788"pending() -> count\n\
1789\n\
1790Returns the number of already decrypted bytes available for read,\n\
1791pending on the connection.\n");
1792
Antoine Pitrou152efa22010-05-16 18:19:27 +00001793static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001794{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001795 PyObject *dest = NULL;
1796 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001797 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001798 int len, count;
1799 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001800 int sockstate;
1801 int err;
1802 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001803 PySocketSockObject *sock = GET_SOCKET(self);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001804
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001805 if (sock != NULL) {
1806 if (((PyObject*)sock) == Py_None) {
1807 _setSSLError("Underlying socket connection gone",
1808 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1809 return NULL;
1810 }
1811 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001812 }
1813
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001814 buf.obj = NULL;
1815 buf.buf = NULL;
1816 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001817 goto error;
1818
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001819 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1820 dest = PyBytes_FromStringAndSize(NULL, len);
1821 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001822 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001823 mem = PyBytes_AS_STRING(dest);
1824 }
1825 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001826 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001827 mem = buf.buf;
1828 if (len <= 0 || len > buf.len) {
1829 len = (int) buf.len;
1830 if (buf.len != len) {
1831 PyErr_SetString(PyExc_OverflowError,
1832 "maximum length can't fit in a C 'int'");
1833 goto error;
1834 }
1835 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001836 }
1837
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001838 if (sock != NULL) {
1839 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001840 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001841 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1842 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1843 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001844
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001845 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001846 PySSL_BEGIN_ALLOW_THREADS
1847 count = SSL_read(self->ssl, mem, len);
1848 err = SSL_get_error(self->ssl, count);
1849 PySSL_END_ALLOW_THREADS
1850 if (PyErr_CheckSignals())
1851 goto error;
1852 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001853 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001854 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001855 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1857 (SSL_get_shutdown(self->ssl) ==
1858 SSL_RECEIVED_SHUTDOWN))
1859 {
1860 count = 0;
1861 goto done;
1862 } else {
1863 sockstate = SOCKET_OPERATION_OK;
1864 }
1865 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001866 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001867 "The read operation timed out");
1868 goto error;
1869 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1870 break;
1871 }
1872 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1873 if (count <= 0) {
1874 PySSL_SetError(self, count, __FILE__, __LINE__);
1875 goto error;
1876 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001877
1878done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001879 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001880 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001881 _PyBytes_Resize(&dest, count);
1882 return dest;
1883 }
1884 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001885 PyBuffer_Release(&buf);
1886 return PyLong_FromLong(count);
1887 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001888
1889error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001890 Py_XDECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001891 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001892 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001893 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001894 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001895 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001896}
1897
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001898PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001899"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001900\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001901Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001902
Antoine Pitrou152efa22010-05-16 18:19:27 +00001903static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001904{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001905 int err, ssl_err, sockstate, nonblocking;
1906 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001907 PySocketSockObject *sock = GET_SOCKET(self);
Bill Janssen40a0f662008-08-12 16:56:25 +00001908
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001909 if (sock != NULL) {
1910 /* Guard against closed socket */
1911 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1912 _setSSLError("Underlying socket connection gone",
1913 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1914 return NULL;
1915 }
1916 Py_INCREF(sock);
1917
1918 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001919 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001920 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1921 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001922 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001923
1924 while (1) {
1925 PySSL_BEGIN_ALLOW_THREADS
1926 /* Disable read-ahead so that unwrap can work correctly.
1927 * Otherwise OpenSSL might read in too much data,
1928 * eating clear text data that happens to be
1929 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001930 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001931 * function is used and the shutdown_seen_zero != 0
1932 * condition is met.
1933 */
1934 if (self->shutdown_seen_zero)
1935 SSL_set_read_ahead(self->ssl, 0);
1936 err = SSL_shutdown(self->ssl);
1937 PySSL_END_ALLOW_THREADS
1938 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1939 if (err > 0)
1940 break;
1941 if (err == 0) {
1942 /* Don't loop endlessly; instead preserve legacy
1943 behaviour of trying SSL_shutdown() only twice.
1944 This looks necessary for OpenSSL < 0.9.8m */
1945 if (++zeros > 1)
1946 break;
1947 /* Shutdown was sent, now try receiving */
1948 self->shutdown_seen_zero = 1;
1949 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001950 }
1951
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001952 /* Possibly retry shutdown until timeout or failure */
1953 ssl_err = SSL_get_error(self->ssl, err);
1954 if (ssl_err == SSL_ERROR_WANT_READ)
1955 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1956 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1957 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1958 else
1959 break;
1960 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1961 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001962 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001963 "The read operation timed out");
1964 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001965 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001966 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001967 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001968 }
1969 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1970 PyErr_SetString(PySSLErrorObject,
1971 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001972 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001973 }
1974 else if (sockstate != SOCKET_OPERATION_OK)
1975 /* Retain the SSL error code */
1976 break;
1977 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001978
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001979 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001980 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001981 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001982 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001983 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001984 /* It's already INCREF'ed */
1985 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001986 else
1987 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001988
1989error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001990 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001991 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001992}
1993
1994PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1995"shutdown(s) -> socket\n\
1996\n\
1997Does the SSL shutdown handshake with the remote end, and returns\n\
1998the underlying socket object.");
1999
Antoine Pitroud6494802011-07-21 01:11:30 +02002000static PyObject *
2001PySSL_tls_unique_cb(PySSLSocket *self)
2002{
2003 PyObject *retval = NULL;
2004 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002005 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002006
2007 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2008 /* if session is resumed XOR we are the client */
2009 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2010 }
2011 else {
2012 /* if a new session XOR we are the server */
2013 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2014 }
2015
2016 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002017 if (len == 0)
2018 Py_RETURN_NONE;
2019
2020 retval = PyBytes_FromStringAndSize(buf, len);
2021
2022 return retval;
2023}
2024
2025PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2026"tls_unique_cb() -> bytes\n\
2027\n\
2028Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2029\n\
2030If the TLS handshake is not yet complete, None is returned");
2031
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002032static PyGetSetDef ssl_getsetlist[] = {
2033 {"context", (getter) PySSL_get_context,
2034 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002035 {"server_side", (getter) PySSL_get_server_side, NULL,
2036 PySSL_get_server_side_doc},
2037 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2038 PySSL_get_server_hostname_doc},
2039 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2040 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002041 {NULL}, /* sentinel */
2042};
2043
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002044static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002045 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2046 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2047 PySSL_SSLwrite_doc},
2048 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2049 PySSL_SSLread_doc},
2050 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2051 PySSL_SSLpending_doc},
2052 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2053 PySSL_peercert_doc},
2054 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002055 {"shared_ciphers", (PyCFunction)PySSL_shared_ciphers, METH_NOARGS},
Antoine Pitrou47e40422014-09-04 21:00:10 +02002056 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002057#ifdef OPENSSL_NPN_NEGOTIATED
2058 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2059#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002060#ifdef HAVE_ALPN
2061 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2062#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002063 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002064 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2065 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02002066 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2067 PySSL_tls_unique_cb_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002068 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002069};
2070
Antoine Pitrou152efa22010-05-16 18:19:27 +00002071static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002072 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002073 "_ssl._SSLSocket", /*tp_name*/
2074 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002075 0, /*tp_itemsize*/
2076 /* methods */
2077 (destructor)PySSL_dealloc, /*tp_dealloc*/
2078 0, /*tp_print*/
2079 0, /*tp_getattr*/
2080 0, /*tp_setattr*/
2081 0, /*tp_reserved*/
2082 0, /*tp_repr*/
2083 0, /*tp_as_number*/
2084 0, /*tp_as_sequence*/
2085 0, /*tp_as_mapping*/
2086 0, /*tp_hash*/
2087 0, /*tp_call*/
2088 0, /*tp_str*/
2089 0, /*tp_getattro*/
2090 0, /*tp_setattro*/
2091 0, /*tp_as_buffer*/
2092 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2093 0, /*tp_doc*/
2094 0, /*tp_traverse*/
2095 0, /*tp_clear*/
2096 0, /*tp_richcompare*/
2097 0, /*tp_weaklistoffset*/
2098 0, /*tp_iter*/
2099 0, /*tp_iternext*/
2100 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002101 0, /*tp_members*/
2102 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002103};
2104
Antoine Pitrou152efa22010-05-16 18:19:27 +00002105
2106/*
2107 * _SSLContext objects
2108 */
2109
2110static PyObject *
2111context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2112{
2113 char *kwlist[] = {"protocol", NULL};
2114 PySSLContext *self;
2115 int proto_version = PY_SSL_VERSION_SSL23;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002116 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002117 SSL_CTX *ctx = NULL;
2118
2119 if (!PyArg_ParseTupleAndKeywords(
2120 args, kwds, "i:_SSLContext", kwlist,
2121 &proto_version))
2122 return NULL;
2123
2124 PySSL_BEGIN_ALLOW_THREADS
2125 if (proto_version == PY_SSL_VERSION_TLS1)
2126 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002127#if HAVE_TLSv1_2
2128 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2129 ctx = SSL_CTX_new(TLSv1_1_method());
2130 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2131 ctx = SSL_CTX_new(TLSv1_2_method());
2132#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002133#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002134 else if (proto_version == PY_SSL_VERSION_SSL3)
2135 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002136#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002137#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002138 else if (proto_version == PY_SSL_VERSION_SSL2)
2139 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002140#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002141 else if (proto_version == PY_SSL_VERSION_SSL23)
2142 ctx = SSL_CTX_new(SSLv23_method());
2143 else
2144 proto_version = -1;
2145 PySSL_END_ALLOW_THREADS
2146
2147 if (proto_version == -1) {
2148 PyErr_SetString(PyExc_ValueError,
2149 "invalid protocol version");
2150 return NULL;
2151 }
2152 if (ctx == NULL) {
2153 PyErr_SetString(PySSLErrorObject,
2154 "failed to allocate SSL context");
2155 return NULL;
2156 }
2157
2158 assert(type != NULL && type->tp_alloc != NULL);
2159 self = (PySSLContext *) type->tp_alloc(type, 0);
2160 if (self == NULL) {
2161 SSL_CTX_free(ctx);
2162 return NULL;
2163 }
2164 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002165#ifdef OPENSSL_NPN_NEGOTIATED
2166 self->npn_protocols = NULL;
2167#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002168#ifdef HAVE_ALPN
2169 self->alpn_protocols = NULL;
2170#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002171#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002172 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002173#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002174 /* Don't check host name by default */
2175 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002176 /* Defaults */
2177 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002178 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2179 if (proto_version != PY_SSL_VERSION_SSL2)
2180 options |= SSL_OP_NO_SSLv2;
2181 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002182
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002183#ifndef OPENSSL_NO_ECDH
2184 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2185 prime256v1 by default. This is Apache mod_ssl's initialization
2186 policy, so we should be safe. */
2187#if defined(SSL_CTX_set_ecdh_auto)
2188 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2189#else
2190 {
2191 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2192 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2193 EC_KEY_free(key);
2194 }
2195#endif
2196#endif
2197
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002198#define SID_CTX "Python"
2199 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2200 sizeof(SID_CTX));
2201#undef SID_CTX
2202
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002203#ifdef X509_V_FLAG_TRUSTED_FIRST
2204 {
2205 /* Improve trust chain building when cross-signed intermediate
2206 certificates are present. See https://bugs.python.org/issue23476. */
2207 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2208 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2209 }
2210#endif
2211
Antoine Pitrou152efa22010-05-16 18:19:27 +00002212 return (PyObject *)self;
2213}
2214
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002215static int
2216context_traverse(PySSLContext *self, visitproc visit, void *arg)
2217{
2218#ifndef OPENSSL_NO_TLSEXT
2219 Py_VISIT(self->set_hostname);
2220#endif
2221 return 0;
2222}
2223
2224static int
2225context_clear(PySSLContext *self)
2226{
2227#ifndef OPENSSL_NO_TLSEXT
2228 Py_CLEAR(self->set_hostname);
2229#endif
2230 return 0;
2231}
2232
Antoine Pitrou152efa22010-05-16 18:19:27 +00002233static void
2234context_dealloc(PySSLContext *self)
2235{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002236 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002237 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002238#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002239 PyMem_FREE(self->npn_protocols);
2240#endif
2241#ifdef HAVE_ALPN
2242 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002243#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002244 Py_TYPE(self)->tp_free(self);
2245}
2246
2247static PyObject *
2248set_ciphers(PySSLContext *self, PyObject *args)
2249{
2250 int ret;
2251 const char *cipherlist;
2252
2253 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2254 return NULL;
2255 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2256 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002257 /* Clearing the error queue is necessary on some OpenSSL versions,
2258 otherwise the error will be reported again when another SSL call
2259 is done. */
2260 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002261 PyErr_SetString(PySSLErrorObject,
2262 "No cipher can be selected.");
2263 return NULL;
2264 }
2265 Py_RETURN_NONE;
2266}
2267
Benjamin Petersonc54de472015-01-28 12:06:39 -05002268#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002269static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002270do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2271 const unsigned char *server_protocols, unsigned int server_protocols_len,
2272 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002273{
Benjamin Peterson88615022015-01-23 17:30:26 -05002274 int ret;
2275 if (client_protocols == NULL) {
2276 client_protocols = (unsigned char *)"";
2277 client_protocols_len = 0;
2278 }
2279 if (server_protocols == NULL) {
2280 server_protocols = (unsigned char *)"";
2281 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002282 }
2283
Benjamin Peterson88615022015-01-23 17:30:26 -05002284 ret = SSL_select_next_proto(out, outlen,
2285 server_protocols, server_protocols_len,
2286 client_protocols, client_protocols_len);
2287 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2288 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002289
2290 return SSL_TLSEXT_ERR_OK;
2291}
2292
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002293/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2294static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002295_advertiseNPN_cb(SSL *s,
2296 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002297 void *args)
2298{
2299 PySSLContext *ssl_ctx = (PySSLContext *) args;
2300
2301 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002302 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002303 *len = 0;
2304 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002305 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002306 *len = ssl_ctx->npn_protocols_len;
2307 }
2308
2309 return SSL_TLSEXT_ERR_OK;
2310}
2311/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2312static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002313_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002314 unsigned char **out, unsigned char *outlen,
2315 const unsigned char *server, unsigned int server_len,
2316 void *args)
2317{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002318 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002319 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002320 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002321}
2322#endif
2323
2324static PyObject *
2325_set_npn_protocols(PySSLContext *self, PyObject *args)
2326{
2327#ifdef OPENSSL_NPN_NEGOTIATED
2328 Py_buffer protos;
2329
2330 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2331 return NULL;
2332
Christian Heimes5cb31c92012-09-20 12:42:54 +02002333 if (self->npn_protocols != NULL) {
2334 PyMem_Free(self->npn_protocols);
2335 }
2336
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002337 self->npn_protocols = PyMem_Malloc(protos.len);
2338 if (self->npn_protocols == NULL) {
2339 PyBuffer_Release(&protos);
2340 return PyErr_NoMemory();
2341 }
2342 memcpy(self->npn_protocols, protos.buf, protos.len);
2343 self->npn_protocols_len = (int) protos.len;
2344
2345 /* set both server and client callbacks, because the context can
2346 * be used to create both types of sockets */
2347 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2348 _advertiseNPN_cb,
2349 self);
2350 SSL_CTX_set_next_proto_select_cb(self->ctx,
2351 _selectNPN_cb,
2352 self);
2353
2354 PyBuffer_Release(&protos);
2355 Py_RETURN_NONE;
2356#else
2357 PyErr_SetString(PyExc_NotImplementedError,
2358 "The NPN extension requires OpenSSL 1.0.1 or later.");
2359 return NULL;
2360#endif
2361}
2362
Benjamin Petersoncca27322015-01-23 16:35:37 -05002363#ifdef HAVE_ALPN
2364static int
2365_selectALPN_cb(SSL *s,
2366 const unsigned char **out, unsigned char *outlen,
2367 const unsigned char *client_protocols, unsigned int client_protocols_len,
2368 void *args)
2369{
2370 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002371 return do_protocol_selection(1, (unsigned char **)out, outlen,
2372 ctx->alpn_protocols, ctx->alpn_protocols_len,
2373 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002374}
2375#endif
2376
2377static PyObject *
2378_set_alpn_protocols(PySSLContext *self, PyObject *args)
2379{
2380#ifdef HAVE_ALPN
2381 Py_buffer protos;
2382
2383 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2384 return NULL;
2385
2386 PyMem_FREE(self->alpn_protocols);
2387 self->alpn_protocols = PyMem_Malloc(protos.len);
2388 if (!self->alpn_protocols)
2389 return PyErr_NoMemory();
2390 memcpy(self->alpn_protocols, protos.buf, protos.len);
2391 self->alpn_protocols_len = protos.len;
2392 PyBuffer_Release(&protos);
2393
2394 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2395 return PyErr_NoMemory();
2396 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2397
2398 PyBuffer_Release(&protos);
2399 Py_RETURN_NONE;
2400#else
2401 PyErr_SetString(PyExc_NotImplementedError,
2402 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2403 return NULL;
2404#endif
2405}
2406
Antoine Pitrou152efa22010-05-16 18:19:27 +00002407static PyObject *
2408get_verify_mode(PySSLContext *self, void *c)
2409{
2410 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2411 case SSL_VERIFY_NONE:
2412 return PyLong_FromLong(PY_SSL_CERT_NONE);
2413 case SSL_VERIFY_PEER:
2414 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2415 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2416 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2417 }
2418 PyErr_SetString(PySSLErrorObject,
2419 "invalid return value from SSL_CTX_get_verify_mode");
2420 return NULL;
2421}
2422
2423static int
2424set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2425{
2426 int n, mode;
2427 if (!PyArg_Parse(arg, "i", &n))
2428 return -1;
2429 if (n == PY_SSL_CERT_NONE)
2430 mode = SSL_VERIFY_NONE;
2431 else if (n == PY_SSL_CERT_OPTIONAL)
2432 mode = SSL_VERIFY_PEER;
2433 else if (n == PY_SSL_CERT_REQUIRED)
2434 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2435 else {
2436 PyErr_SetString(PyExc_ValueError,
2437 "invalid value for verify_mode");
2438 return -1;
2439 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002440 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2441 PyErr_SetString(PyExc_ValueError,
2442 "Cannot set verify_mode to CERT_NONE when "
2443 "check_hostname is enabled.");
2444 return -1;
2445 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002446 SSL_CTX_set_verify(self->ctx, mode, NULL);
2447 return 0;
2448}
2449
2450static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002451get_verify_flags(PySSLContext *self, void *c)
2452{
2453 X509_STORE *store;
2454 unsigned long flags;
2455
2456 store = SSL_CTX_get_cert_store(self->ctx);
2457 flags = X509_VERIFY_PARAM_get_flags(store->param);
2458 return PyLong_FromUnsignedLong(flags);
2459}
2460
2461static int
2462set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2463{
2464 X509_STORE *store;
2465 unsigned long new_flags, flags, set, clear;
2466
2467 if (!PyArg_Parse(arg, "k", &new_flags))
2468 return -1;
2469 store = SSL_CTX_get_cert_store(self->ctx);
2470 flags = X509_VERIFY_PARAM_get_flags(store->param);
2471 clear = flags & ~new_flags;
2472 set = ~flags & new_flags;
2473 if (clear) {
2474 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2475 _setSSLError(NULL, 0, __FILE__, __LINE__);
2476 return -1;
2477 }
2478 }
2479 if (set) {
2480 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2481 _setSSLError(NULL, 0, __FILE__, __LINE__);
2482 return -1;
2483 }
2484 }
2485 return 0;
2486}
2487
2488static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002489get_options(PySSLContext *self, void *c)
2490{
2491 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2492}
2493
2494static int
2495set_options(PySSLContext *self, PyObject *arg, void *c)
2496{
2497 long new_opts, opts, set, clear;
2498 if (!PyArg_Parse(arg, "l", &new_opts))
2499 return -1;
2500 opts = SSL_CTX_get_options(self->ctx);
2501 clear = opts & ~new_opts;
2502 set = ~opts & new_opts;
2503 if (clear) {
2504#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2505 SSL_CTX_clear_options(self->ctx, clear);
2506#else
2507 PyErr_SetString(PyExc_ValueError,
2508 "can't clear options before OpenSSL 0.9.8m");
2509 return -1;
2510#endif
2511 }
2512 if (set)
2513 SSL_CTX_set_options(self->ctx, set);
2514 return 0;
2515}
2516
Christian Heimes1aa9a752013-12-02 02:41:19 +01002517static PyObject *
2518get_check_hostname(PySSLContext *self, void *c)
2519{
2520 return PyBool_FromLong(self->check_hostname);
2521}
2522
2523static int
2524set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2525{
2526 int check_hostname;
2527 if (!PyArg_Parse(arg, "p", &check_hostname))
2528 return -1;
2529 if (check_hostname &&
2530 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2531 PyErr_SetString(PyExc_ValueError,
2532 "check_hostname needs a SSL context with either "
2533 "CERT_OPTIONAL or CERT_REQUIRED");
2534 return -1;
2535 }
2536 self->check_hostname = check_hostname;
2537 return 0;
2538}
2539
2540
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002541typedef struct {
2542 PyThreadState *thread_state;
2543 PyObject *callable;
2544 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002545 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002546 int error;
2547} _PySSLPasswordInfo;
2548
2549static int
2550_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2551 const char *bad_type_error)
2552{
2553 /* Set the password and size fields of a _PySSLPasswordInfo struct
2554 from a unicode, bytes, or byte array object.
2555 The password field will be dynamically allocated and must be freed
2556 by the caller */
2557 PyObject *password_bytes = NULL;
2558 const char *data = NULL;
2559 Py_ssize_t size;
2560
2561 if (PyUnicode_Check(password)) {
2562 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2563 if (!password_bytes) {
2564 goto error;
2565 }
2566 data = PyBytes_AS_STRING(password_bytes);
2567 size = PyBytes_GET_SIZE(password_bytes);
2568 } else if (PyBytes_Check(password)) {
2569 data = PyBytes_AS_STRING(password);
2570 size = PyBytes_GET_SIZE(password);
2571 } else if (PyByteArray_Check(password)) {
2572 data = PyByteArray_AS_STRING(password);
2573 size = PyByteArray_GET_SIZE(password);
2574 } else {
2575 PyErr_SetString(PyExc_TypeError, bad_type_error);
2576 goto error;
2577 }
2578
Victor Stinner9ee02032013-06-23 15:08:23 +02002579 if (size > (Py_ssize_t)INT_MAX) {
2580 PyErr_Format(PyExc_ValueError,
2581 "password cannot be longer than %d bytes", INT_MAX);
2582 goto error;
2583 }
2584
Victor Stinner11ebff22013-07-07 17:07:52 +02002585 PyMem_Free(pw_info->password);
2586 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002587 if (!pw_info->password) {
2588 PyErr_SetString(PyExc_MemoryError,
2589 "unable to allocate password buffer");
2590 goto error;
2591 }
2592 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002593 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002594
2595 Py_XDECREF(password_bytes);
2596 return 1;
2597
2598error:
2599 Py_XDECREF(password_bytes);
2600 return 0;
2601}
2602
2603static int
2604_password_callback(char *buf, int size, int rwflag, void *userdata)
2605{
2606 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2607 PyObject *fn_ret = NULL;
2608
2609 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2610
2611 if (pw_info->callable) {
2612 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2613 if (!fn_ret) {
2614 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2615 core python API, so we could use it to add a frame here */
2616 goto error;
2617 }
2618
2619 if (!_pwinfo_set(pw_info, fn_ret,
2620 "password callback must return a string")) {
2621 goto error;
2622 }
2623 Py_CLEAR(fn_ret);
2624 }
2625
2626 if (pw_info->size > size) {
2627 PyErr_Format(PyExc_ValueError,
2628 "password cannot be longer than %d bytes", size);
2629 goto error;
2630 }
2631
2632 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2633 memcpy(buf, pw_info->password, pw_info->size);
2634 return pw_info->size;
2635
2636error:
2637 Py_XDECREF(fn_ret);
2638 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2639 pw_info->error = 1;
2640 return -1;
2641}
2642
Antoine Pitroub5218772010-05-21 09:56:06 +00002643static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002644load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2645{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002646 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2647 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002648 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002649 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2650 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2651 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002652 int r;
2653
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002654 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002655 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002656 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002657 "O|OO:load_cert_chain", kwlist,
2658 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002659 return NULL;
2660 if (keyfile == Py_None)
2661 keyfile = NULL;
2662 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2663 PyErr_SetString(PyExc_TypeError,
2664 "certfile should be a valid filesystem path");
2665 return NULL;
2666 }
2667 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2668 PyErr_SetString(PyExc_TypeError,
2669 "keyfile should be a valid filesystem path");
2670 goto error;
2671 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002672 if (password && password != Py_None) {
2673 if (PyCallable_Check(password)) {
2674 pw_info.callable = password;
2675 } else if (!_pwinfo_set(&pw_info, password,
2676 "password should be a string or callable")) {
2677 goto error;
2678 }
2679 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2680 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2681 }
2682 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002683 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2684 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002685 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002686 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002687 if (pw_info.error) {
2688 ERR_clear_error();
2689 /* the password callback has already set the error information */
2690 }
2691 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002692 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002693 PyErr_SetFromErrno(PyExc_IOError);
2694 }
2695 else {
2696 _setSSLError(NULL, 0, __FILE__, __LINE__);
2697 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002698 goto error;
2699 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002700 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002701 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002702 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2703 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002704 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2705 Py_CLEAR(keyfile_bytes);
2706 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002707 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002708 if (pw_info.error) {
2709 ERR_clear_error();
2710 /* the password callback has already set the error information */
2711 }
2712 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002713 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002714 PyErr_SetFromErrno(PyExc_IOError);
2715 }
2716 else {
2717 _setSSLError(NULL, 0, __FILE__, __LINE__);
2718 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002719 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002720 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002721 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002722 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002723 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002724 if (r != 1) {
2725 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002726 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002727 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002728 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2729 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002730 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002731 Py_RETURN_NONE;
2732
2733error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002734 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2735 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002736 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002737 Py_XDECREF(keyfile_bytes);
2738 Py_XDECREF(certfile_bytes);
2739 return NULL;
2740}
2741
Christian Heimesefff7062013-11-21 03:35:02 +01002742/* internal helper function, returns -1 on error
2743 */
2744static int
2745_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2746 int filetype)
2747{
2748 BIO *biobuf = NULL;
2749 X509_STORE *store;
2750 int retval = 0, err, loaded = 0;
2751
2752 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2753
2754 if (len <= 0) {
2755 PyErr_SetString(PyExc_ValueError,
2756 "Empty certificate data");
2757 return -1;
2758 } else if (len > INT_MAX) {
2759 PyErr_SetString(PyExc_OverflowError,
2760 "Certificate data is too long.");
2761 return -1;
2762 }
2763
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002764 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002765 if (biobuf == NULL) {
2766 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2767 return -1;
2768 }
2769
2770 store = SSL_CTX_get_cert_store(self->ctx);
2771 assert(store != NULL);
2772
2773 while (1) {
2774 X509 *cert = NULL;
2775 int r;
2776
2777 if (filetype == SSL_FILETYPE_ASN1) {
2778 cert = d2i_X509_bio(biobuf, NULL);
2779 } else {
2780 cert = PEM_read_bio_X509(biobuf, NULL,
2781 self->ctx->default_passwd_callback,
2782 self->ctx->default_passwd_callback_userdata);
2783 }
2784 if (cert == NULL) {
2785 break;
2786 }
2787 r = X509_STORE_add_cert(store, cert);
2788 X509_free(cert);
2789 if (!r) {
2790 err = ERR_peek_last_error();
2791 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2792 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2793 /* cert already in hash table, not an error */
2794 ERR_clear_error();
2795 } else {
2796 break;
2797 }
2798 }
2799 loaded++;
2800 }
2801
2802 err = ERR_peek_last_error();
2803 if ((filetype == SSL_FILETYPE_ASN1) &&
2804 (loaded > 0) &&
2805 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2806 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2807 /* EOF ASN1 file, not an error */
2808 ERR_clear_error();
2809 retval = 0;
2810 } else if ((filetype == SSL_FILETYPE_PEM) &&
2811 (loaded > 0) &&
2812 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2813 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2814 /* EOF PEM file, not an error */
2815 ERR_clear_error();
2816 retval = 0;
2817 } else {
2818 _setSSLError(NULL, 0, __FILE__, __LINE__);
2819 retval = -1;
2820 }
2821
2822 BIO_free(biobuf);
2823 return retval;
2824}
2825
2826
Antoine Pitrou152efa22010-05-16 18:19:27 +00002827static PyObject *
2828load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2829{
Christian Heimesefff7062013-11-21 03:35:02 +01002830 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2831 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002832 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2833 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002834 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002835
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002836 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002837 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002838 "|OOO:load_verify_locations", kwlist,
2839 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002840 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002841
Antoine Pitrou152efa22010-05-16 18:19:27 +00002842 if (cafile == Py_None)
2843 cafile = NULL;
2844 if (capath == Py_None)
2845 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002846 if (cadata == Py_None)
2847 cadata = NULL;
2848
2849 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002850 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002851 "cafile, capath and cadata cannot be all omitted");
2852 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002853 }
2854 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2855 PyErr_SetString(PyExc_TypeError,
2856 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002857 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002858 }
2859 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002860 PyErr_SetString(PyExc_TypeError,
2861 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002862 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002863 }
Christian Heimesefff7062013-11-21 03:35:02 +01002864
2865 /* validata cadata type and load cadata */
2866 if (cadata) {
2867 Py_buffer buf;
2868 PyObject *cadata_ascii = NULL;
2869
2870 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2871 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2872 PyBuffer_Release(&buf);
2873 PyErr_SetString(PyExc_TypeError,
2874 "cadata should be a contiguous buffer with "
2875 "a single dimension");
2876 goto error;
2877 }
2878 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2879 PyBuffer_Release(&buf);
2880 if (r == -1) {
2881 goto error;
2882 }
2883 } else {
2884 PyErr_Clear();
2885 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2886 if (cadata_ascii == NULL) {
2887 PyErr_SetString(PyExc_TypeError,
2888 "cadata should be a ASCII string or a "
2889 "bytes-like object");
2890 goto error;
2891 }
2892 r = _add_ca_certs(self,
2893 PyBytes_AS_STRING(cadata_ascii),
2894 PyBytes_GET_SIZE(cadata_ascii),
2895 SSL_FILETYPE_PEM);
2896 Py_DECREF(cadata_ascii);
2897 if (r == -1) {
2898 goto error;
2899 }
2900 }
2901 }
2902
2903 /* load cafile or capath */
2904 if (cafile || capath) {
2905 if (cafile)
2906 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2907 if (capath)
2908 capath_buf = PyBytes_AS_STRING(capath_bytes);
2909 PySSL_BEGIN_ALLOW_THREADS
2910 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2911 PySSL_END_ALLOW_THREADS
2912 if (r != 1) {
2913 ok = 0;
2914 if (errno != 0) {
2915 ERR_clear_error();
2916 PyErr_SetFromErrno(PyExc_IOError);
2917 }
2918 else {
2919 _setSSLError(NULL, 0, __FILE__, __LINE__);
2920 }
2921 goto error;
2922 }
2923 }
2924 goto end;
2925
2926 error:
2927 ok = 0;
2928 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002929 Py_XDECREF(cafile_bytes);
2930 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002931 if (ok) {
2932 Py_RETURN_NONE;
2933 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002934 return NULL;
2935 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002936}
2937
2938static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002939load_dh_params(PySSLContext *self, PyObject *filepath)
2940{
2941 FILE *f;
2942 DH *dh;
2943
Victor Stinnerdaf45552013-08-28 00:53:59 +02002944 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01002945 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002946 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01002947
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002948 errno = 0;
2949 PySSL_BEGIN_ALLOW_THREADS
2950 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002951 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002952 PySSL_END_ALLOW_THREADS
2953 if (dh == NULL) {
2954 if (errno != 0) {
2955 ERR_clear_error();
2956 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2957 }
2958 else {
2959 _setSSLError(NULL, 0, __FILE__, __LINE__);
2960 }
2961 return NULL;
2962 }
2963 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2964 _setSSLError(NULL, 0, __FILE__, __LINE__);
2965 DH_free(dh);
2966 Py_RETURN_NONE;
2967}
2968
2969static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002970context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2971{
Antoine Pitroud5323212010-10-22 18:19:07 +00002972 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002973 PySocketSockObject *sock;
2974 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002975 char *hostname = NULL;
2976 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002977
Antoine Pitroud5323212010-10-22 18:19:07 +00002978 /* server_hostname is either None (or absent), or to be encoded
2979 using the idna encoding. */
2980 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002981 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002982 &sock, &server_side,
2983 Py_TYPE(Py_None), &hostname_obj)) {
2984 PyErr_Clear();
2985 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2986 PySocketModule.Sock_Type,
2987 &sock, &server_side,
2988 "idna", &hostname))
2989 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002990 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002991
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002992 res = (PyObject *) newPySSLSocket(self, sock, server_side, hostname,
2993 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00002994 if (hostname != NULL)
2995 PyMem_Free(hostname);
2996 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002997}
2998
Antoine Pitroub0182c82010-10-12 20:09:02 +00002999static PyObject *
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003000context_wrap_bio(PySSLContext *self, PyObject *args, PyObject *kwds)
3001{
3002 char *kwlist[] = {"incoming", "outgoing", "server_side",
3003 "server_hostname", NULL};
3004 int server_side;
3005 char *hostname = NULL;
3006 PyObject *hostname_obj = Py_None, *res;
3007 PySSLMemoryBIO *incoming, *outgoing;
3008
3009 /* server_hostname is either None (or absent), or to be encoded
3010 using the idna encoding. */
3011 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!O!i|O:_wrap_bio", kwlist,
3012 &PySSLMemoryBIO_Type, &incoming,
3013 &PySSLMemoryBIO_Type, &outgoing,
3014 &server_side, &hostname_obj))
3015 return NULL;
3016 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003017 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3018 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003019 }
3020
3021 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3022 incoming, outgoing);
3023
3024 PyMem_Free(hostname);
3025 return res;
3026}
3027
3028static PyObject *
Antoine Pitroub0182c82010-10-12 20:09:02 +00003029session_stats(PySSLContext *self, PyObject *unused)
3030{
3031 int r;
3032 PyObject *value, *stats = PyDict_New();
3033 if (!stats)
3034 return NULL;
3035
3036#define ADD_STATS(SSL_NAME, KEY_NAME) \
3037 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3038 if (value == NULL) \
3039 goto error; \
3040 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3041 Py_DECREF(value); \
3042 if (r < 0) \
3043 goto error;
3044
3045 ADD_STATS(number, "number");
3046 ADD_STATS(connect, "connect");
3047 ADD_STATS(connect_good, "connect_good");
3048 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3049 ADD_STATS(accept, "accept");
3050 ADD_STATS(accept_good, "accept_good");
3051 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3052 ADD_STATS(accept, "accept");
3053 ADD_STATS(hits, "hits");
3054 ADD_STATS(misses, "misses");
3055 ADD_STATS(timeouts, "timeouts");
3056 ADD_STATS(cache_full, "cache_full");
3057
3058#undef ADD_STATS
3059
3060 return stats;
3061
3062error:
3063 Py_DECREF(stats);
3064 return NULL;
3065}
3066
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003067static PyObject *
3068set_default_verify_paths(PySSLContext *self, PyObject *unused)
3069{
3070 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3071 _setSSLError(NULL, 0, __FILE__, __LINE__);
3072 return NULL;
3073 }
3074 Py_RETURN_NONE;
3075}
3076
Antoine Pitrou501da612011-12-21 09:27:41 +01003077#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003078static PyObject *
3079set_ecdh_curve(PySSLContext *self, PyObject *name)
3080{
3081 PyObject *name_bytes;
3082 int nid;
3083 EC_KEY *key;
3084
3085 if (!PyUnicode_FSConverter(name, &name_bytes))
3086 return NULL;
3087 assert(PyBytes_Check(name_bytes));
3088 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3089 Py_DECREF(name_bytes);
3090 if (nid == 0) {
3091 PyErr_Format(PyExc_ValueError,
3092 "unknown elliptic curve name %R", name);
3093 return NULL;
3094 }
3095 key = EC_KEY_new_by_curve_name(nid);
3096 if (key == NULL) {
3097 _setSSLError(NULL, 0, __FILE__, __LINE__);
3098 return NULL;
3099 }
3100 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3101 EC_KEY_free(key);
3102 Py_RETURN_NONE;
3103}
Antoine Pitrou501da612011-12-21 09:27:41 +01003104#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003105
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003106#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003107static int
3108_servername_callback(SSL *s, int *al, void *args)
3109{
3110 int ret;
3111 PySSLContext *ssl_ctx = (PySSLContext *) args;
3112 PySSLSocket *ssl;
3113 PyObject *servername_o;
3114 PyObject *servername_idna;
3115 PyObject *result;
3116 /* The high-level ssl.SSLSocket object */
3117 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003118 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003119#ifdef WITH_THREAD
3120 PyGILState_STATE gstate = PyGILState_Ensure();
3121#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003122
3123 if (ssl_ctx->set_hostname == NULL) {
3124 /* remove race condition in this the call back while if removing the
3125 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003126#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003127 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003128#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003129 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003130 }
3131
3132 ssl = SSL_get_app_data(s);
3133 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003134
3135 /* The servername callback expects a argument that represents the current
3136 * SSL connection and that has a .context attribute that can be changed to
3137 * identify the requested hostname. Since the official API is the Python
3138 * level API we want to pass the callback a Python level object rather than
3139 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3140 * SSLObject) that will be passed. Otherwise if there's a socket then that
3141 * will be passed. If both do not exist only then the C-level object is
3142 * passed. */
3143 if (ssl->owner)
3144 ssl_socket = PyWeakref_GetObject(ssl->owner);
3145 else if (ssl->Socket)
3146 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3147 else
3148 ssl_socket = (PyObject *) ssl;
3149
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003150 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003151 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003152 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003153
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003154 if (servername == NULL) {
3155 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3156 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003157 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003158 else {
3159 servername_o = PyBytes_FromString(servername);
3160 if (servername_o == NULL) {
3161 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3162 goto error;
3163 }
3164 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3165 if (servername_idna == NULL) {
3166 PyErr_WriteUnraisable(servername_o);
3167 Py_DECREF(servername_o);
3168 goto error;
3169 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003170 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003171 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3172 servername_idna, ssl_ctx, NULL);
3173 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003174 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003175 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003176
3177 if (result == NULL) {
3178 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3179 *al = SSL_AD_HANDSHAKE_FAILURE;
3180 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3181 }
3182 else {
3183 if (result != Py_None) {
3184 *al = (int) PyLong_AsLong(result);
3185 if (PyErr_Occurred()) {
3186 PyErr_WriteUnraisable(result);
3187 *al = SSL_AD_INTERNAL_ERROR;
3188 }
3189 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3190 }
3191 else {
3192 ret = SSL_TLSEXT_ERR_OK;
3193 }
3194 Py_DECREF(result);
3195 }
3196
Stefan Krah20d60802013-01-17 17:07:17 +01003197#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003198 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003199#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003200 return ret;
3201
3202error:
3203 Py_DECREF(ssl_socket);
3204 *al = SSL_AD_INTERNAL_ERROR;
3205 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003206#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003207 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003208#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003209 return ret;
3210}
Antoine Pitroua5963382013-03-30 16:39:00 +01003211#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003212
3213PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3214"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003215\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003216This sets a callback that will be called when a server name is provided by\n\
3217the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003218\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003219If the argument is None then the callback is disabled. The method is called\n\
3220with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003221See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003222
3223static PyObject *
3224set_servername_callback(PySSLContext *self, PyObject *args)
3225{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003226#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003227 PyObject *cb;
3228
3229 if (!PyArg_ParseTuple(args, "O", &cb))
3230 return NULL;
3231
3232 Py_CLEAR(self->set_hostname);
3233 if (cb == Py_None) {
3234 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3235 }
3236 else {
3237 if (!PyCallable_Check(cb)) {
3238 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3239 PyErr_SetString(PyExc_TypeError,
3240 "not a callable object");
3241 return NULL;
3242 }
3243 Py_INCREF(cb);
3244 self->set_hostname = cb;
3245 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3246 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3247 }
3248 Py_RETURN_NONE;
3249#else
3250 PyErr_SetString(PyExc_NotImplementedError,
3251 "The TLS extension servername callback, "
3252 "SSL_CTX_set_tlsext_servername_callback, "
3253 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003254 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003255#endif
3256}
3257
Christian Heimes9a5395a2013-06-17 15:44:12 +02003258PyDoc_STRVAR(PySSL_get_stats_doc,
3259"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3260\n\
3261Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3262CA extension and certificate revocation lists inside the context's cert\n\
3263store.\n\
3264NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3265been used at least once.");
3266
3267static PyObject *
3268cert_store_stats(PySSLContext *self)
3269{
3270 X509_STORE *store;
3271 X509_OBJECT *obj;
3272 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3273
3274 store = SSL_CTX_get_cert_store(self->ctx);
3275 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3276 obj = sk_X509_OBJECT_value(store->objs, i);
3277 switch (obj->type) {
3278 case X509_LU_X509:
3279 x509++;
3280 if (X509_check_ca(obj->data.x509)) {
3281 ca++;
3282 }
3283 break;
3284 case X509_LU_CRL:
3285 crl++;
3286 break;
3287 case X509_LU_PKEY:
3288 pkey++;
3289 break;
3290 default:
3291 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3292 * As far as I can tell they are internal states and never
3293 * stored in a cert store */
3294 break;
3295 }
3296 }
3297 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3298 "x509_ca", ca);
3299}
3300
3301PyDoc_STRVAR(PySSL_get_ca_certs_doc,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003302"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
Christian Heimes9a5395a2013-06-17 15:44:12 +02003303\n\
3304Returns a list of dicts with information of loaded CA certs. If the\n\
3305optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3306NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3307been used at least once.");
3308
3309static PyObject *
Christian Heimesf22e8e52013-11-22 02:22:51 +01003310get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
Christian Heimes9a5395a2013-06-17 15:44:12 +02003311{
Christian Heimesf22e8e52013-11-22 02:22:51 +01003312 char *kwlist[] = {"binary_form", NULL};
Christian Heimes9a5395a2013-06-17 15:44:12 +02003313 X509_STORE *store;
3314 PyObject *ci = NULL, *rlist = NULL;
3315 int i;
3316 int binary_mode = 0;
3317
Christian Heimesf22e8e52013-11-22 02:22:51 +01003318 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|p:get_ca_certs",
3319 kwlist, &binary_mode)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003320 return NULL;
3321 }
3322
3323 if ((rlist = PyList_New(0)) == NULL) {
3324 return NULL;
3325 }
3326
3327 store = SSL_CTX_get_cert_store(self->ctx);
3328 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3329 X509_OBJECT *obj;
3330 X509 *cert;
3331
3332 obj = sk_X509_OBJECT_value(store->objs, i);
3333 if (obj->type != X509_LU_X509) {
3334 /* not a x509 cert */
3335 continue;
3336 }
3337 /* CA for any purpose */
3338 cert = obj->data.x509;
3339 if (!X509_check_ca(cert)) {
3340 continue;
3341 }
3342 if (binary_mode) {
3343 ci = _certificate_to_der(cert);
3344 } else {
3345 ci = _decode_certificate(cert);
3346 }
3347 if (ci == NULL) {
3348 goto error;
3349 }
3350 if (PyList_Append(rlist, ci) == -1) {
3351 goto error;
3352 }
3353 Py_CLEAR(ci);
3354 }
3355 return rlist;
3356
3357 error:
3358 Py_XDECREF(ci);
3359 Py_XDECREF(rlist);
3360 return NULL;
3361}
3362
3363
Antoine Pitrou152efa22010-05-16 18:19:27 +00003364static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003365 {"check_hostname", (getter) get_check_hostname,
3366 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003367 {"options", (getter) get_options,
3368 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003369 {"verify_flags", (getter) get_verify_flags,
3370 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003371 {"verify_mode", (getter) get_verify_mode,
3372 (setter) set_verify_mode, NULL},
3373 {NULL}, /* sentinel */
3374};
3375
3376static struct PyMethodDef context_methods[] = {
3377 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3378 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003379 {"_wrap_bio", (PyCFunction) context_wrap_bio,
3380 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003381 {"set_ciphers", (PyCFunction) set_ciphers,
3382 METH_VARARGS, NULL},
Benjamin Petersoncca27322015-01-23 16:35:37 -05003383 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3384 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003385 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3386 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003387 {"load_cert_chain", (PyCFunction) load_cert_chain,
3388 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003389 {"load_dh_params", (PyCFunction) load_dh_params,
3390 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003391 {"load_verify_locations", (PyCFunction) load_verify_locations,
3392 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00003393 {"session_stats", (PyCFunction) session_stats,
3394 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003395 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3396 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003397#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003398 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3399 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003400#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003401 {"set_servername_callback", (PyCFunction) set_servername_callback,
3402 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02003403 {"cert_store_stats", (PyCFunction) cert_store_stats,
3404 METH_NOARGS, PySSL_get_stats_doc},
3405 {"get_ca_certs", (PyCFunction) get_ca_certs,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003406 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003407 {NULL, NULL} /* sentinel */
3408};
3409
3410static PyTypeObject PySSLContext_Type = {
3411 PyVarObject_HEAD_INIT(NULL, 0)
3412 "_ssl._SSLContext", /*tp_name*/
3413 sizeof(PySSLContext), /*tp_basicsize*/
3414 0, /*tp_itemsize*/
3415 (destructor)context_dealloc, /*tp_dealloc*/
3416 0, /*tp_print*/
3417 0, /*tp_getattr*/
3418 0, /*tp_setattr*/
3419 0, /*tp_reserved*/
3420 0, /*tp_repr*/
3421 0, /*tp_as_number*/
3422 0, /*tp_as_sequence*/
3423 0, /*tp_as_mapping*/
3424 0, /*tp_hash*/
3425 0, /*tp_call*/
3426 0, /*tp_str*/
3427 0, /*tp_getattro*/
3428 0, /*tp_setattro*/
3429 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003430 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003431 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003432 (traverseproc) context_traverse, /*tp_traverse*/
3433 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003434 0, /*tp_richcompare*/
3435 0, /*tp_weaklistoffset*/
3436 0, /*tp_iter*/
3437 0, /*tp_iternext*/
3438 context_methods, /*tp_methods*/
3439 0, /*tp_members*/
3440 context_getsetlist, /*tp_getset*/
3441 0, /*tp_base*/
3442 0, /*tp_dict*/
3443 0, /*tp_descr_get*/
3444 0, /*tp_descr_set*/
3445 0, /*tp_dictoffset*/
3446 0, /*tp_init*/
3447 0, /*tp_alloc*/
3448 context_new, /*tp_new*/
3449};
3450
3451
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003452/*
3453 * MemoryBIO objects
3454 */
3455
3456static PyObject *
3457memory_bio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3458{
3459 char *kwlist[] = {NULL};
3460 BIO *bio;
3461 PySSLMemoryBIO *self;
3462
3463 if (!PyArg_ParseTupleAndKeywords(args, kwds, ":MemoryBIO", kwlist))
3464 return NULL;
3465
3466 bio = BIO_new(BIO_s_mem());
3467 if (bio == NULL) {
3468 PyErr_SetString(PySSLErrorObject,
3469 "failed to allocate BIO");
3470 return NULL;
3471 }
3472 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3473 * just that no data is currently available. The SSL routines should retry
3474 * the read, which we can achieve by calling BIO_set_retry_read(). */
3475 BIO_set_retry_read(bio);
3476 BIO_set_mem_eof_return(bio, -1);
3477
3478 assert(type != NULL && type->tp_alloc != NULL);
3479 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3480 if (self == NULL) {
3481 BIO_free(bio);
3482 return NULL;
3483 }
3484 self->bio = bio;
3485 self->eof_written = 0;
3486
3487 return (PyObject *) self;
3488}
3489
3490static void
3491memory_bio_dealloc(PySSLMemoryBIO *self)
3492{
3493 BIO_free(self->bio);
3494 Py_TYPE(self)->tp_free(self);
3495}
3496
3497static PyObject *
3498memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3499{
3500 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3501}
3502
3503PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3504"The number of bytes pending in the memory BIO.");
3505
3506static PyObject *
3507memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3508{
3509 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3510 && self->eof_written);
3511}
3512
3513PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3514"Whether the memory BIO is at EOF.");
3515
3516static PyObject *
3517memory_bio_read(PySSLMemoryBIO *self, PyObject *args)
3518{
3519 int len = -1, avail, nbytes;
3520 PyObject *result;
3521
3522 if (!PyArg_ParseTuple(args, "|i:read", &len))
3523 return NULL;
3524
3525 avail = BIO_ctrl_pending(self->bio);
3526 if ((len < 0) || (len > avail))
3527 len = avail;
3528
3529 result = PyBytes_FromStringAndSize(NULL, len);
3530 if ((result == NULL) || (len == 0))
3531 return result;
3532
3533 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3534 /* There should never be any short reads but check anyway. */
3535 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3536 Py_DECREF(result);
3537 return NULL;
3538 }
3539
3540 return result;
3541}
3542
3543PyDoc_STRVAR(PySSL_memory_bio_read_doc,
3544"read([len]) -> bytes\n\
3545\n\
3546Read up to len bytes from the memory BIO.\n\
3547\n\
3548If len is not specified, read the entire buffer.\n\
3549If the return value is an empty bytes instance, this means either\n\
3550EOF or that no data is available. Use the \"eof\" property to\n\
3551distinguish between the two.");
3552
3553static PyObject *
3554memory_bio_write(PySSLMemoryBIO *self, PyObject *args)
3555{
3556 Py_buffer buf;
3557 int nbytes;
3558
3559 if (!PyArg_ParseTuple(args, "y*:write", &buf))
3560 return NULL;
3561
3562 if (buf.len > INT_MAX) {
3563 PyErr_Format(PyExc_OverflowError,
3564 "string longer than %d bytes", INT_MAX);
3565 goto error;
3566 }
3567
3568 if (self->eof_written) {
3569 PyErr_SetString(PySSLErrorObject,
3570 "cannot write() after write_eof()");
3571 goto error;
3572 }
3573
3574 nbytes = BIO_write(self->bio, buf.buf, buf.len);
3575 if (nbytes < 0) {
3576 _setSSLError(NULL, 0, __FILE__, __LINE__);
3577 goto error;
3578 }
3579
3580 PyBuffer_Release(&buf);
3581 return PyLong_FromLong(nbytes);
3582
3583error:
3584 PyBuffer_Release(&buf);
3585 return NULL;
3586}
3587
3588PyDoc_STRVAR(PySSL_memory_bio_write_doc,
3589"write(b) -> len\n\
3590\n\
3591Writes the bytes b into the memory BIO. Returns the number\n\
3592of bytes written.");
3593
3594static PyObject *
3595memory_bio_write_eof(PySSLMemoryBIO *self, PyObject *args)
3596{
3597 self->eof_written = 1;
3598 /* After an EOF is written, a zero return from read() should be a real EOF
3599 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3600 BIO_clear_retry_flags(self->bio);
3601 BIO_set_mem_eof_return(self->bio, 0);
3602
3603 Py_RETURN_NONE;
3604}
3605
3606PyDoc_STRVAR(PySSL_memory_bio_write_eof_doc,
3607"write_eof()\n\
3608\n\
3609Write an EOF marker to the memory BIO.\n\
3610When all data has been read, the \"eof\" property will be True.");
3611
3612static PyGetSetDef memory_bio_getsetlist[] = {
3613 {"pending", (getter) memory_bio_get_pending, NULL,
3614 PySSL_memory_bio_pending_doc},
3615 {"eof", (getter) memory_bio_get_eof, NULL,
3616 PySSL_memory_bio_eof_doc},
3617 {NULL}, /* sentinel */
3618};
3619
3620static struct PyMethodDef memory_bio_methods[] = {
3621 {"read", (PyCFunction) memory_bio_read,
3622 METH_VARARGS, PySSL_memory_bio_read_doc},
3623 {"write", (PyCFunction) memory_bio_write,
3624 METH_VARARGS, PySSL_memory_bio_write_doc},
3625 {"write_eof", (PyCFunction) memory_bio_write_eof,
3626 METH_NOARGS, PySSL_memory_bio_write_eof_doc},
3627 {NULL, NULL} /* sentinel */
3628};
3629
3630static PyTypeObject PySSLMemoryBIO_Type = {
3631 PyVarObject_HEAD_INIT(NULL, 0)
3632 "_ssl.MemoryBIO", /*tp_name*/
3633 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3634 0, /*tp_itemsize*/
3635 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3636 0, /*tp_print*/
3637 0, /*tp_getattr*/
3638 0, /*tp_setattr*/
3639 0, /*tp_reserved*/
3640 0, /*tp_repr*/
3641 0, /*tp_as_number*/
3642 0, /*tp_as_sequence*/
3643 0, /*tp_as_mapping*/
3644 0, /*tp_hash*/
3645 0, /*tp_call*/
3646 0, /*tp_str*/
3647 0, /*tp_getattro*/
3648 0, /*tp_setattro*/
3649 0, /*tp_as_buffer*/
3650 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3651 0, /*tp_doc*/
3652 0, /*tp_traverse*/
3653 0, /*tp_clear*/
3654 0, /*tp_richcompare*/
3655 0, /*tp_weaklistoffset*/
3656 0, /*tp_iter*/
3657 0, /*tp_iternext*/
3658 memory_bio_methods, /*tp_methods*/
3659 0, /*tp_members*/
3660 memory_bio_getsetlist, /*tp_getset*/
3661 0, /*tp_base*/
3662 0, /*tp_dict*/
3663 0, /*tp_descr_get*/
3664 0, /*tp_descr_set*/
3665 0, /*tp_dictoffset*/
3666 0, /*tp_init*/
3667 0, /*tp_alloc*/
3668 memory_bio_new, /*tp_new*/
3669};
3670
Antoine Pitrou152efa22010-05-16 18:19:27 +00003671
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003672/* helper routines for seeding the SSL PRNG */
3673static PyObject *
3674PySSL_RAND_add(PyObject *self, PyObject *args)
3675{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02003676 Py_buffer view;
3677 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003678 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003679 double entropy;
3680
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02003681 if (!PyArg_ParseTuple(args, "s*d:RAND_add", &view, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00003682 return NULL;
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02003683 buf = (const char *)view.buf;
3684 len = view.len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003685 do {
3686 written = Py_MIN(len, INT_MAX);
3687 RAND_add(buf, (int)written, entropy);
3688 buf += written;
3689 len -= written;
3690 } while (len);
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02003691 PyBuffer_Release(&view);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003692 Py_INCREF(Py_None);
3693 return Py_None;
3694}
3695
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003696PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003697"RAND_add(string, entropy)\n\
3698\n\
3699Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003700bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003701
3702static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003703PySSL_RAND(int len, int pseudo)
3704{
3705 int ok;
3706 PyObject *bytes;
3707 unsigned long err;
3708 const char *errstr;
3709 PyObject *v;
3710
Victor Stinner1e81a392013-12-19 16:47:04 +01003711 if (len < 0) {
3712 PyErr_SetString(PyExc_ValueError, "num must be positive");
3713 return NULL;
3714 }
3715
Victor Stinner99c8b162011-05-24 12:05:19 +02003716 bytes = PyBytes_FromStringAndSize(NULL, len);
3717 if (bytes == NULL)
3718 return NULL;
3719 if (pseudo) {
3720 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3721 if (ok == 0 || ok == 1)
3722 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3723 }
3724 else {
3725 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3726 if (ok == 1)
3727 return bytes;
3728 }
3729 Py_DECREF(bytes);
3730
3731 err = ERR_get_error();
3732 errstr = ERR_reason_error_string(err);
3733 v = Py_BuildValue("(ks)", err, errstr);
3734 if (v != NULL) {
3735 PyErr_SetObject(PySSLErrorObject, v);
3736 Py_DECREF(v);
3737 }
3738 return NULL;
3739}
3740
3741static PyObject *
3742PySSL_RAND_bytes(PyObject *self, PyObject *args)
3743{
3744 int len;
3745 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3746 return NULL;
3747 return PySSL_RAND(len, 0);
3748}
3749
3750PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3751"RAND_bytes(n) -> bytes\n\
3752\n\
3753Generate n cryptographically strong pseudo-random bytes.");
3754
3755static PyObject *
3756PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3757{
3758 int len;
3759 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3760 return NULL;
3761 return PySSL_RAND(len, 1);
3762}
3763
3764PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3765"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3766\n\
3767Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3768generated are cryptographically strong.");
3769
3770static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003771PySSL_RAND_status(PyObject *self)
3772{
Christian Heimes217cfd12007-12-02 14:31:20 +00003773 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003774}
3775
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003776PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003777"RAND_status() -> 0 or 1\n\
3778\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003779Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3780It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3781using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003782
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003783#ifdef HAVE_RAND_EGD
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003784static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003785PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003786{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003787 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003788 int bytes;
3789
Jesus Ceac8754a12012-09-11 02:00:58 +02003790 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003791 PyUnicode_FSConverter, &path))
3792 return NULL;
3793
3794 bytes = RAND_egd(PyBytes_AsString(path));
3795 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003796 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003797 PyErr_SetString(PySSLErrorObject,
3798 "EGD connection failed or EGD did not return "
3799 "enough data to seed the PRNG");
3800 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003801 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003802 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003803}
3804
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003805PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003806"RAND_egd(path) -> bytes\n\
3807\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003808Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3809Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003810fails or if it does not provide enough data to seed PRNG.");
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003811#endif /* HAVE_RAND_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003812
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003813
Christian Heimes6d7ad132013-06-09 18:02:55 +02003814PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3815"get_default_verify_paths() -> tuple\n\
3816\n\
3817Return search paths and environment vars that are used by SSLContext's\n\
3818set_default_verify_paths() to load default CAs. The values are\n\
3819'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3820
3821static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003822PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003823{
3824 PyObject *ofile_env = NULL;
3825 PyObject *ofile = NULL;
3826 PyObject *odir_env = NULL;
3827 PyObject *odir = NULL;
3828
3829#define convert(info, target) { \
3830 const char *tmp = (info); \
3831 target = NULL; \
3832 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3833 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3834 target = PyBytes_FromString(tmp); } \
3835 if (!target) goto error; \
3836 } while(0)
3837
3838 convert(X509_get_default_cert_file_env(), ofile_env);
3839 convert(X509_get_default_cert_file(), ofile);
3840 convert(X509_get_default_cert_dir_env(), odir_env);
3841 convert(X509_get_default_cert_dir(), odir);
3842#undef convert
3843
Christian Heimes200bb1b2013-06-14 15:14:29 +02003844 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003845
3846 error:
3847 Py_XDECREF(ofile_env);
3848 Py_XDECREF(ofile);
3849 Py_XDECREF(odir_env);
3850 Py_XDECREF(odir);
3851 return NULL;
3852}
3853
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003854static PyObject*
3855asn1obj2py(ASN1_OBJECT *obj)
3856{
3857 int nid;
3858 const char *ln, *sn;
3859 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02003860 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003861
3862 nid = OBJ_obj2nid(obj);
3863 if (nid == NID_undef) {
3864 PyErr_Format(PyExc_ValueError, "Unknown object");
3865 return NULL;
3866 }
3867 sn = OBJ_nid2sn(nid);
3868 ln = OBJ_nid2ln(nid);
3869 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3870 if (buflen < 0) {
3871 _setSSLError(NULL, 0, __FILE__, __LINE__);
3872 return NULL;
3873 }
3874 if (buflen) {
3875 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3876 } else {
3877 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3878 }
3879}
3880
3881PyDoc_STRVAR(PySSL_txt2obj_doc,
3882"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3883\n\
3884Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3885objects are looked up by OID. With name=True short and long name are also\n\
3886matched.");
3887
3888static PyObject*
3889PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3890{
3891 char *kwlist[] = {"txt", "name", NULL};
3892 PyObject *result = NULL;
3893 char *txt;
3894 int name = 0;
3895 ASN1_OBJECT *obj;
3896
3897 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3898 kwlist, &txt, &name)) {
3899 return NULL;
3900 }
3901 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3902 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003903 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003904 return NULL;
3905 }
3906 result = asn1obj2py(obj);
3907 ASN1_OBJECT_free(obj);
3908 return result;
3909}
3910
3911PyDoc_STRVAR(PySSL_nid2obj_doc,
3912"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3913\n\
3914Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3915
3916static PyObject*
3917PySSL_nid2obj(PyObject *self, PyObject *args)
3918{
3919 PyObject *result = NULL;
3920 int nid;
3921 ASN1_OBJECT *obj;
3922
3923 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3924 return NULL;
3925 }
3926 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003927 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003928 return NULL;
3929 }
3930 obj = OBJ_nid2obj(nid);
3931 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003932 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003933 return NULL;
3934 }
3935 result = asn1obj2py(obj);
3936 ASN1_OBJECT_free(obj);
3937 return result;
3938}
3939
Christian Heimes46bebee2013-06-09 19:03:31 +02003940#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003941
3942static PyObject*
3943certEncodingType(DWORD encodingType)
3944{
3945 static PyObject *x509_asn = NULL;
3946 static PyObject *pkcs_7_asn = NULL;
3947
3948 if (x509_asn == NULL) {
3949 x509_asn = PyUnicode_InternFromString("x509_asn");
3950 if (x509_asn == NULL)
3951 return NULL;
3952 }
3953 if (pkcs_7_asn == NULL) {
3954 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
3955 if (pkcs_7_asn == NULL)
3956 return NULL;
3957 }
3958 switch(encodingType) {
3959 case X509_ASN_ENCODING:
3960 Py_INCREF(x509_asn);
3961 return x509_asn;
3962 case PKCS_7_ASN_ENCODING:
3963 Py_INCREF(pkcs_7_asn);
3964 return pkcs_7_asn;
3965 default:
3966 return PyLong_FromLong(encodingType);
3967 }
3968}
3969
3970static PyObject*
3971parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3972{
3973 CERT_ENHKEY_USAGE *usage;
3974 DWORD size, error, i;
3975 PyObject *retval;
3976
3977 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3978 error = GetLastError();
3979 if (error == CRYPT_E_NOT_FOUND) {
3980 Py_RETURN_TRUE;
3981 }
3982 return PyErr_SetFromWindowsErr(error);
3983 }
3984
3985 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3986 if (usage == NULL) {
3987 return PyErr_NoMemory();
3988 }
3989
3990 /* Now get the actual enhanced usage property */
3991 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3992 PyMem_Free(usage);
3993 error = GetLastError();
3994 if (error == CRYPT_E_NOT_FOUND) {
3995 Py_RETURN_TRUE;
3996 }
3997 return PyErr_SetFromWindowsErr(error);
3998 }
3999 retval = PySet_New(NULL);
4000 if (retval == NULL) {
4001 goto error;
4002 }
4003 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4004 if (usage->rgpszUsageIdentifier[i]) {
4005 PyObject *oid;
4006 int err;
4007 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4008 if (oid == NULL) {
4009 Py_CLEAR(retval);
4010 goto error;
4011 }
4012 err = PySet_Add(retval, oid);
4013 Py_DECREF(oid);
4014 if (err == -1) {
4015 Py_CLEAR(retval);
4016 goto error;
4017 }
4018 }
4019 }
4020 error:
4021 PyMem_Free(usage);
4022 return retval;
4023}
4024
4025PyDoc_STRVAR(PySSL_enum_certificates_doc,
4026"enum_certificates(store_name) -> []\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02004027\n\
4028Retrieve certificates from Windows' cert store. store_name may be one of\n\
4029'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
Christian Heimes44109d72013-11-22 01:51:30 +01004030The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02004031encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
Christian Heimes44109d72013-11-22 01:51:30 +01004032PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
4033boolean True.");
Bill Janssen40a0f662008-08-12 16:56:25 +00004034
Christian Heimes46bebee2013-06-09 19:03:31 +02004035static PyObject *
Christian Heimes44109d72013-11-22 01:51:30 +01004036PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes46bebee2013-06-09 19:03:31 +02004037{
Christian Heimes44109d72013-11-22 01:51:30 +01004038 char *kwlist[] = {"store_name", NULL};
Christian Heimes46bebee2013-06-09 19:03:31 +02004039 char *store_name;
Christian Heimes46bebee2013-06-09 19:03:31 +02004040 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004041 PCCERT_CONTEXT pCertCtx = NULL;
4042 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004043 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004044
Christian Heimes44109d72013-11-22 01:51:30 +01004045 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_certificates",
4046 kwlist, &store_name)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004047 return NULL;
4048 }
Christian Heimes44109d72013-11-22 01:51:30 +01004049 result = PyList_New(0);
4050 if (result == NULL) {
4051 return NULL;
4052 }
4053 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4054 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004055 Py_DECREF(result);
4056 return PyErr_SetFromWindowsErr(GetLastError());
4057 }
4058
Christian Heimes44109d72013-11-22 01:51:30 +01004059 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4060 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4061 pCertCtx->cbCertEncoded);
4062 if (!cert) {
4063 Py_CLEAR(result);
4064 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004065 }
Christian Heimes44109d72013-11-22 01:51:30 +01004066 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4067 Py_CLEAR(result);
4068 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004069 }
Christian Heimes44109d72013-11-22 01:51:30 +01004070 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4071 if (keyusage == Py_True) {
4072 Py_DECREF(keyusage);
4073 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004074 }
Christian Heimes44109d72013-11-22 01:51:30 +01004075 if (keyusage == NULL) {
4076 Py_CLEAR(result);
4077 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004078 }
Christian Heimes44109d72013-11-22 01:51:30 +01004079 if ((tup = PyTuple_New(3)) == NULL) {
4080 Py_CLEAR(result);
4081 break;
4082 }
4083 PyTuple_SET_ITEM(tup, 0, cert);
4084 cert = NULL;
4085 PyTuple_SET_ITEM(tup, 1, enc);
4086 enc = NULL;
4087 PyTuple_SET_ITEM(tup, 2, keyusage);
4088 keyusage = NULL;
4089 if (PyList_Append(result, tup) < 0) {
4090 Py_CLEAR(result);
4091 break;
4092 }
4093 Py_CLEAR(tup);
4094 }
4095 if (pCertCtx) {
4096 /* loop ended with an error, need to clean up context manually */
4097 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004098 }
4099
4100 /* In error cases cert, enc and tup may not be NULL */
4101 Py_XDECREF(cert);
4102 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004103 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004104 Py_XDECREF(tup);
4105
4106 if (!CertCloseStore(hStore, 0)) {
4107 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004108 Py_XDECREF(result);
4109 return PyErr_SetFromWindowsErr(GetLastError());
4110 }
4111 return result;
4112}
4113
4114PyDoc_STRVAR(PySSL_enum_crls_doc,
4115"enum_crls(store_name) -> []\n\
4116\n\
4117Retrieve CRLs from Windows' cert store. store_name may be one of\n\
4118'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
4119The function returns a list of (bytes, encoding_type) tuples. The\n\
4120encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
4121PKCS_7_ASN_ENCODING.");
4122
4123static PyObject *
4124PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
4125{
4126 char *kwlist[] = {"store_name", NULL};
4127 char *store_name;
4128 HCERTSTORE hStore = NULL;
4129 PCCRL_CONTEXT pCrlCtx = NULL;
4130 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4131 PyObject *result = NULL;
4132
4133 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_crls",
4134 kwlist, &store_name)) {
4135 return NULL;
4136 }
4137 result = PyList_New(0);
4138 if (result == NULL) {
4139 return NULL;
4140 }
4141 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4142 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004143 Py_DECREF(result);
4144 return PyErr_SetFromWindowsErr(GetLastError());
4145 }
Christian Heimes44109d72013-11-22 01:51:30 +01004146
4147 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4148 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4149 pCrlCtx->cbCrlEncoded);
4150 if (!crl) {
4151 Py_CLEAR(result);
4152 break;
4153 }
4154 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4155 Py_CLEAR(result);
4156 break;
4157 }
4158 if ((tup = PyTuple_New(2)) == NULL) {
4159 Py_CLEAR(result);
4160 break;
4161 }
4162 PyTuple_SET_ITEM(tup, 0, crl);
4163 crl = NULL;
4164 PyTuple_SET_ITEM(tup, 1, enc);
4165 enc = NULL;
4166
4167 if (PyList_Append(result, tup) < 0) {
4168 Py_CLEAR(result);
4169 break;
4170 }
4171 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004172 }
Christian Heimes44109d72013-11-22 01:51:30 +01004173 if (pCrlCtx) {
4174 /* loop ended with an error, need to clean up context manually */
4175 CertFreeCRLContext(pCrlCtx);
4176 }
4177
4178 /* In error cases cert, enc and tup may not be NULL */
4179 Py_XDECREF(crl);
4180 Py_XDECREF(enc);
4181 Py_XDECREF(tup);
4182
4183 if (!CertCloseStore(hStore, 0)) {
4184 /* This error case might shadow another exception.*/
4185 Py_XDECREF(result);
4186 return PyErr_SetFromWindowsErr(GetLastError());
4187 }
4188 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004189}
Christian Heimes44109d72013-11-22 01:51:30 +01004190
4191#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004192
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004193/* List of functions exported by this module. */
4194
4195static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004196 {"_test_decode_cert", PySSL_test_decode_certificate,
4197 METH_VARARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004198 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
4199 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02004200 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
4201 PySSL_RAND_bytes_doc},
4202 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
4203 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerbeeb5122014-11-28 13:28:25 +01004204#ifdef HAVE_RAND_EGD
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004205 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004206 PySSL_RAND_egd_doc},
Victor Stinnerbeeb5122014-11-28 13:28:25 +01004207#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004208 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
4209 PySSL_RAND_status_doc},
Christian Heimes200bb1b2013-06-14 15:14:29 +02004210 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02004211 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02004212#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004213 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
4214 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
4215 {"enum_crls", (PyCFunction)PySSL_enum_crls,
4216 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02004217#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004218 {"txt2obj", (PyCFunction)PySSL_txt2obj,
4219 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
4220 {"nid2obj", (PyCFunction)PySSL_nid2obj,
4221 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004222 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004223};
4224
4225
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004226#ifdef WITH_THREAD
4227
4228/* an implementation of OpenSSL threading operations in terms
4229 of the Python C thread library */
4230
4231static PyThread_type_lock *_ssl_locks = NULL;
4232
Christian Heimes4d98ca92013-08-19 17:36:29 +02004233#if OPENSSL_VERSION_NUMBER >= 0x10000000
4234/* use new CRYPTO_THREADID API. */
4235static void
4236_ssl_threadid_callback(CRYPTO_THREADID *id)
4237{
4238 CRYPTO_THREADID_set_numeric(id,
4239 (unsigned long)PyThread_get_thread_ident());
4240}
4241#else
4242/* deprecated CRYPTO_set_id_callback() API. */
4243static unsigned long
4244_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004245 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004246}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004247#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004248
Bill Janssen6e027db2007-11-15 22:23:56 +00004249static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004250 (int mode, int n, const char *file, int line) {
4251 /* this function is needed to perform locking on shared data
4252 structures. (Note that OpenSSL uses a number of global data
4253 structures that will be implicitly shared whenever multiple
4254 threads use OpenSSL.) Multi-threaded applications will
4255 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004256
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004257 locking_function() must be able to handle up to
4258 CRYPTO_num_locks() different mutex locks. It sets the n-th
4259 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004260
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004261 file and line are the file number of the function setting the
4262 lock. They can be useful for debugging.
4263 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004264
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004265 if ((_ssl_locks == NULL) ||
4266 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4267 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004268
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004269 if (mode & CRYPTO_LOCK) {
4270 PyThread_acquire_lock(_ssl_locks[n], 1);
4271 } else {
4272 PyThread_release_lock(_ssl_locks[n]);
4273 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004274}
4275
4276static int _setup_ssl_threads(void) {
4277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004278 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004279
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004280 if (_ssl_locks == NULL) {
4281 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004282 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4283 if (_ssl_locks == NULL) {
4284 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004285 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004286 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004287 memset(_ssl_locks, 0,
4288 sizeof(PyThread_type_lock) * _ssl_locks_count);
4289 for (i = 0; i < _ssl_locks_count; i++) {
4290 _ssl_locks[i] = PyThread_allocate_lock();
4291 if (_ssl_locks[i] == NULL) {
4292 unsigned int j;
4293 for (j = 0; j < i; j++) {
4294 PyThread_free_lock(_ssl_locks[j]);
4295 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004296 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004297 return 0;
4298 }
4299 }
4300 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004301#if OPENSSL_VERSION_NUMBER >= 0x10000000
4302 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4303#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004304 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004305#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004306 }
4307 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004308}
4309
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004310#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004311
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004312PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004313"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004314for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004315
Martin v. Löwis1a214512008-06-11 05:26:20 +00004316
4317static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004318 PyModuleDef_HEAD_INIT,
4319 "_ssl",
4320 module_doc,
4321 -1,
4322 PySSL_methods,
4323 NULL,
4324 NULL,
4325 NULL,
4326 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004327};
4328
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004329
4330static void
4331parse_openssl_version(unsigned long libver,
4332 unsigned int *major, unsigned int *minor,
4333 unsigned int *fix, unsigned int *patch,
4334 unsigned int *status)
4335{
4336 *status = libver & 0xF;
4337 libver >>= 4;
4338 *patch = libver & 0xFF;
4339 libver >>= 8;
4340 *fix = libver & 0xFF;
4341 libver >>= 8;
4342 *minor = libver & 0xFF;
4343 libver >>= 8;
4344 *major = libver & 0xFF;
4345}
4346
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004347PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004348PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004349{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004350 PyObject *m, *d, *r;
4351 unsigned long libver;
4352 unsigned int major, minor, fix, patch, status;
4353 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004354 struct py_ssl_error_code *errcode;
4355 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004356
Antoine Pitrou152efa22010-05-16 18:19:27 +00004357 if (PyType_Ready(&PySSLContext_Type) < 0)
4358 return NULL;
4359 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004360 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004361 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4362 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004363
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004364 m = PyModule_Create(&_sslmodule);
4365 if (m == NULL)
4366 return NULL;
4367 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004368
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004369 /* Load _socket module and its C API */
4370 socket_api = PySocketModule_ImportModuleAndAPI();
4371 if (!socket_api)
4372 return NULL;
4373 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004374
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004375 /* Init OpenSSL */
4376 SSL_load_error_strings();
4377 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004378#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004379 /* note that this will start threading if not already started */
4380 if (!_setup_ssl_threads()) {
4381 return NULL;
4382 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004383#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004384 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004385
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004386 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004387 sslerror_type_slots[0].pfunc = PyExc_OSError;
4388 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004389 if (PySSLErrorObject == NULL)
4390 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004391
Antoine Pitrou41032a62011-10-27 23:56:55 +02004392 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4393 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4394 PySSLErrorObject, NULL);
4395 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4396 "ssl.SSLWantReadError", SSLWantReadError_doc,
4397 PySSLErrorObject, NULL);
4398 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4399 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4400 PySSLErrorObject, NULL);
4401 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4402 "ssl.SSLSyscallError", SSLSyscallError_doc,
4403 PySSLErrorObject, NULL);
4404 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4405 "ssl.SSLEOFError", SSLEOFError_doc,
4406 PySSLErrorObject, NULL);
4407 if (PySSLZeroReturnErrorObject == NULL
4408 || PySSLWantReadErrorObject == NULL
4409 || PySSLWantWriteErrorObject == NULL
4410 || PySSLSyscallErrorObject == NULL
4411 || PySSLEOFErrorObject == NULL)
4412 return NULL;
4413 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4414 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4415 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4416 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4417 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4418 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004419 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004420 if (PyDict_SetItemString(d, "_SSLContext",
4421 (PyObject *)&PySSLContext_Type) != 0)
4422 return NULL;
4423 if (PyDict_SetItemString(d, "_SSLSocket",
4424 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004425 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004426 if (PyDict_SetItemString(d, "MemoryBIO",
4427 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4428 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004429 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4430 PY_SSL_ERROR_ZERO_RETURN);
4431 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4432 PY_SSL_ERROR_WANT_READ);
4433 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4434 PY_SSL_ERROR_WANT_WRITE);
4435 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4436 PY_SSL_ERROR_WANT_X509_LOOKUP);
4437 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4438 PY_SSL_ERROR_SYSCALL);
4439 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4440 PY_SSL_ERROR_SSL);
4441 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4442 PY_SSL_ERROR_WANT_CONNECT);
4443 /* non ssl.h errorcodes */
4444 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4445 PY_SSL_ERROR_EOF);
4446 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4447 PY_SSL_ERROR_INVALID_ERROR_CODE);
4448 /* cert requirements */
4449 PyModule_AddIntConstant(m, "CERT_NONE",
4450 PY_SSL_CERT_NONE);
4451 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4452 PY_SSL_CERT_OPTIONAL);
4453 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4454 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004455 /* CRL verification for verification_flags */
4456 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4457 0);
4458 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4459 X509_V_FLAG_CRL_CHECK);
4460 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4461 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4462 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4463 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05004464#ifdef X509_V_FLAG_TRUSTED_FIRST
4465 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4466 X509_V_FLAG_TRUSTED_FIRST);
4467#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004468
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004469 /* Alert Descriptions from ssl.h */
4470 /* note RESERVED constants no longer intended for use have been removed */
4471 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4472
4473#define ADD_AD_CONSTANT(s) \
4474 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4475 SSL_AD_##s)
4476
4477 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4478 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4479 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4480 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4481 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4482 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4483 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4484 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4485 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4486 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4487 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4488 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4489 ADD_AD_CONSTANT(UNKNOWN_CA);
4490 ADD_AD_CONSTANT(ACCESS_DENIED);
4491 ADD_AD_CONSTANT(DECODE_ERROR);
4492 ADD_AD_CONSTANT(DECRYPT_ERROR);
4493 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4494 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4495 ADD_AD_CONSTANT(INTERNAL_ERROR);
4496 ADD_AD_CONSTANT(USER_CANCELLED);
4497 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004498 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004499#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4500 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4501#endif
4502#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4503 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4504#endif
4505#ifdef SSL_AD_UNRECOGNIZED_NAME
4506 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4507#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004508#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4509 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4510#endif
4511#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4512 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4513#endif
4514#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4515 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4516#endif
4517
4518#undef ADD_AD_CONSTANT
4519
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004520 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004521#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004522 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4523 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004524#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004525#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004526 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4527 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004528#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004529 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4530 PY_SSL_VERSION_SSL23);
4531 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4532 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004533#if HAVE_TLSv1_2
4534 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4535 PY_SSL_VERSION_TLS1_1);
4536 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4537 PY_SSL_VERSION_TLS1_2);
4538#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004539
Antoine Pitroub5218772010-05-21 09:56:06 +00004540 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004541 PyModule_AddIntConstant(m, "OP_ALL",
4542 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004543 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4544 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4545 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004546#if HAVE_TLSv1_2
4547 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4548 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4549#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004550 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4551 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004552 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004553#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004554 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004555#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004556#ifdef SSL_OP_NO_COMPRESSION
4557 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4558 SSL_OP_NO_COMPRESSION);
4559#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004560
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004561#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004562 r = Py_True;
4563#else
4564 r = Py_False;
4565#endif
4566 Py_INCREF(r);
4567 PyModule_AddObject(m, "HAS_SNI", r);
4568
Antoine Pitroud6494802011-07-21 01:11:30 +02004569 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004570 Py_INCREF(r);
4571 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4572
Antoine Pitrou501da612011-12-21 09:27:41 +01004573#ifdef OPENSSL_NO_ECDH
4574 r = Py_False;
4575#else
4576 r = Py_True;
4577#endif
4578 Py_INCREF(r);
4579 PyModule_AddObject(m, "HAS_ECDH", r);
4580
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004581#ifdef OPENSSL_NPN_NEGOTIATED
4582 r = Py_True;
4583#else
4584 r = Py_False;
4585#endif
4586 Py_INCREF(r);
4587 PyModule_AddObject(m, "HAS_NPN", r);
4588
Benjamin Petersoncca27322015-01-23 16:35:37 -05004589#ifdef HAVE_ALPN
4590 r = Py_True;
4591#else
4592 r = Py_False;
4593#endif
4594 Py_INCREF(r);
4595 PyModule_AddObject(m, "HAS_ALPN", r);
4596
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004597 /* Mappings for error codes */
4598 err_codes_to_names = PyDict_New();
4599 err_names_to_codes = PyDict_New();
4600 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4601 return NULL;
4602 errcode = error_codes;
4603 while (errcode->mnemonic != NULL) {
4604 PyObject *mnemo, *key;
4605 mnemo = PyUnicode_FromString(errcode->mnemonic);
4606 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4607 if (mnemo == NULL || key == NULL)
4608 return NULL;
4609 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4610 return NULL;
4611 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4612 return NULL;
4613 Py_DECREF(key);
4614 Py_DECREF(mnemo);
4615 errcode++;
4616 }
4617 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4618 return NULL;
4619 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4620 return NULL;
4621
4622 lib_codes_to_names = PyDict_New();
4623 if (lib_codes_to_names == NULL)
4624 return NULL;
4625 libcode = library_codes;
4626 while (libcode->library != NULL) {
4627 PyObject *mnemo, *key;
4628 key = PyLong_FromLong(libcode->code);
4629 mnemo = PyUnicode_FromString(libcode->library);
4630 if (key == NULL || mnemo == NULL)
4631 return NULL;
4632 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4633 return NULL;
4634 Py_DECREF(key);
4635 Py_DECREF(mnemo);
4636 libcode++;
4637 }
4638 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4639 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004640
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004641 /* OpenSSL version */
4642 /* SSLeay() gives us the version of the library linked against,
4643 which could be different from the headers version.
4644 */
4645 libver = SSLeay();
4646 r = PyLong_FromUnsignedLong(libver);
4647 if (r == NULL)
4648 return NULL;
4649 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4650 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004651 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004652 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4653 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4654 return NULL;
4655 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4656 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4657 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004658
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004659 libver = OPENSSL_VERSION_NUMBER;
4660 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4661 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4662 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4663 return NULL;
4664
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004665 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004666}