blob: f0f362c117148a0cdfefdedca45c1bfca3d90597 [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 */
113#if OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
114# 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 */
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200537 if (sock && sock->sock_timeout >= 0.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 */
579 nonblocking = (sock->sock_timeout >= 0.0);
580 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) */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001619 if ((s == NULL) || (s->sock_timeout == 0.0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001620 return SOCKET_IS_NONBLOCKING;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001621 else if (s->sock_timeout < 0.0)
1622 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 */
1639 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1640 PySSL_BEGIN_ALLOW_THREADS
1641 rc = poll(&pollfd, 1, timeout);
1642 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001643
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001644 goto normal_return;
1645 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001646#endif
1647
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001648 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001649 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001650 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001651
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001652 /* Construct the arguments to select */
1653 tv.tv_sec = (int)s->sock_timeout;
1654 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1655 FD_ZERO(&fds);
1656 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001657
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001658 /* See if the socket is ready */
1659 PySSL_BEGIN_ALLOW_THREADS
1660 if (writing)
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001661 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1662 NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001663 else
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001664 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1665 &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001666 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001667
Bill Janssen6e027db2007-11-15 22:23:56 +00001668#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001669normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001670#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001671 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1672 (when we are able to write or when there's something to read) */
1673 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001674}
1675
Antoine Pitrou152efa22010-05-16 18:19:27 +00001676static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001677{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001678 Py_buffer buf;
1679 int len;
1680 int sockstate;
1681 int err;
1682 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001683 PySocketSockObject *sock = GET_SOCKET(self);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001684
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001685 if (sock != NULL) {
1686 if (((PyObject*)sock) == Py_None) {
1687 _setSSLError("Underlying socket connection gone",
1688 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1689 return NULL;
1690 }
1691 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001692 }
1693
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001694 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001695 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001696 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001697 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001698
Victor Stinner6efa9652013-06-25 00:42:31 +02001699 if (buf.len > INT_MAX) {
1700 PyErr_Format(PyExc_OverflowError,
1701 "string longer than %d bytes", INT_MAX);
1702 goto error;
1703 }
1704
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001705 if (sock != NULL) {
1706 /* just in case the blocking state of the socket has been changed */
1707 nonblocking = (sock->sock_timeout >= 0.0);
1708 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1709 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1710 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001711
1712 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1713 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001714 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001715 "The write operation timed out");
1716 goto error;
1717 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1718 PyErr_SetString(PySSLErrorObject,
1719 "Underlying socket has been closed.");
1720 goto error;
1721 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1722 PyErr_SetString(PySSLErrorObject,
1723 "Underlying socket too large for select().");
1724 goto error;
1725 }
1726 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001727 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001728 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001729 err = SSL_get_error(self->ssl, len);
1730 PySSL_END_ALLOW_THREADS
1731 if (PyErr_CheckSignals()) {
1732 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001733 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001734 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001735 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001736 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001737 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001738 } else {
1739 sockstate = SOCKET_OPERATION_OK;
1740 }
1741 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001742 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001743 "The write operation timed out");
1744 goto error;
1745 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1746 PyErr_SetString(PySSLErrorObject,
1747 "Underlying socket has been closed.");
1748 goto error;
1749 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1750 break;
1751 }
1752 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001753
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001754 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001755 PyBuffer_Release(&buf);
1756 if (len > 0)
1757 return PyLong_FromLong(len);
1758 else
1759 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001760
1761error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001762 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001763 PyBuffer_Release(&buf);
1764 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001765}
1766
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001767PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001768"write(s) -> len\n\
1769\n\
1770Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001771of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001772
Antoine Pitrou152efa22010-05-16 18:19:27 +00001773static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001774{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001775 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001776
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001777 PySSL_BEGIN_ALLOW_THREADS
1778 count = SSL_pending(self->ssl);
1779 PySSL_END_ALLOW_THREADS
1780 if (count < 0)
1781 return PySSL_SetError(self, count, __FILE__, __LINE__);
1782 else
1783 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001784}
1785
1786PyDoc_STRVAR(PySSL_SSLpending_doc,
1787"pending() -> count\n\
1788\n\
1789Returns the number of already decrypted bytes available for read,\n\
1790pending on the connection.\n");
1791
Antoine Pitrou152efa22010-05-16 18:19:27 +00001792static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001793{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001794 PyObject *dest = NULL;
1795 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001796 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001797 int len, count;
1798 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001799 int sockstate;
1800 int err;
1801 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001802 PySocketSockObject *sock = GET_SOCKET(self);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001803
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001804 if (sock != NULL) {
1805 if (((PyObject*)sock) == Py_None) {
1806 _setSSLError("Underlying socket connection gone",
1807 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1808 return NULL;
1809 }
1810 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001811 }
1812
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001813 buf.obj = NULL;
1814 buf.buf = NULL;
1815 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001816 goto error;
1817
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001818 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1819 dest = PyBytes_FromStringAndSize(NULL, len);
1820 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001821 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001822 mem = PyBytes_AS_STRING(dest);
1823 }
1824 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001826 mem = buf.buf;
1827 if (len <= 0 || len > buf.len) {
1828 len = (int) buf.len;
1829 if (buf.len != len) {
1830 PyErr_SetString(PyExc_OverflowError,
1831 "maximum length can't fit in a C 'int'");
1832 goto error;
1833 }
1834 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001835 }
1836
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001837 if (sock != NULL) {
1838 /* just in case the blocking state of the socket has been changed */
1839 nonblocking = (sock->sock_timeout >= 0.0);
1840 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1841 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1842 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001843
1844 /* first check if there are bytes ready to be read */
1845 PySSL_BEGIN_ALLOW_THREADS
1846 count = SSL_pending(self->ssl);
1847 PySSL_END_ALLOW_THREADS
1848
1849 if (!count) {
1850 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1851 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001852 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001853 "The read operation timed out");
1854 goto error;
1855 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1856 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001857 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001858 goto error;
1859 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1860 count = 0;
1861 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001862 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001863 }
1864 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001865 PySSL_BEGIN_ALLOW_THREADS
1866 count = SSL_read(self->ssl, mem, len);
1867 err = SSL_get_error(self->ssl, count);
1868 PySSL_END_ALLOW_THREADS
1869 if (PyErr_CheckSignals())
1870 goto error;
1871 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001872 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001873 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001874 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001875 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1876 (SSL_get_shutdown(self->ssl) ==
1877 SSL_RECEIVED_SHUTDOWN))
1878 {
1879 count = 0;
1880 goto done;
1881 } else {
1882 sockstate = SOCKET_OPERATION_OK;
1883 }
1884 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001885 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001886 "The read operation timed out");
1887 goto error;
1888 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1889 break;
1890 }
1891 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1892 if (count <= 0) {
1893 PySSL_SetError(self, count, __FILE__, __LINE__);
1894 goto error;
1895 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001896
1897done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001898 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001899 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001900 _PyBytes_Resize(&dest, count);
1901 return dest;
1902 }
1903 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001904 PyBuffer_Release(&buf);
1905 return PyLong_FromLong(count);
1906 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001907
1908error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001909 Py_XDECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001910 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001911 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001912 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001913 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001914 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001915}
1916
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001917PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001918"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001919\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001920Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001921
Antoine Pitrou152efa22010-05-16 18:19:27 +00001922static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001923{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001924 int err, ssl_err, sockstate, nonblocking;
1925 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001926 PySocketSockObject *sock = GET_SOCKET(self);
Bill Janssen40a0f662008-08-12 16:56:25 +00001927
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001928 if (sock != NULL) {
1929 /* Guard against closed socket */
1930 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1931 _setSSLError("Underlying socket connection gone",
1932 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1933 return NULL;
1934 }
1935 Py_INCREF(sock);
1936
1937 /* Just in case the blocking state of the socket has been changed */
1938 nonblocking = (sock->sock_timeout >= 0.0);
1939 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1940 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001941 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001942
1943 while (1) {
1944 PySSL_BEGIN_ALLOW_THREADS
1945 /* Disable read-ahead so that unwrap can work correctly.
1946 * Otherwise OpenSSL might read in too much data,
1947 * eating clear text data that happens to be
1948 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001949 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001950 * function is used and the shutdown_seen_zero != 0
1951 * condition is met.
1952 */
1953 if (self->shutdown_seen_zero)
1954 SSL_set_read_ahead(self->ssl, 0);
1955 err = SSL_shutdown(self->ssl);
1956 PySSL_END_ALLOW_THREADS
1957 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1958 if (err > 0)
1959 break;
1960 if (err == 0) {
1961 /* Don't loop endlessly; instead preserve legacy
1962 behaviour of trying SSL_shutdown() only twice.
1963 This looks necessary for OpenSSL < 0.9.8m */
1964 if (++zeros > 1)
1965 break;
1966 /* Shutdown was sent, now try receiving */
1967 self->shutdown_seen_zero = 1;
1968 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001969 }
1970
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001971 /* Possibly retry shutdown until timeout or failure */
1972 ssl_err = SSL_get_error(self->ssl, err);
1973 if (ssl_err == SSL_ERROR_WANT_READ)
1974 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1975 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1976 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1977 else
1978 break;
1979 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1980 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001981 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001982 "The read operation timed out");
1983 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001984 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001985 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001986 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001987 }
1988 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1989 PyErr_SetString(PySSLErrorObject,
1990 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001991 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001992 }
1993 else if (sockstate != SOCKET_OPERATION_OK)
1994 /* Retain the SSL error code */
1995 break;
1996 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001997
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001998 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001999 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002000 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002001 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002002 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002003 /* It's already INCREF'ed */
2004 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002005 else
2006 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002007
2008error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002009 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002010 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002011}
2012
2013PyDoc_STRVAR(PySSL_SSLshutdown_doc,
2014"shutdown(s) -> socket\n\
2015\n\
2016Does the SSL shutdown handshake with the remote end, and returns\n\
2017the underlying socket object.");
2018
Antoine Pitroud6494802011-07-21 01:11:30 +02002019static PyObject *
2020PySSL_tls_unique_cb(PySSLSocket *self)
2021{
2022 PyObject *retval = NULL;
2023 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002024 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002025
2026 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2027 /* if session is resumed XOR we are the client */
2028 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2029 }
2030 else {
2031 /* if a new session XOR we are the server */
2032 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2033 }
2034
2035 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002036 if (len == 0)
2037 Py_RETURN_NONE;
2038
2039 retval = PyBytes_FromStringAndSize(buf, len);
2040
2041 return retval;
2042}
2043
2044PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2045"tls_unique_cb() -> bytes\n\
2046\n\
2047Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2048\n\
2049If the TLS handshake is not yet complete, None is returned");
2050
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002051static PyGetSetDef ssl_getsetlist[] = {
2052 {"context", (getter) PySSL_get_context,
2053 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002054 {"server_side", (getter) PySSL_get_server_side, NULL,
2055 PySSL_get_server_side_doc},
2056 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2057 PySSL_get_server_hostname_doc},
2058 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2059 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002060 {NULL}, /* sentinel */
2061};
2062
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002063static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002064 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2065 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2066 PySSL_SSLwrite_doc},
2067 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2068 PySSL_SSLread_doc},
2069 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2070 PySSL_SSLpending_doc},
2071 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2072 PySSL_peercert_doc},
2073 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002074 {"shared_ciphers", (PyCFunction)PySSL_shared_ciphers, METH_NOARGS},
Antoine Pitrou47e40422014-09-04 21:00:10 +02002075 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002076#ifdef OPENSSL_NPN_NEGOTIATED
2077 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2078#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002079#ifdef HAVE_ALPN
2080 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2081#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002082 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002083 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2084 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02002085 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2086 PySSL_tls_unique_cb_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002087 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002088};
2089
Antoine Pitrou152efa22010-05-16 18:19:27 +00002090static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002091 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002092 "_ssl._SSLSocket", /*tp_name*/
2093 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002094 0, /*tp_itemsize*/
2095 /* methods */
2096 (destructor)PySSL_dealloc, /*tp_dealloc*/
2097 0, /*tp_print*/
2098 0, /*tp_getattr*/
2099 0, /*tp_setattr*/
2100 0, /*tp_reserved*/
2101 0, /*tp_repr*/
2102 0, /*tp_as_number*/
2103 0, /*tp_as_sequence*/
2104 0, /*tp_as_mapping*/
2105 0, /*tp_hash*/
2106 0, /*tp_call*/
2107 0, /*tp_str*/
2108 0, /*tp_getattro*/
2109 0, /*tp_setattro*/
2110 0, /*tp_as_buffer*/
2111 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2112 0, /*tp_doc*/
2113 0, /*tp_traverse*/
2114 0, /*tp_clear*/
2115 0, /*tp_richcompare*/
2116 0, /*tp_weaklistoffset*/
2117 0, /*tp_iter*/
2118 0, /*tp_iternext*/
2119 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002120 0, /*tp_members*/
2121 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002122};
2123
Antoine Pitrou152efa22010-05-16 18:19:27 +00002124
2125/*
2126 * _SSLContext objects
2127 */
2128
2129static PyObject *
2130context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2131{
2132 char *kwlist[] = {"protocol", NULL};
2133 PySSLContext *self;
2134 int proto_version = PY_SSL_VERSION_SSL23;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002135 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002136 SSL_CTX *ctx = NULL;
2137
2138 if (!PyArg_ParseTupleAndKeywords(
2139 args, kwds, "i:_SSLContext", kwlist,
2140 &proto_version))
2141 return NULL;
2142
2143 PySSL_BEGIN_ALLOW_THREADS
2144 if (proto_version == PY_SSL_VERSION_TLS1)
2145 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002146#if HAVE_TLSv1_2
2147 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2148 ctx = SSL_CTX_new(TLSv1_1_method());
2149 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2150 ctx = SSL_CTX_new(TLSv1_2_method());
2151#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002152#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002153 else if (proto_version == PY_SSL_VERSION_SSL3)
2154 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002155#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002156#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002157 else if (proto_version == PY_SSL_VERSION_SSL2)
2158 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002159#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002160 else if (proto_version == PY_SSL_VERSION_SSL23)
2161 ctx = SSL_CTX_new(SSLv23_method());
2162 else
2163 proto_version = -1;
2164 PySSL_END_ALLOW_THREADS
2165
2166 if (proto_version == -1) {
2167 PyErr_SetString(PyExc_ValueError,
2168 "invalid protocol version");
2169 return NULL;
2170 }
2171 if (ctx == NULL) {
2172 PyErr_SetString(PySSLErrorObject,
2173 "failed to allocate SSL context");
2174 return NULL;
2175 }
2176
2177 assert(type != NULL && type->tp_alloc != NULL);
2178 self = (PySSLContext *) type->tp_alloc(type, 0);
2179 if (self == NULL) {
2180 SSL_CTX_free(ctx);
2181 return NULL;
2182 }
2183 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002184#ifdef OPENSSL_NPN_NEGOTIATED
2185 self->npn_protocols = NULL;
2186#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002187#ifdef HAVE_ALPN
2188 self->alpn_protocols = NULL;
2189#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002190#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002191 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002192#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002193 /* Don't check host name by default */
2194 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002195 /* Defaults */
2196 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002197 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2198 if (proto_version != PY_SSL_VERSION_SSL2)
2199 options |= SSL_OP_NO_SSLv2;
2200 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002201
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002202#ifndef OPENSSL_NO_ECDH
2203 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2204 prime256v1 by default. This is Apache mod_ssl's initialization
2205 policy, so we should be safe. */
2206#if defined(SSL_CTX_set_ecdh_auto)
2207 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2208#else
2209 {
2210 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2211 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2212 EC_KEY_free(key);
2213 }
2214#endif
2215#endif
2216
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002217#define SID_CTX "Python"
2218 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2219 sizeof(SID_CTX));
2220#undef SID_CTX
2221
Antoine Pitrou152efa22010-05-16 18:19:27 +00002222 return (PyObject *)self;
2223}
2224
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002225static int
2226context_traverse(PySSLContext *self, visitproc visit, void *arg)
2227{
2228#ifndef OPENSSL_NO_TLSEXT
2229 Py_VISIT(self->set_hostname);
2230#endif
2231 return 0;
2232}
2233
2234static int
2235context_clear(PySSLContext *self)
2236{
2237#ifndef OPENSSL_NO_TLSEXT
2238 Py_CLEAR(self->set_hostname);
2239#endif
2240 return 0;
2241}
2242
Antoine Pitrou152efa22010-05-16 18:19:27 +00002243static void
2244context_dealloc(PySSLContext *self)
2245{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002246 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002247 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002248#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002249 PyMem_FREE(self->npn_protocols);
2250#endif
2251#ifdef HAVE_ALPN
2252 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002253#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002254 Py_TYPE(self)->tp_free(self);
2255}
2256
2257static PyObject *
2258set_ciphers(PySSLContext *self, PyObject *args)
2259{
2260 int ret;
2261 const char *cipherlist;
2262
2263 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2264 return NULL;
2265 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2266 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002267 /* Clearing the error queue is necessary on some OpenSSL versions,
2268 otherwise the error will be reported again when another SSL call
2269 is done. */
2270 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002271 PyErr_SetString(PySSLErrorObject,
2272 "No cipher can be selected.");
2273 return NULL;
2274 }
2275 Py_RETURN_NONE;
2276}
2277
Benjamin Petersoncca27322015-01-23 16:35:37 -05002278static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002279do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2280 const unsigned char *server_protocols, unsigned int server_protocols_len,
2281 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002282{
Benjamin Peterson88615022015-01-23 17:30:26 -05002283 int ret;
2284 if (client_protocols == NULL) {
2285 client_protocols = (unsigned char *)"";
2286 client_protocols_len = 0;
2287 }
2288 if (server_protocols == NULL) {
2289 server_protocols = (unsigned char *)"";
2290 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002291 }
2292
Benjamin Peterson88615022015-01-23 17:30:26 -05002293 ret = SSL_select_next_proto(out, outlen,
2294 server_protocols, server_protocols_len,
2295 client_protocols, client_protocols_len);
2296 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2297 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002298
2299 return SSL_TLSEXT_ERR_OK;
2300}
2301
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002302#ifdef OPENSSL_NPN_NEGOTIATED
2303/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2304static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002305_advertiseNPN_cb(SSL *s,
2306 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002307 void *args)
2308{
2309 PySSLContext *ssl_ctx = (PySSLContext *) args;
2310
2311 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002312 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002313 *len = 0;
2314 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002315 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002316 *len = ssl_ctx->npn_protocols_len;
2317 }
2318
2319 return SSL_TLSEXT_ERR_OK;
2320}
2321/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2322static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002323_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002324 unsigned char **out, unsigned char *outlen,
2325 const unsigned char *server, unsigned int server_len,
2326 void *args)
2327{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002328 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002329 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002330 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002331}
2332#endif
2333
2334static PyObject *
2335_set_npn_protocols(PySSLContext *self, PyObject *args)
2336{
2337#ifdef OPENSSL_NPN_NEGOTIATED
2338 Py_buffer protos;
2339
2340 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2341 return NULL;
2342
Christian Heimes5cb31c92012-09-20 12:42:54 +02002343 if (self->npn_protocols != NULL) {
2344 PyMem_Free(self->npn_protocols);
2345 }
2346
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002347 self->npn_protocols = PyMem_Malloc(protos.len);
2348 if (self->npn_protocols == NULL) {
2349 PyBuffer_Release(&protos);
2350 return PyErr_NoMemory();
2351 }
2352 memcpy(self->npn_protocols, protos.buf, protos.len);
2353 self->npn_protocols_len = (int) protos.len;
2354
2355 /* set both server and client callbacks, because the context can
2356 * be used to create both types of sockets */
2357 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2358 _advertiseNPN_cb,
2359 self);
2360 SSL_CTX_set_next_proto_select_cb(self->ctx,
2361 _selectNPN_cb,
2362 self);
2363
2364 PyBuffer_Release(&protos);
2365 Py_RETURN_NONE;
2366#else
2367 PyErr_SetString(PyExc_NotImplementedError,
2368 "The NPN extension requires OpenSSL 1.0.1 or later.");
2369 return NULL;
2370#endif
2371}
2372
Benjamin Petersoncca27322015-01-23 16:35:37 -05002373#ifdef HAVE_ALPN
2374static int
2375_selectALPN_cb(SSL *s,
2376 const unsigned char **out, unsigned char *outlen,
2377 const unsigned char *client_protocols, unsigned int client_protocols_len,
2378 void *args)
2379{
2380 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002381 return do_protocol_selection(1, (unsigned char **)out, outlen,
2382 ctx->alpn_protocols, ctx->alpn_protocols_len,
2383 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002384}
2385#endif
2386
2387static PyObject *
2388_set_alpn_protocols(PySSLContext *self, PyObject *args)
2389{
2390#ifdef HAVE_ALPN
2391 Py_buffer protos;
2392
2393 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2394 return NULL;
2395
2396 PyMem_FREE(self->alpn_protocols);
2397 self->alpn_protocols = PyMem_Malloc(protos.len);
2398 if (!self->alpn_protocols)
2399 return PyErr_NoMemory();
2400 memcpy(self->alpn_protocols, protos.buf, protos.len);
2401 self->alpn_protocols_len = protos.len;
2402 PyBuffer_Release(&protos);
2403
2404 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2405 return PyErr_NoMemory();
2406 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2407
2408 PyBuffer_Release(&protos);
2409 Py_RETURN_NONE;
2410#else
2411 PyErr_SetString(PyExc_NotImplementedError,
2412 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2413 return NULL;
2414#endif
2415}
2416
Antoine Pitrou152efa22010-05-16 18:19:27 +00002417static PyObject *
2418get_verify_mode(PySSLContext *self, void *c)
2419{
2420 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2421 case SSL_VERIFY_NONE:
2422 return PyLong_FromLong(PY_SSL_CERT_NONE);
2423 case SSL_VERIFY_PEER:
2424 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2425 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2426 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2427 }
2428 PyErr_SetString(PySSLErrorObject,
2429 "invalid return value from SSL_CTX_get_verify_mode");
2430 return NULL;
2431}
2432
2433static int
2434set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2435{
2436 int n, mode;
2437 if (!PyArg_Parse(arg, "i", &n))
2438 return -1;
2439 if (n == PY_SSL_CERT_NONE)
2440 mode = SSL_VERIFY_NONE;
2441 else if (n == PY_SSL_CERT_OPTIONAL)
2442 mode = SSL_VERIFY_PEER;
2443 else if (n == PY_SSL_CERT_REQUIRED)
2444 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2445 else {
2446 PyErr_SetString(PyExc_ValueError,
2447 "invalid value for verify_mode");
2448 return -1;
2449 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002450 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2451 PyErr_SetString(PyExc_ValueError,
2452 "Cannot set verify_mode to CERT_NONE when "
2453 "check_hostname is enabled.");
2454 return -1;
2455 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002456 SSL_CTX_set_verify(self->ctx, mode, NULL);
2457 return 0;
2458}
2459
2460static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002461get_verify_flags(PySSLContext *self, void *c)
2462{
2463 X509_STORE *store;
2464 unsigned long flags;
2465
2466 store = SSL_CTX_get_cert_store(self->ctx);
2467 flags = X509_VERIFY_PARAM_get_flags(store->param);
2468 return PyLong_FromUnsignedLong(flags);
2469}
2470
2471static int
2472set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2473{
2474 X509_STORE *store;
2475 unsigned long new_flags, flags, set, clear;
2476
2477 if (!PyArg_Parse(arg, "k", &new_flags))
2478 return -1;
2479 store = SSL_CTX_get_cert_store(self->ctx);
2480 flags = X509_VERIFY_PARAM_get_flags(store->param);
2481 clear = flags & ~new_flags;
2482 set = ~flags & new_flags;
2483 if (clear) {
2484 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2485 _setSSLError(NULL, 0, __FILE__, __LINE__);
2486 return -1;
2487 }
2488 }
2489 if (set) {
2490 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2491 _setSSLError(NULL, 0, __FILE__, __LINE__);
2492 return -1;
2493 }
2494 }
2495 return 0;
2496}
2497
2498static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002499get_options(PySSLContext *self, void *c)
2500{
2501 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2502}
2503
2504static int
2505set_options(PySSLContext *self, PyObject *arg, void *c)
2506{
2507 long new_opts, opts, set, clear;
2508 if (!PyArg_Parse(arg, "l", &new_opts))
2509 return -1;
2510 opts = SSL_CTX_get_options(self->ctx);
2511 clear = opts & ~new_opts;
2512 set = ~opts & new_opts;
2513 if (clear) {
2514#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2515 SSL_CTX_clear_options(self->ctx, clear);
2516#else
2517 PyErr_SetString(PyExc_ValueError,
2518 "can't clear options before OpenSSL 0.9.8m");
2519 return -1;
2520#endif
2521 }
2522 if (set)
2523 SSL_CTX_set_options(self->ctx, set);
2524 return 0;
2525}
2526
Christian Heimes1aa9a752013-12-02 02:41:19 +01002527static PyObject *
2528get_check_hostname(PySSLContext *self, void *c)
2529{
2530 return PyBool_FromLong(self->check_hostname);
2531}
2532
2533static int
2534set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2535{
2536 int check_hostname;
2537 if (!PyArg_Parse(arg, "p", &check_hostname))
2538 return -1;
2539 if (check_hostname &&
2540 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2541 PyErr_SetString(PyExc_ValueError,
2542 "check_hostname needs a SSL context with either "
2543 "CERT_OPTIONAL or CERT_REQUIRED");
2544 return -1;
2545 }
2546 self->check_hostname = check_hostname;
2547 return 0;
2548}
2549
2550
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002551typedef struct {
2552 PyThreadState *thread_state;
2553 PyObject *callable;
2554 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002555 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002556 int error;
2557} _PySSLPasswordInfo;
2558
2559static int
2560_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2561 const char *bad_type_error)
2562{
2563 /* Set the password and size fields of a _PySSLPasswordInfo struct
2564 from a unicode, bytes, or byte array object.
2565 The password field will be dynamically allocated and must be freed
2566 by the caller */
2567 PyObject *password_bytes = NULL;
2568 const char *data = NULL;
2569 Py_ssize_t size;
2570
2571 if (PyUnicode_Check(password)) {
2572 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2573 if (!password_bytes) {
2574 goto error;
2575 }
2576 data = PyBytes_AS_STRING(password_bytes);
2577 size = PyBytes_GET_SIZE(password_bytes);
2578 } else if (PyBytes_Check(password)) {
2579 data = PyBytes_AS_STRING(password);
2580 size = PyBytes_GET_SIZE(password);
2581 } else if (PyByteArray_Check(password)) {
2582 data = PyByteArray_AS_STRING(password);
2583 size = PyByteArray_GET_SIZE(password);
2584 } else {
2585 PyErr_SetString(PyExc_TypeError, bad_type_error);
2586 goto error;
2587 }
2588
Victor Stinner9ee02032013-06-23 15:08:23 +02002589 if (size > (Py_ssize_t)INT_MAX) {
2590 PyErr_Format(PyExc_ValueError,
2591 "password cannot be longer than %d bytes", INT_MAX);
2592 goto error;
2593 }
2594
Victor Stinner11ebff22013-07-07 17:07:52 +02002595 PyMem_Free(pw_info->password);
2596 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002597 if (!pw_info->password) {
2598 PyErr_SetString(PyExc_MemoryError,
2599 "unable to allocate password buffer");
2600 goto error;
2601 }
2602 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002603 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002604
2605 Py_XDECREF(password_bytes);
2606 return 1;
2607
2608error:
2609 Py_XDECREF(password_bytes);
2610 return 0;
2611}
2612
2613static int
2614_password_callback(char *buf, int size, int rwflag, void *userdata)
2615{
2616 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2617 PyObject *fn_ret = NULL;
2618
2619 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2620
2621 if (pw_info->callable) {
2622 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2623 if (!fn_ret) {
2624 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2625 core python API, so we could use it to add a frame here */
2626 goto error;
2627 }
2628
2629 if (!_pwinfo_set(pw_info, fn_ret,
2630 "password callback must return a string")) {
2631 goto error;
2632 }
2633 Py_CLEAR(fn_ret);
2634 }
2635
2636 if (pw_info->size > size) {
2637 PyErr_Format(PyExc_ValueError,
2638 "password cannot be longer than %d bytes", size);
2639 goto error;
2640 }
2641
2642 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2643 memcpy(buf, pw_info->password, pw_info->size);
2644 return pw_info->size;
2645
2646error:
2647 Py_XDECREF(fn_ret);
2648 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2649 pw_info->error = 1;
2650 return -1;
2651}
2652
Antoine Pitroub5218772010-05-21 09:56:06 +00002653static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002654load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2655{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002656 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2657 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002658 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002659 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2660 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2661 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002662 int r;
2663
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002664 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002665 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002666 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002667 "O|OO:load_cert_chain", kwlist,
2668 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002669 return NULL;
2670 if (keyfile == Py_None)
2671 keyfile = NULL;
2672 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2673 PyErr_SetString(PyExc_TypeError,
2674 "certfile should be a valid filesystem path");
2675 return NULL;
2676 }
2677 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2678 PyErr_SetString(PyExc_TypeError,
2679 "keyfile should be a valid filesystem path");
2680 goto error;
2681 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002682 if (password && password != Py_None) {
2683 if (PyCallable_Check(password)) {
2684 pw_info.callable = password;
2685 } else if (!_pwinfo_set(&pw_info, password,
2686 "password should be a string or callable")) {
2687 goto error;
2688 }
2689 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2690 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2691 }
2692 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002693 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2694 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002695 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002696 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002697 if (pw_info.error) {
2698 ERR_clear_error();
2699 /* the password callback has already set the error information */
2700 }
2701 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002702 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002703 PyErr_SetFromErrno(PyExc_IOError);
2704 }
2705 else {
2706 _setSSLError(NULL, 0, __FILE__, __LINE__);
2707 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002708 goto error;
2709 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002710 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002711 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002712 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2713 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002714 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2715 Py_CLEAR(keyfile_bytes);
2716 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002717 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002718 if (pw_info.error) {
2719 ERR_clear_error();
2720 /* the password callback has already set the error information */
2721 }
2722 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002723 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002724 PyErr_SetFromErrno(PyExc_IOError);
2725 }
2726 else {
2727 _setSSLError(NULL, 0, __FILE__, __LINE__);
2728 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002729 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002730 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002731 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002732 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002733 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002734 if (r != 1) {
2735 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002736 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002737 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002738 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2739 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002740 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002741 Py_RETURN_NONE;
2742
2743error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002744 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2745 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002746 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002747 Py_XDECREF(keyfile_bytes);
2748 Py_XDECREF(certfile_bytes);
2749 return NULL;
2750}
2751
Christian Heimesefff7062013-11-21 03:35:02 +01002752/* internal helper function, returns -1 on error
2753 */
2754static int
2755_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2756 int filetype)
2757{
2758 BIO *biobuf = NULL;
2759 X509_STORE *store;
2760 int retval = 0, err, loaded = 0;
2761
2762 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2763
2764 if (len <= 0) {
2765 PyErr_SetString(PyExc_ValueError,
2766 "Empty certificate data");
2767 return -1;
2768 } else if (len > INT_MAX) {
2769 PyErr_SetString(PyExc_OverflowError,
2770 "Certificate data is too long.");
2771 return -1;
2772 }
2773
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002774 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002775 if (biobuf == NULL) {
2776 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2777 return -1;
2778 }
2779
2780 store = SSL_CTX_get_cert_store(self->ctx);
2781 assert(store != NULL);
2782
2783 while (1) {
2784 X509 *cert = NULL;
2785 int r;
2786
2787 if (filetype == SSL_FILETYPE_ASN1) {
2788 cert = d2i_X509_bio(biobuf, NULL);
2789 } else {
2790 cert = PEM_read_bio_X509(biobuf, NULL,
2791 self->ctx->default_passwd_callback,
2792 self->ctx->default_passwd_callback_userdata);
2793 }
2794 if (cert == NULL) {
2795 break;
2796 }
2797 r = X509_STORE_add_cert(store, cert);
2798 X509_free(cert);
2799 if (!r) {
2800 err = ERR_peek_last_error();
2801 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2802 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2803 /* cert already in hash table, not an error */
2804 ERR_clear_error();
2805 } else {
2806 break;
2807 }
2808 }
2809 loaded++;
2810 }
2811
2812 err = ERR_peek_last_error();
2813 if ((filetype == SSL_FILETYPE_ASN1) &&
2814 (loaded > 0) &&
2815 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2816 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2817 /* EOF ASN1 file, not an error */
2818 ERR_clear_error();
2819 retval = 0;
2820 } else if ((filetype == SSL_FILETYPE_PEM) &&
2821 (loaded > 0) &&
2822 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2823 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2824 /* EOF PEM file, not an error */
2825 ERR_clear_error();
2826 retval = 0;
2827 } else {
2828 _setSSLError(NULL, 0, __FILE__, __LINE__);
2829 retval = -1;
2830 }
2831
2832 BIO_free(biobuf);
2833 return retval;
2834}
2835
2836
Antoine Pitrou152efa22010-05-16 18:19:27 +00002837static PyObject *
2838load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2839{
Christian Heimesefff7062013-11-21 03:35:02 +01002840 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2841 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002842 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2843 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002844 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002845
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002846 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002847 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002848 "|OOO:load_verify_locations", kwlist,
2849 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002850 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002851
Antoine Pitrou152efa22010-05-16 18:19:27 +00002852 if (cafile == Py_None)
2853 cafile = NULL;
2854 if (capath == Py_None)
2855 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002856 if (cadata == Py_None)
2857 cadata = NULL;
2858
2859 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002860 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002861 "cafile, capath and cadata cannot be all omitted");
2862 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002863 }
2864 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2865 PyErr_SetString(PyExc_TypeError,
2866 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002867 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002868 }
2869 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002870 PyErr_SetString(PyExc_TypeError,
2871 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002872 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002873 }
Christian Heimesefff7062013-11-21 03:35:02 +01002874
2875 /* validata cadata type and load cadata */
2876 if (cadata) {
2877 Py_buffer buf;
2878 PyObject *cadata_ascii = NULL;
2879
2880 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2881 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2882 PyBuffer_Release(&buf);
2883 PyErr_SetString(PyExc_TypeError,
2884 "cadata should be a contiguous buffer with "
2885 "a single dimension");
2886 goto error;
2887 }
2888 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2889 PyBuffer_Release(&buf);
2890 if (r == -1) {
2891 goto error;
2892 }
2893 } else {
2894 PyErr_Clear();
2895 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2896 if (cadata_ascii == NULL) {
2897 PyErr_SetString(PyExc_TypeError,
2898 "cadata should be a ASCII string or a "
2899 "bytes-like object");
2900 goto error;
2901 }
2902 r = _add_ca_certs(self,
2903 PyBytes_AS_STRING(cadata_ascii),
2904 PyBytes_GET_SIZE(cadata_ascii),
2905 SSL_FILETYPE_PEM);
2906 Py_DECREF(cadata_ascii);
2907 if (r == -1) {
2908 goto error;
2909 }
2910 }
2911 }
2912
2913 /* load cafile or capath */
2914 if (cafile || capath) {
2915 if (cafile)
2916 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2917 if (capath)
2918 capath_buf = PyBytes_AS_STRING(capath_bytes);
2919 PySSL_BEGIN_ALLOW_THREADS
2920 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2921 PySSL_END_ALLOW_THREADS
2922 if (r != 1) {
2923 ok = 0;
2924 if (errno != 0) {
2925 ERR_clear_error();
2926 PyErr_SetFromErrno(PyExc_IOError);
2927 }
2928 else {
2929 _setSSLError(NULL, 0, __FILE__, __LINE__);
2930 }
2931 goto error;
2932 }
2933 }
2934 goto end;
2935
2936 error:
2937 ok = 0;
2938 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002939 Py_XDECREF(cafile_bytes);
2940 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002941 if (ok) {
2942 Py_RETURN_NONE;
2943 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002944 return NULL;
2945 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002946}
2947
2948static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002949load_dh_params(PySSLContext *self, PyObject *filepath)
2950{
2951 FILE *f;
2952 DH *dh;
2953
Victor Stinnerdaf45552013-08-28 00:53:59 +02002954 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002955 if (f == NULL) {
2956 if (!PyErr_Occurred())
2957 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2958 return NULL;
2959 }
2960 errno = 0;
2961 PySSL_BEGIN_ALLOW_THREADS
2962 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002963 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002964 PySSL_END_ALLOW_THREADS
2965 if (dh == NULL) {
2966 if (errno != 0) {
2967 ERR_clear_error();
2968 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2969 }
2970 else {
2971 _setSSLError(NULL, 0, __FILE__, __LINE__);
2972 }
2973 return NULL;
2974 }
2975 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2976 _setSSLError(NULL, 0, __FILE__, __LINE__);
2977 DH_free(dh);
2978 Py_RETURN_NONE;
2979}
2980
2981static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002982context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2983{
Antoine Pitroud5323212010-10-22 18:19:07 +00002984 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002985 PySocketSockObject *sock;
2986 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002987 char *hostname = NULL;
2988 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002989
Antoine Pitroud5323212010-10-22 18:19:07 +00002990 /* server_hostname is either None (or absent), or to be encoded
2991 using the idna encoding. */
2992 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002993 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002994 &sock, &server_side,
2995 Py_TYPE(Py_None), &hostname_obj)) {
2996 PyErr_Clear();
2997 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2998 PySocketModule.Sock_Type,
2999 &sock, &server_side,
3000 "idna", &hostname))
3001 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003002 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003003
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003004 res = (PyObject *) newPySSLSocket(self, sock, server_side, hostname,
3005 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003006 if (hostname != NULL)
3007 PyMem_Free(hostname);
3008 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003009}
3010
Antoine Pitroub0182c82010-10-12 20:09:02 +00003011static PyObject *
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003012context_wrap_bio(PySSLContext *self, PyObject *args, PyObject *kwds)
3013{
3014 char *kwlist[] = {"incoming", "outgoing", "server_side",
3015 "server_hostname", NULL};
3016 int server_side;
3017 char *hostname = NULL;
3018 PyObject *hostname_obj = Py_None, *res;
3019 PySSLMemoryBIO *incoming, *outgoing;
3020
3021 /* server_hostname is either None (or absent), or to be encoded
3022 using the idna encoding. */
3023 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!O!i|O:_wrap_bio", kwlist,
3024 &PySSLMemoryBIO_Type, &incoming,
3025 &PySSLMemoryBIO_Type, &outgoing,
3026 &server_side, &hostname_obj))
3027 return NULL;
3028 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003029 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3030 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003031 }
3032
3033 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3034 incoming, outgoing);
3035
3036 PyMem_Free(hostname);
3037 return res;
3038}
3039
3040static PyObject *
Antoine Pitroub0182c82010-10-12 20:09:02 +00003041session_stats(PySSLContext *self, PyObject *unused)
3042{
3043 int r;
3044 PyObject *value, *stats = PyDict_New();
3045 if (!stats)
3046 return NULL;
3047
3048#define ADD_STATS(SSL_NAME, KEY_NAME) \
3049 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3050 if (value == NULL) \
3051 goto error; \
3052 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3053 Py_DECREF(value); \
3054 if (r < 0) \
3055 goto error;
3056
3057 ADD_STATS(number, "number");
3058 ADD_STATS(connect, "connect");
3059 ADD_STATS(connect_good, "connect_good");
3060 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3061 ADD_STATS(accept, "accept");
3062 ADD_STATS(accept_good, "accept_good");
3063 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3064 ADD_STATS(accept, "accept");
3065 ADD_STATS(hits, "hits");
3066 ADD_STATS(misses, "misses");
3067 ADD_STATS(timeouts, "timeouts");
3068 ADD_STATS(cache_full, "cache_full");
3069
3070#undef ADD_STATS
3071
3072 return stats;
3073
3074error:
3075 Py_DECREF(stats);
3076 return NULL;
3077}
3078
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003079static PyObject *
3080set_default_verify_paths(PySSLContext *self, PyObject *unused)
3081{
3082 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3083 _setSSLError(NULL, 0, __FILE__, __LINE__);
3084 return NULL;
3085 }
3086 Py_RETURN_NONE;
3087}
3088
Antoine Pitrou501da612011-12-21 09:27:41 +01003089#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003090static PyObject *
3091set_ecdh_curve(PySSLContext *self, PyObject *name)
3092{
3093 PyObject *name_bytes;
3094 int nid;
3095 EC_KEY *key;
3096
3097 if (!PyUnicode_FSConverter(name, &name_bytes))
3098 return NULL;
3099 assert(PyBytes_Check(name_bytes));
3100 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3101 Py_DECREF(name_bytes);
3102 if (nid == 0) {
3103 PyErr_Format(PyExc_ValueError,
3104 "unknown elliptic curve name %R", name);
3105 return NULL;
3106 }
3107 key = EC_KEY_new_by_curve_name(nid);
3108 if (key == NULL) {
3109 _setSSLError(NULL, 0, __FILE__, __LINE__);
3110 return NULL;
3111 }
3112 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3113 EC_KEY_free(key);
3114 Py_RETURN_NONE;
3115}
Antoine Pitrou501da612011-12-21 09:27:41 +01003116#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003117
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003118#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003119static int
3120_servername_callback(SSL *s, int *al, void *args)
3121{
3122 int ret;
3123 PySSLContext *ssl_ctx = (PySSLContext *) args;
3124 PySSLSocket *ssl;
3125 PyObject *servername_o;
3126 PyObject *servername_idna;
3127 PyObject *result;
3128 /* The high-level ssl.SSLSocket object */
3129 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003130 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003131#ifdef WITH_THREAD
3132 PyGILState_STATE gstate = PyGILState_Ensure();
3133#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003134
3135 if (ssl_ctx->set_hostname == NULL) {
3136 /* remove race condition in this the call back while if removing the
3137 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003138#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003139 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003140#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003141 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003142 }
3143
3144 ssl = SSL_get_app_data(s);
3145 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003146
3147 /* The servername callback expects a argument that represents the current
3148 * SSL connection and that has a .context attribute that can be changed to
3149 * identify the requested hostname. Since the official API is the Python
3150 * level API we want to pass the callback a Python level object rather than
3151 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3152 * SSLObject) that will be passed. Otherwise if there's a socket then that
3153 * will be passed. If both do not exist only then the C-level object is
3154 * passed. */
3155 if (ssl->owner)
3156 ssl_socket = PyWeakref_GetObject(ssl->owner);
3157 else if (ssl->Socket)
3158 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3159 else
3160 ssl_socket = (PyObject *) ssl;
3161
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003162 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003163 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003164 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003165
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003166 if (servername == NULL) {
3167 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3168 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003169 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003170 else {
3171 servername_o = PyBytes_FromString(servername);
3172 if (servername_o == NULL) {
3173 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3174 goto error;
3175 }
3176 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3177 if (servername_idna == NULL) {
3178 PyErr_WriteUnraisable(servername_o);
3179 Py_DECREF(servername_o);
3180 goto error;
3181 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003182 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003183 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3184 servername_idna, ssl_ctx, NULL);
3185 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003186 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003187 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003188
3189 if (result == NULL) {
3190 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3191 *al = SSL_AD_HANDSHAKE_FAILURE;
3192 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3193 }
3194 else {
3195 if (result != Py_None) {
3196 *al = (int) PyLong_AsLong(result);
3197 if (PyErr_Occurred()) {
3198 PyErr_WriteUnraisable(result);
3199 *al = SSL_AD_INTERNAL_ERROR;
3200 }
3201 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3202 }
3203 else {
3204 ret = SSL_TLSEXT_ERR_OK;
3205 }
3206 Py_DECREF(result);
3207 }
3208
Stefan Krah20d60802013-01-17 17:07:17 +01003209#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003210 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003211#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003212 return ret;
3213
3214error:
3215 Py_DECREF(ssl_socket);
3216 *al = SSL_AD_INTERNAL_ERROR;
3217 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003218#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003219 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003220#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003221 return ret;
3222}
Antoine Pitroua5963382013-03-30 16:39:00 +01003223#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003224
3225PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3226"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003227\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003228This sets a callback that will be called when a server name is provided by\n\
3229the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003230\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003231If the argument is None then the callback is disabled. The method is called\n\
3232with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003233See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003234
3235static PyObject *
3236set_servername_callback(PySSLContext *self, PyObject *args)
3237{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003238#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003239 PyObject *cb;
3240
3241 if (!PyArg_ParseTuple(args, "O", &cb))
3242 return NULL;
3243
3244 Py_CLEAR(self->set_hostname);
3245 if (cb == Py_None) {
3246 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3247 }
3248 else {
3249 if (!PyCallable_Check(cb)) {
3250 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3251 PyErr_SetString(PyExc_TypeError,
3252 "not a callable object");
3253 return NULL;
3254 }
3255 Py_INCREF(cb);
3256 self->set_hostname = cb;
3257 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3258 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3259 }
3260 Py_RETURN_NONE;
3261#else
3262 PyErr_SetString(PyExc_NotImplementedError,
3263 "The TLS extension servername callback, "
3264 "SSL_CTX_set_tlsext_servername_callback, "
3265 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003266 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003267#endif
3268}
3269
Christian Heimes9a5395a2013-06-17 15:44:12 +02003270PyDoc_STRVAR(PySSL_get_stats_doc,
3271"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3272\n\
3273Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3274CA extension and certificate revocation lists inside the context's cert\n\
3275store.\n\
3276NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3277been used at least once.");
3278
3279static PyObject *
3280cert_store_stats(PySSLContext *self)
3281{
3282 X509_STORE *store;
3283 X509_OBJECT *obj;
3284 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3285
3286 store = SSL_CTX_get_cert_store(self->ctx);
3287 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3288 obj = sk_X509_OBJECT_value(store->objs, i);
3289 switch (obj->type) {
3290 case X509_LU_X509:
3291 x509++;
3292 if (X509_check_ca(obj->data.x509)) {
3293 ca++;
3294 }
3295 break;
3296 case X509_LU_CRL:
3297 crl++;
3298 break;
3299 case X509_LU_PKEY:
3300 pkey++;
3301 break;
3302 default:
3303 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3304 * As far as I can tell they are internal states and never
3305 * stored in a cert store */
3306 break;
3307 }
3308 }
3309 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3310 "x509_ca", ca);
3311}
3312
3313PyDoc_STRVAR(PySSL_get_ca_certs_doc,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003314"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
Christian Heimes9a5395a2013-06-17 15:44:12 +02003315\n\
3316Returns a list of dicts with information of loaded CA certs. If the\n\
3317optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3318NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3319been used at least once.");
3320
3321static PyObject *
Christian Heimesf22e8e52013-11-22 02:22:51 +01003322get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
Christian Heimes9a5395a2013-06-17 15:44:12 +02003323{
Christian Heimesf22e8e52013-11-22 02:22:51 +01003324 char *kwlist[] = {"binary_form", NULL};
Christian Heimes9a5395a2013-06-17 15:44:12 +02003325 X509_STORE *store;
3326 PyObject *ci = NULL, *rlist = NULL;
3327 int i;
3328 int binary_mode = 0;
3329
Christian Heimesf22e8e52013-11-22 02:22:51 +01003330 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|p:get_ca_certs",
3331 kwlist, &binary_mode)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003332 return NULL;
3333 }
3334
3335 if ((rlist = PyList_New(0)) == NULL) {
3336 return NULL;
3337 }
3338
3339 store = SSL_CTX_get_cert_store(self->ctx);
3340 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3341 X509_OBJECT *obj;
3342 X509 *cert;
3343
3344 obj = sk_X509_OBJECT_value(store->objs, i);
3345 if (obj->type != X509_LU_X509) {
3346 /* not a x509 cert */
3347 continue;
3348 }
3349 /* CA for any purpose */
3350 cert = obj->data.x509;
3351 if (!X509_check_ca(cert)) {
3352 continue;
3353 }
3354 if (binary_mode) {
3355 ci = _certificate_to_der(cert);
3356 } else {
3357 ci = _decode_certificate(cert);
3358 }
3359 if (ci == NULL) {
3360 goto error;
3361 }
3362 if (PyList_Append(rlist, ci) == -1) {
3363 goto error;
3364 }
3365 Py_CLEAR(ci);
3366 }
3367 return rlist;
3368
3369 error:
3370 Py_XDECREF(ci);
3371 Py_XDECREF(rlist);
3372 return NULL;
3373}
3374
3375
Antoine Pitrou152efa22010-05-16 18:19:27 +00003376static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003377 {"check_hostname", (getter) get_check_hostname,
3378 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003379 {"options", (getter) get_options,
3380 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003381 {"verify_flags", (getter) get_verify_flags,
3382 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003383 {"verify_mode", (getter) get_verify_mode,
3384 (setter) set_verify_mode, NULL},
3385 {NULL}, /* sentinel */
3386};
3387
3388static struct PyMethodDef context_methods[] = {
3389 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3390 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003391 {"_wrap_bio", (PyCFunction) context_wrap_bio,
3392 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003393 {"set_ciphers", (PyCFunction) set_ciphers,
3394 METH_VARARGS, NULL},
Benjamin Petersoncca27322015-01-23 16:35:37 -05003395 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3396 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003397 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3398 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003399 {"load_cert_chain", (PyCFunction) load_cert_chain,
3400 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003401 {"load_dh_params", (PyCFunction) load_dh_params,
3402 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003403 {"load_verify_locations", (PyCFunction) load_verify_locations,
3404 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00003405 {"session_stats", (PyCFunction) session_stats,
3406 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003407 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3408 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003409#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003410 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3411 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003412#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003413 {"set_servername_callback", (PyCFunction) set_servername_callback,
3414 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02003415 {"cert_store_stats", (PyCFunction) cert_store_stats,
3416 METH_NOARGS, PySSL_get_stats_doc},
3417 {"get_ca_certs", (PyCFunction) get_ca_certs,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003418 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003419 {NULL, NULL} /* sentinel */
3420};
3421
3422static PyTypeObject PySSLContext_Type = {
3423 PyVarObject_HEAD_INIT(NULL, 0)
3424 "_ssl._SSLContext", /*tp_name*/
3425 sizeof(PySSLContext), /*tp_basicsize*/
3426 0, /*tp_itemsize*/
3427 (destructor)context_dealloc, /*tp_dealloc*/
3428 0, /*tp_print*/
3429 0, /*tp_getattr*/
3430 0, /*tp_setattr*/
3431 0, /*tp_reserved*/
3432 0, /*tp_repr*/
3433 0, /*tp_as_number*/
3434 0, /*tp_as_sequence*/
3435 0, /*tp_as_mapping*/
3436 0, /*tp_hash*/
3437 0, /*tp_call*/
3438 0, /*tp_str*/
3439 0, /*tp_getattro*/
3440 0, /*tp_setattro*/
3441 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003442 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003443 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003444 (traverseproc) context_traverse, /*tp_traverse*/
3445 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003446 0, /*tp_richcompare*/
3447 0, /*tp_weaklistoffset*/
3448 0, /*tp_iter*/
3449 0, /*tp_iternext*/
3450 context_methods, /*tp_methods*/
3451 0, /*tp_members*/
3452 context_getsetlist, /*tp_getset*/
3453 0, /*tp_base*/
3454 0, /*tp_dict*/
3455 0, /*tp_descr_get*/
3456 0, /*tp_descr_set*/
3457 0, /*tp_dictoffset*/
3458 0, /*tp_init*/
3459 0, /*tp_alloc*/
3460 context_new, /*tp_new*/
3461};
3462
3463
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003464/*
3465 * MemoryBIO objects
3466 */
3467
3468static PyObject *
3469memory_bio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3470{
3471 char *kwlist[] = {NULL};
3472 BIO *bio;
3473 PySSLMemoryBIO *self;
3474
3475 if (!PyArg_ParseTupleAndKeywords(args, kwds, ":MemoryBIO", kwlist))
3476 return NULL;
3477
3478 bio = BIO_new(BIO_s_mem());
3479 if (bio == NULL) {
3480 PyErr_SetString(PySSLErrorObject,
3481 "failed to allocate BIO");
3482 return NULL;
3483 }
3484 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3485 * just that no data is currently available. The SSL routines should retry
3486 * the read, which we can achieve by calling BIO_set_retry_read(). */
3487 BIO_set_retry_read(bio);
3488 BIO_set_mem_eof_return(bio, -1);
3489
3490 assert(type != NULL && type->tp_alloc != NULL);
3491 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3492 if (self == NULL) {
3493 BIO_free(bio);
3494 return NULL;
3495 }
3496 self->bio = bio;
3497 self->eof_written = 0;
3498
3499 return (PyObject *) self;
3500}
3501
3502static void
3503memory_bio_dealloc(PySSLMemoryBIO *self)
3504{
3505 BIO_free(self->bio);
3506 Py_TYPE(self)->tp_free(self);
3507}
3508
3509static PyObject *
3510memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3511{
3512 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3513}
3514
3515PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3516"The number of bytes pending in the memory BIO.");
3517
3518static PyObject *
3519memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3520{
3521 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3522 && self->eof_written);
3523}
3524
3525PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3526"Whether the memory BIO is at EOF.");
3527
3528static PyObject *
3529memory_bio_read(PySSLMemoryBIO *self, PyObject *args)
3530{
3531 int len = -1, avail, nbytes;
3532 PyObject *result;
3533
3534 if (!PyArg_ParseTuple(args, "|i:read", &len))
3535 return NULL;
3536
3537 avail = BIO_ctrl_pending(self->bio);
3538 if ((len < 0) || (len > avail))
3539 len = avail;
3540
3541 result = PyBytes_FromStringAndSize(NULL, len);
3542 if ((result == NULL) || (len == 0))
3543 return result;
3544
3545 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3546 /* There should never be any short reads but check anyway. */
3547 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3548 Py_DECREF(result);
3549 return NULL;
3550 }
3551
3552 return result;
3553}
3554
3555PyDoc_STRVAR(PySSL_memory_bio_read_doc,
3556"read([len]) -> bytes\n\
3557\n\
3558Read up to len bytes from the memory BIO.\n\
3559\n\
3560If len is not specified, read the entire buffer.\n\
3561If the return value is an empty bytes instance, this means either\n\
3562EOF or that no data is available. Use the \"eof\" property to\n\
3563distinguish between the two.");
3564
3565static PyObject *
3566memory_bio_write(PySSLMemoryBIO *self, PyObject *args)
3567{
3568 Py_buffer buf;
3569 int nbytes;
3570
3571 if (!PyArg_ParseTuple(args, "y*:write", &buf))
3572 return NULL;
3573
3574 if (buf.len > INT_MAX) {
3575 PyErr_Format(PyExc_OverflowError,
3576 "string longer than %d bytes", INT_MAX);
3577 goto error;
3578 }
3579
3580 if (self->eof_written) {
3581 PyErr_SetString(PySSLErrorObject,
3582 "cannot write() after write_eof()");
3583 goto error;
3584 }
3585
3586 nbytes = BIO_write(self->bio, buf.buf, buf.len);
3587 if (nbytes < 0) {
3588 _setSSLError(NULL, 0, __FILE__, __LINE__);
3589 goto error;
3590 }
3591
3592 PyBuffer_Release(&buf);
3593 return PyLong_FromLong(nbytes);
3594
3595error:
3596 PyBuffer_Release(&buf);
3597 return NULL;
3598}
3599
3600PyDoc_STRVAR(PySSL_memory_bio_write_doc,
3601"write(b) -> len\n\
3602\n\
3603Writes the bytes b into the memory BIO. Returns the number\n\
3604of bytes written.");
3605
3606static PyObject *
3607memory_bio_write_eof(PySSLMemoryBIO *self, PyObject *args)
3608{
3609 self->eof_written = 1;
3610 /* After an EOF is written, a zero return from read() should be a real EOF
3611 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3612 BIO_clear_retry_flags(self->bio);
3613 BIO_set_mem_eof_return(self->bio, 0);
3614
3615 Py_RETURN_NONE;
3616}
3617
3618PyDoc_STRVAR(PySSL_memory_bio_write_eof_doc,
3619"write_eof()\n\
3620\n\
3621Write an EOF marker to the memory BIO.\n\
3622When all data has been read, the \"eof\" property will be True.");
3623
3624static PyGetSetDef memory_bio_getsetlist[] = {
3625 {"pending", (getter) memory_bio_get_pending, NULL,
3626 PySSL_memory_bio_pending_doc},
3627 {"eof", (getter) memory_bio_get_eof, NULL,
3628 PySSL_memory_bio_eof_doc},
3629 {NULL}, /* sentinel */
3630};
3631
3632static struct PyMethodDef memory_bio_methods[] = {
3633 {"read", (PyCFunction) memory_bio_read,
3634 METH_VARARGS, PySSL_memory_bio_read_doc},
3635 {"write", (PyCFunction) memory_bio_write,
3636 METH_VARARGS, PySSL_memory_bio_write_doc},
3637 {"write_eof", (PyCFunction) memory_bio_write_eof,
3638 METH_NOARGS, PySSL_memory_bio_write_eof_doc},
3639 {NULL, NULL} /* sentinel */
3640};
3641
3642static PyTypeObject PySSLMemoryBIO_Type = {
3643 PyVarObject_HEAD_INIT(NULL, 0)
3644 "_ssl.MemoryBIO", /*tp_name*/
3645 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3646 0, /*tp_itemsize*/
3647 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3648 0, /*tp_print*/
3649 0, /*tp_getattr*/
3650 0, /*tp_setattr*/
3651 0, /*tp_reserved*/
3652 0, /*tp_repr*/
3653 0, /*tp_as_number*/
3654 0, /*tp_as_sequence*/
3655 0, /*tp_as_mapping*/
3656 0, /*tp_hash*/
3657 0, /*tp_call*/
3658 0, /*tp_str*/
3659 0, /*tp_getattro*/
3660 0, /*tp_setattro*/
3661 0, /*tp_as_buffer*/
3662 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3663 0, /*tp_doc*/
3664 0, /*tp_traverse*/
3665 0, /*tp_clear*/
3666 0, /*tp_richcompare*/
3667 0, /*tp_weaklistoffset*/
3668 0, /*tp_iter*/
3669 0, /*tp_iternext*/
3670 memory_bio_methods, /*tp_methods*/
3671 0, /*tp_members*/
3672 memory_bio_getsetlist, /*tp_getset*/
3673 0, /*tp_base*/
3674 0, /*tp_dict*/
3675 0, /*tp_descr_get*/
3676 0, /*tp_descr_set*/
3677 0, /*tp_dictoffset*/
3678 0, /*tp_init*/
3679 0, /*tp_alloc*/
3680 memory_bio_new, /*tp_new*/
3681};
3682
Antoine Pitrou152efa22010-05-16 18:19:27 +00003683
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003684/* helper routines for seeding the SSL PRNG */
3685static PyObject *
3686PySSL_RAND_add(PyObject *self, PyObject *args)
3687{
3688 char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003689 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003690 double entropy;
3691
3692 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00003693 return NULL;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003694 do {
3695 written = Py_MIN(len, INT_MAX);
3696 RAND_add(buf, (int)written, entropy);
3697 buf += written;
3698 len -= written;
3699 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003700 Py_INCREF(Py_None);
3701 return Py_None;
3702}
3703
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003704PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003705"RAND_add(string, entropy)\n\
3706\n\
3707Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003708bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003709
3710static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003711PySSL_RAND(int len, int pseudo)
3712{
3713 int ok;
3714 PyObject *bytes;
3715 unsigned long err;
3716 const char *errstr;
3717 PyObject *v;
3718
Victor Stinner1e81a392013-12-19 16:47:04 +01003719 if (len < 0) {
3720 PyErr_SetString(PyExc_ValueError, "num must be positive");
3721 return NULL;
3722 }
3723
Victor Stinner99c8b162011-05-24 12:05:19 +02003724 bytes = PyBytes_FromStringAndSize(NULL, len);
3725 if (bytes == NULL)
3726 return NULL;
3727 if (pseudo) {
3728 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3729 if (ok == 0 || ok == 1)
3730 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3731 }
3732 else {
3733 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3734 if (ok == 1)
3735 return bytes;
3736 }
3737 Py_DECREF(bytes);
3738
3739 err = ERR_get_error();
3740 errstr = ERR_reason_error_string(err);
3741 v = Py_BuildValue("(ks)", err, errstr);
3742 if (v != NULL) {
3743 PyErr_SetObject(PySSLErrorObject, v);
3744 Py_DECREF(v);
3745 }
3746 return NULL;
3747}
3748
3749static PyObject *
3750PySSL_RAND_bytes(PyObject *self, PyObject *args)
3751{
3752 int len;
3753 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3754 return NULL;
3755 return PySSL_RAND(len, 0);
3756}
3757
3758PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3759"RAND_bytes(n) -> bytes\n\
3760\n\
3761Generate n cryptographically strong pseudo-random bytes.");
3762
3763static PyObject *
3764PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3765{
3766 int len;
3767 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3768 return NULL;
3769 return PySSL_RAND(len, 1);
3770}
3771
3772PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3773"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3774\n\
3775Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3776generated are cryptographically strong.");
3777
3778static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003779PySSL_RAND_status(PyObject *self)
3780{
Christian Heimes217cfd12007-12-02 14:31:20 +00003781 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003782}
3783
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003784PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003785"RAND_status() -> 0 or 1\n\
3786\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003787Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3788It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3789using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003790
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003791#ifdef HAVE_RAND_EGD
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003792static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003793PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003794{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003795 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003796 int bytes;
3797
Jesus Ceac8754a12012-09-11 02:00:58 +02003798 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003799 PyUnicode_FSConverter, &path))
3800 return NULL;
3801
3802 bytes = RAND_egd(PyBytes_AsString(path));
3803 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003804 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003805 PyErr_SetString(PySSLErrorObject,
3806 "EGD connection failed or EGD did not return "
3807 "enough data to seed the PRNG");
3808 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003809 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003810 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003811}
3812
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003813PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003814"RAND_egd(path) -> bytes\n\
3815\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003816Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3817Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003818fails or if it does not provide enough data to seed PRNG.");
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003819#endif /* HAVE_RAND_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003820
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003821
Christian Heimes6d7ad132013-06-09 18:02:55 +02003822PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3823"get_default_verify_paths() -> tuple\n\
3824\n\
3825Return search paths and environment vars that are used by SSLContext's\n\
3826set_default_verify_paths() to load default CAs. The values are\n\
3827'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3828
3829static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003830PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003831{
3832 PyObject *ofile_env = NULL;
3833 PyObject *ofile = NULL;
3834 PyObject *odir_env = NULL;
3835 PyObject *odir = NULL;
3836
3837#define convert(info, target) { \
3838 const char *tmp = (info); \
3839 target = NULL; \
3840 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3841 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3842 target = PyBytes_FromString(tmp); } \
3843 if (!target) goto error; \
3844 } while(0)
3845
3846 convert(X509_get_default_cert_file_env(), ofile_env);
3847 convert(X509_get_default_cert_file(), ofile);
3848 convert(X509_get_default_cert_dir_env(), odir_env);
3849 convert(X509_get_default_cert_dir(), odir);
3850#undef convert
3851
Christian Heimes200bb1b2013-06-14 15:14:29 +02003852 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003853
3854 error:
3855 Py_XDECREF(ofile_env);
3856 Py_XDECREF(ofile);
3857 Py_XDECREF(odir_env);
3858 Py_XDECREF(odir);
3859 return NULL;
3860}
3861
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003862static PyObject*
3863asn1obj2py(ASN1_OBJECT *obj)
3864{
3865 int nid;
3866 const char *ln, *sn;
3867 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02003868 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003869
3870 nid = OBJ_obj2nid(obj);
3871 if (nid == NID_undef) {
3872 PyErr_Format(PyExc_ValueError, "Unknown object");
3873 return NULL;
3874 }
3875 sn = OBJ_nid2sn(nid);
3876 ln = OBJ_nid2ln(nid);
3877 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3878 if (buflen < 0) {
3879 _setSSLError(NULL, 0, __FILE__, __LINE__);
3880 return NULL;
3881 }
3882 if (buflen) {
3883 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3884 } else {
3885 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3886 }
3887}
3888
3889PyDoc_STRVAR(PySSL_txt2obj_doc,
3890"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3891\n\
3892Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3893objects are looked up by OID. With name=True short and long name are also\n\
3894matched.");
3895
3896static PyObject*
3897PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3898{
3899 char *kwlist[] = {"txt", "name", NULL};
3900 PyObject *result = NULL;
3901 char *txt;
3902 int name = 0;
3903 ASN1_OBJECT *obj;
3904
3905 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3906 kwlist, &txt, &name)) {
3907 return NULL;
3908 }
3909 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3910 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003911 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003912 return NULL;
3913 }
3914 result = asn1obj2py(obj);
3915 ASN1_OBJECT_free(obj);
3916 return result;
3917}
3918
3919PyDoc_STRVAR(PySSL_nid2obj_doc,
3920"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3921\n\
3922Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3923
3924static PyObject*
3925PySSL_nid2obj(PyObject *self, PyObject *args)
3926{
3927 PyObject *result = NULL;
3928 int nid;
3929 ASN1_OBJECT *obj;
3930
3931 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3932 return NULL;
3933 }
3934 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003935 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003936 return NULL;
3937 }
3938 obj = OBJ_nid2obj(nid);
3939 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003940 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003941 return NULL;
3942 }
3943 result = asn1obj2py(obj);
3944 ASN1_OBJECT_free(obj);
3945 return result;
3946}
3947
Christian Heimes46bebee2013-06-09 19:03:31 +02003948#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003949
3950static PyObject*
3951certEncodingType(DWORD encodingType)
3952{
3953 static PyObject *x509_asn = NULL;
3954 static PyObject *pkcs_7_asn = NULL;
3955
3956 if (x509_asn == NULL) {
3957 x509_asn = PyUnicode_InternFromString("x509_asn");
3958 if (x509_asn == NULL)
3959 return NULL;
3960 }
3961 if (pkcs_7_asn == NULL) {
3962 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
3963 if (pkcs_7_asn == NULL)
3964 return NULL;
3965 }
3966 switch(encodingType) {
3967 case X509_ASN_ENCODING:
3968 Py_INCREF(x509_asn);
3969 return x509_asn;
3970 case PKCS_7_ASN_ENCODING:
3971 Py_INCREF(pkcs_7_asn);
3972 return pkcs_7_asn;
3973 default:
3974 return PyLong_FromLong(encodingType);
3975 }
3976}
3977
3978static PyObject*
3979parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3980{
3981 CERT_ENHKEY_USAGE *usage;
3982 DWORD size, error, i;
3983 PyObject *retval;
3984
3985 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3986 error = GetLastError();
3987 if (error == CRYPT_E_NOT_FOUND) {
3988 Py_RETURN_TRUE;
3989 }
3990 return PyErr_SetFromWindowsErr(error);
3991 }
3992
3993 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3994 if (usage == NULL) {
3995 return PyErr_NoMemory();
3996 }
3997
3998 /* Now get the actual enhanced usage property */
3999 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4000 PyMem_Free(usage);
4001 error = GetLastError();
4002 if (error == CRYPT_E_NOT_FOUND) {
4003 Py_RETURN_TRUE;
4004 }
4005 return PyErr_SetFromWindowsErr(error);
4006 }
4007 retval = PySet_New(NULL);
4008 if (retval == NULL) {
4009 goto error;
4010 }
4011 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4012 if (usage->rgpszUsageIdentifier[i]) {
4013 PyObject *oid;
4014 int err;
4015 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4016 if (oid == NULL) {
4017 Py_CLEAR(retval);
4018 goto error;
4019 }
4020 err = PySet_Add(retval, oid);
4021 Py_DECREF(oid);
4022 if (err == -1) {
4023 Py_CLEAR(retval);
4024 goto error;
4025 }
4026 }
4027 }
4028 error:
4029 PyMem_Free(usage);
4030 return retval;
4031}
4032
4033PyDoc_STRVAR(PySSL_enum_certificates_doc,
4034"enum_certificates(store_name) -> []\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02004035\n\
4036Retrieve certificates from Windows' cert store. store_name may be one of\n\
4037'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
Christian Heimes44109d72013-11-22 01:51:30 +01004038The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02004039encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
Christian Heimes44109d72013-11-22 01:51:30 +01004040PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
4041boolean True.");
Bill Janssen40a0f662008-08-12 16:56:25 +00004042
Christian Heimes46bebee2013-06-09 19:03:31 +02004043static PyObject *
Christian Heimes44109d72013-11-22 01:51:30 +01004044PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes46bebee2013-06-09 19:03:31 +02004045{
Christian Heimes44109d72013-11-22 01:51:30 +01004046 char *kwlist[] = {"store_name", NULL};
Christian Heimes46bebee2013-06-09 19:03:31 +02004047 char *store_name;
Christian Heimes46bebee2013-06-09 19:03:31 +02004048 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004049 PCCERT_CONTEXT pCertCtx = NULL;
4050 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004051 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004052
Christian Heimes44109d72013-11-22 01:51:30 +01004053 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_certificates",
4054 kwlist, &store_name)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004055 return NULL;
4056 }
Christian Heimes44109d72013-11-22 01:51:30 +01004057 result = PyList_New(0);
4058 if (result == NULL) {
4059 return NULL;
4060 }
4061 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4062 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004063 Py_DECREF(result);
4064 return PyErr_SetFromWindowsErr(GetLastError());
4065 }
4066
Christian Heimes44109d72013-11-22 01:51:30 +01004067 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4068 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4069 pCertCtx->cbCertEncoded);
4070 if (!cert) {
4071 Py_CLEAR(result);
4072 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004073 }
Christian Heimes44109d72013-11-22 01:51:30 +01004074 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4075 Py_CLEAR(result);
4076 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004077 }
Christian Heimes44109d72013-11-22 01:51:30 +01004078 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4079 if (keyusage == Py_True) {
4080 Py_DECREF(keyusage);
4081 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004082 }
Christian Heimes44109d72013-11-22 01:51:30 +01004083 if (keyusage == NULL) {
4084 Py_CLEAR(result);
4085 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004086 }
Christian Heimes44109d72013-11-22 01:51:30 +01004087 if ((tup = PyTuple_New(3)) == NULL) {
4088 Py_CLEAR(result);
4089 break;
4090 }
4091 PyTuple_SET_ITEM(tup, 0, cert);
4092 cert = NULL;
4093 PyTuple_SET_ITEM(tup, 1, enc);
4094 enc = NULL;
4095 PyTuple_SET_ITEM(tup, 2, keyusage);
4096 keyusage = NULL;
4097 if (PyList_Append(result, tup) < 0) {
4098 Py_CLEAR(result);
4099 break;
4100 }
4101 Py_CLEAR(tup);
4102 }
4103 if (pCertCtx) {
4104 /* loop ended with an error, need to clean up context manually */
4105 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004106 }
4107
4108 /* In error cases cert, enc and tup may not be NULL */
4109 Py_XDECREF(cert);
4110 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004111 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004112 Py_XDECREF(tup);
4113
4114 if (!CertCloseStore(hStore, 0)) {
4115 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004116 Py_XDECREF(result);
4117 return PyErr_SetFromWindowsErr(GetLastError());
4118 }
4119 return result;
4120}
4121
4122PyDoc_STRVAR(PySSL_enum_crls_doc,
4123"enum_crls(store_name) -> []\n\
4124\n\
4125Retrieve CRLs from Windows' cert store. store_name may be one of\n\
4126'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
4127The function returns a list of (bytes, encoding_type) tuples. The\n\
4128encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
4129PKCS_7_ASN_ENCODING.");
4130
4131static PyObject *
4132PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
4133{
4134 char *kwlist[] = {"store_name", NULL};
4135 char *store_name;
4136 HCERTSTORE hStore = NULL;
4137 PCCRL_CONTEXT pCrlCtx = NULL;
4138 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4139 PyObject *result = NULL;
4140
4141 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_crls",
4142 kwlist, &store_name)) {
4143 return NULL;
4144 }
4145 result = PyList_New(0);
4146 if (result == NULL) {
4147 return NULL;
4148 }
4149 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4150 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004151 Py_DECREF(result);
4152 return PyErr_SetFromWindowsErr(GetLastError());
4153 }
Christian Heimes44109d72013-11-22 01:51:30 +01004154
4155 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4156 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4157 pCrlCtx->cbCrlEncoded);
4158 if (!crl) {
4159 Py_CLEAR(result);
4160 break;
4161 }
4162 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4163 Py_CLEAR(result);
4164 break;
4165 }
4166 if ((tup = PyTuple_New(2)) == NULL) {
4167 Py_CLEAR(result);
4168 break;
4169 }
4170 PyTuple_SET_ITEM(tup, 0, crl);
4171 crl = NULL;
4172 PyTuple_SET_ITEM(tup, 1, enc);
4173 enc = NULL;
4174
4175 if (PyList_Append(result, tup) < 0) {
4176 Py_CLEAR(result);
4177 break;
4178 }
4179 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004180 }
Christian Heimes44109d72013-11-22 01:51:30 +01004181 if (pCrlCtx) {
4182 /* loop ended with an error, need to clean up context manually */
4183 CertFreeCRLContext(pCrlCtx);
4184 }
4185
4186 /* In error cases cert, enc and tup may not be NULL */
4187 Py_XDECREF(crl);
4188 Py_XDECREF(enc);
4189 Py_XDECREF(tup);
4190
4191 if (!CertCloseStore(hStore, 0)) {
4192 /* This error case might shadow another exception.*/
4193 Py_XDECREF(result);
4194 return PyErr_SetFromWindowsErr(GetLastError());
4195 }
4196 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004197}
Christian Heimes44109d72013-11-22 01:51:30 +01004198
4199#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004200
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004201/* List of functions exported by this module. */
4202
4203static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004204 {"_test_decode_cert", PySSL_test_decode_certificate,
4205 METH_VARARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004206 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
4207 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02004208 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
4209 PySSL_RAND_bytes_doc},
4210 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
4211 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerbeeb5122014-11-28 13:28:25 +01004212#ifdef HAVE_RAND_EGD
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004213 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004214 PySSL_RAND_egd_doc},
Victor Stinnerbeeb5122014-11-28 13:28:25 +01004215#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004216 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
4217 PySSL_RAND_status_doc},
Christian Heimes200bb1b2013-06-14 15:14:29 +02004218 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02004219 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02004220#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004221 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
4222 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
4223 {"enum_crls", (PyCFunction)PySSL_enum_crls,
4224 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02004225#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004226 {"txt2obj", (PyCFunction)PySSL_txt2obj,
4227 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
4228 {"nid2obj", (PyCFunction)PySSL_nid2obj,
4229 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004230 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004231};
4232
4233
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004234#ifdef WITH_THREAD
4235
4236/* an implementation of OpenSSL threading operations in terms
4237 of the Python C thread library */
4238
4239static PyThread_type_lock *_ssl_locks = NULL;
4240
Christian Heimes4d98ca92013-08-19 17:36:29 +02004241#if OPENSSL_VERSION_NUMBER >= 0x10000000
4242/* use new CRYPTO_THREADID API. */
4243static void
4244_ssl_threadid_callback(CRYPTO_THREADID *id)
4245{
4246 CRYPTO_THREADID_set_numeric(id,
4247 (unsigned long)PyThread_get_thread_ident());
4248}
4249#else
4250/* deprecated CRYPTO_set_id_callback() API. */
4251static unsigned long
4252_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004253 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004254}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004255#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004256
Bill Janssen6e027db2007-11-15 22:23:56 +00004257static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004258 (int mode, int n, const char *file, int line) {
4259 /* this function is needed to perform locking on shared data
4260 structures. (Note that OpenSSL uses a number of global data
4261 structures that will be implicitly shared whenever multiple
4262 threads use OpenSSL.) Multi-threaded applications will
4263 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004264
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004265 locking_function() must be able to handle up to
4266 CRYPTO_num_locks() different mutex locks. It sets the n-th
4267 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004268
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004269 file and line are the file number of the function setting the
4270 lock. They can be useful for debugging.
4271 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004272
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004273 if ((_ssl_locks == NULL) ||
4274 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4275 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004276
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004277 if (mode & CRYPTO_LOCK) {
4278 PyThread_acquire_lock(_ssl_locks[n], 1);
4279 } else {
4280 PyThread_release_lock(_ssl_locks[n]);
4281 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004282}
4283
4284static int _setup_ssl_threads(void) {
4285
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004286 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004288 if (_ssl_locks == NULL) {
4289 _ssl_locks_count = CRYPTO_num_locks();
4290 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02004291 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004292 if (_ssl_locks == NULL)
4293 return 0;
4294 memset(_ssl_locks, 0,
4295 sizeof(PyThread_type_lock) * _ssl_locks_count);
4296 for (i = 0; i < _ssl_locks_count; i++) {
4297 _ssl_locks[i] = PyThread_allocate_lock();
4298 if (_ssl_locks[i] == NULL) {
4299 unsigned int j;
4300 for (j = 0; j < i; j++) {
4301 PyThread_free_lock(_ssl_locks[j]);
4302 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004303 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004304 return 0;
4305 }
4306 }
4307 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004308#if OPENSSL_VERSION_NUMBER >= 0x10000000
4309 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4310#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004311 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004312#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004313 }
4314 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004315}
4316
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004317#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004318
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004319PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004320"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004321for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004322
Martin v. Löwis1a214512008-06-11 05:26:20 +00004323
4324static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004325 PyModuleDef_HEAD_INIT,
4326 "_ssl",
4327 module_doc,
4328 -1,
4329 PySSL_methods,
4330 NULL,
4331 NULL,
4332 NULL,
4333 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004334};
4335
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004336
4337static void
4338parse_openssl_version(unsigned long libver,
4339 unsigned int *major, unsigned int *minor,
4340 unsigned int *fix, unsigned int *patch,
4341 unsigned int *status)
4342{
4343 *status = libver & 0xF;
4344 libver >>= 4;
4345 *patch = libver & 0xFF;
4346 libver >>= 8;
4347 *fix = libver & 0xFF;
4348 libver >>= 8;
4349 *minor = libver & 0xFF;
4350 libver >>= 8;
4351 *major = libver & 0xFF;
4352}
4353
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004354PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004355PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004356{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004357 PyObject *m, *d, *r;
4358 unsigned long libver;
4359 unsigned int major, minor, fix, patch, status;
4360 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004361 struct py_ssl_error_code *errcode;
4362 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004363
Antoine Pitrou152efa22010-05-16 18:19:27 +00004364 if (PyType_Ready(&PySSLContext_Type) < 0)
4365 return NULL;
4366 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004367 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004368 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4369 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004370
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004371 m = PyModule_Create(&_sslmodule);
4372 if (m == NULL)
4373 return NULL;
4374 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004375
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004376 /* Load _socket module and its C API */
4377 socket_api = PySocketModule_ImportModuleAndAPI();
4378 if (!socket_api)
4379 return NULL;
4380 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004381
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004382 /* Init OpenSSL */
4383 SSL_load_error_strings();
4384 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004385#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004386 /* note that this will start threading if not already started */
4387 if (!_setup_ssl_threads()) {
4388 return NULL;
4389 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004390#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004391 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004392
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004393 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004394 sslerror_type_slots[0].pfunc = PyExc_OSError;
4395 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004396 if (PySSLErrorObject == NULL)
4397 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004398
Antoine Pitrou41032a62011-10-27 23:56:55 +02004399 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4400 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4401 PySSLErrorObject, NULL);
4402 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4403 "ssl.SSLWantReadError", SSLWantReadError_doc,
4404 PySSLErrorObject, NULL);
4405 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4406 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4407 PySSLErrorObject, NULL);
4408 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4409 "ssl.SSLSyscallError", SSLSyscallError_doc,
4410 PySSLErrorObject, NULL);
4411 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4412 "ssl.SSLEOFError", SSLEOFError_doc,
4413 PySSLErrorObject, NULL);
4414 if (PySSLZeroReturnErrorObject == NULL
4415 || PySSLWantReadErrorObject == NULL
4416 || PySSLWantWriteErrorObject == NULL
4417 || PySSLSyscallErrorObject == NULL
4418 || PySSLEOFErrorObject == NULL)
4419 return NULL;
4420 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4421 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4422 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4423 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4424 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4425 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004426 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004427 if (PyDict_SetItemString(d, "_SSLContext",
4428 (PyObject *)&PySSLContext_Type) != 0)
4429 return NULL;
4430 if (PyDict_SetItemString(d, "_SSLSocket",
4431 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004432 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004433 if (PyDict_SetItemString(d, "MemoryBIO",
4434 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4435 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004436 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4437 PY_SSL_ERROR_ZERO_RETURN);
4438 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4439 PY_SSL_ERROR_WANT_READ);
4440 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4441 PY_SSL_ERROR_WANT_WRITE);
4442 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4443 PY_SSL_ERROR_WANT_X509_LOOKUP);
4444 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4445 PY_SSL_ERROR_SYSCALL);
4446 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4447 PY_SSL_ERROR_SSL);
4448 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4449 PY_SSL_ERROR_WANT_CONNECT);
4450 /* non ssl.h errorcodes */
4451 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4452 PY_SSL_ERROR_EOF);
4453 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4454 PY_SSL_ERROR_INVALID_ERROR_CODE);
4455 /* cert requirements */
4456 PyModule_AddIntConstant(m, "CERT_NONE",
4457 PY_SSL_CERT_NONE);
4458 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4459 PY_SSL_CERT_OPTIONAL);
4460 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4461 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004462 /* CRL verification for verification_flags */
4463 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4464 0);
4465 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4466 X509_V_FLAG_CRL_CHECK);
4467 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4468 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4469 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4470 X509_V_FLAG_X509_STRICT);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004471
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004472 /* Alert Descriptions from ssl.h */
4473 /* note RESERVED constants no longer intended for use have been removed */
4474 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4475
4476#define ADD_AD_CONSTANT(s) \
4477 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4478 SSL_AD_##s)
4479
4480 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4481 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4482 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4483 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4484 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4485 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4486 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4487 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4488 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4489 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4490 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4491 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4492 ADD_AD_CONSTANT(UNKNOWN_CA);
4493 ADD_AD_CONSTANT(ACCESS_DENIED);
4494 ADD_AD_CONSTANT(DECODE_ERROR);
4495 ADD_AD_CONSTANT(DECRYPT_ERROR);
4496 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4497 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4498 ADD_AD_CONSTANT(INTERNAL_ERROR);
4499 ADD_AD_CONSTANT(USER_CANCELLED);
4500 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004501 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004502#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4503 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4504#endif
4505#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4506 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4507#endif
4508#ifdef SSL_AD_UNRECOGNIZED_NAME
4509 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4510#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004511#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4512 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4513#endif
4514#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4515 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4516#endif
4517#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4518 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4519#endif
4520
4521#undef ADD_AD_CONSTANT
4522
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004523 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004524#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004525 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4526 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004527#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004528#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004529 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4530 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004531#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004532 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4533 PY_SSL_VERSION_SSL23);
4534 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4535 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004536#if HAVE_TLSv1_2
4537 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4538 PY_SSL_VERSION_TLS1_1);
4539 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4540 PY_SSL_VERSION_TLS1_2);
4541#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004542
Antoine Pitroub5218772010-05-21 09:56:06 +00004543 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004544 PyModule_AddIntConstant(m, "OP_ALL",
4545 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004546 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4547 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4548 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004549#if HAVE_TLSv1_2
4550 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4551 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4552#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004553 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4554 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004555 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004556#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004557 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004558#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004559#ifdef SSL_OP_NO_COMPRESSION
4560 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4561 SSL_OP_NO_COMPRESSION);
4562#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004563
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004564#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004565 r = Py_True;
4566#else
4567 r = Py_False;
4568#endif
4569 Py_INCREF(r);
4570 PyModule_AddObject(m, "HAS_SNI", r);
4571
Antoine Pitroud6494802011-07-21 01:11:30 +02004572 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004573 Py_INCREF(r);
4574 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4575
Antoine Pitrou501da612011-12-21 09:27:41 +01004576#ifdef OPENSSL_NO_ECDH
4577 r = Py_False;
4578#else
4579 r = Py_True;
4580#endif
4581 Py_INCREF(r);
4582 PyModule_AddObject(m, "HAS_ECDH", r);
4583
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004584#ifdef OPENSSL_NPN_NEGOTIATED
4585 r = Py_True;
4586#else
4587 r = Py_False;
4588#endif
4589 Py_INCREF(r);
4590 PyModule_AddObject(m, "HAS_NPN", r);
4591
Benjamin Petersoncca27322015-01-23 16:35:37 -05004592#ifdef HAVE_ALPN
4593 r = Py_True;
4594#else
4595 r = Py_False;
4596#endif
4597 Py_INCREF(r);
4598 PyModule_AddObject(m, "HAS_ALPN", r);
4599
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004600 /* Mappings for error codes */
4601 err_codes_to_names = PyDict_New();
4602 err_names_to_codes = PyDict_New();
4603 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4604 return NULL;
4605 errcode = error_codes;
4606 while (errcode->mnemonic != NULL) {
4607 PyObject *mnemo, *key;
4608 mnemo = PyUnicode_FromString(errcode->mnemonic);
4609 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4610 if (mnemo == NULL || key == NULL)
4611 return NULL;
4612 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4613 return NULL;
4614 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4615 return NULL;
4616 Py_DECREF(key);
4617 Py_DECREF(mnemo);
4618 errcode++;
4619 }
4620 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4621 return NULL;
4622 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4623 return NULL;
4624
4625 lib_codes_to_names = PyDict_New();
4626 if (lib_codes_to_names == NULL)
4627 return NULL;
4628 libcode = library_codes;
4629 while (libcode->library != NULL) {
4630 PyObject *mnemo, *key;
4631 key = PyLong_FromLong(libcode->code);
4632 mnemo = PyUnicode_FromString(libcode->library);
4633 if (key == NULL || mnemo == NULL)
4634 return NULL;
4635 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4636 return NULL;
4637 Py_DECREF(key);
4638 Py_DECREF(mnemo);
4639 libcode++;
4640 }
4641 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4642 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004643
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004644 /* OpenSSL version */
4645 /* SSLeay() gives us the version of the library linked against,
4646 which could be different from the headers version.
4647 */
4648 libver = SSLeay();
4649 r = PyLong_FromUnsignedLong(libver);
4650 if (r == NULL)
4651 return NULL;
4652 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4653 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004654 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004655 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4656 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4657 return NULL;
4658 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4659 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4660 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004661
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004662 libver = OPENSSL_VERSION_NUMBER;
4663 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4664 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4665 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4666 return NULL;
4667
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004668 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004669}