blob: fb03513d89b02ddafe5fa8631a285ff49aa49711 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#ifdef WITH_THREAD
22#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020023
Christian Heimesf77b4b22013-08-21 13:26:05 +020024
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020025#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
26 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
27#define PySSL_END_ALLOW_THREADS_S(save) \
28 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000029#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000030 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020031 PySSL_BEGIN_ALLOW_THREADS_S(_save);
32#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
33#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
34#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000035
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000036#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000037
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020038#define PySSL_BEGIN_ALLOW_THREADS_S(save)
39#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000040#define PySSL_BEGIN_ALLOW_THREADS
41#define PySSL_BLOCK_THREADS
42#define PySSL_UNBLOCK_THREADS
43#define PySSL_END_ALLOW_THREADS
44
45#endif
46
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010047/* Include symbols from _socket module */
48#include "socketmodule.h"
49
50static PySocketModule_APIObject PySocketModule;
51
52#if defined(HAVE_POLL_H)
53#include <poll.h>
54#elif defined(HAVE_SYS_POLL_H)
55#include <sys/poll.h>
56#endif
57
58/* Include OpenSSL header files */
59#include "openssl/rsa.h"
60#include "openssl/crypto.h"
61#include "openssl/x509.h"
62#include "openssl/x509v3.h"
63#include "openssl/pem.h"
64#include "openssl/ssl.h"
65#include "openssl/err.h"
66#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020067#include "openssl/bio.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010068
69/* SSL error object */
70static PyObject *PySSLErrorObject;
71static PyObject *PySSLZeroReturnErrorObject;
72static PyObject *PySSLWantReadErrorObject;
73static PyObject *PySSLWantWriteErrorObject;
74static PyObject *PySSLSyscallErrorObject;
75static PyObject *PySSLEOFErrorObject;
76
77/* Error mappings */
78static PyObject *err_codes_to_names;
79static PyObject *err_names_to_codes;
80static PyObject *lib_codes_to_names;
81
82struct py_ssl_error_code {
83 const char *mnemonic;
84 int library, reason;
85};
86struct py_ssl_library_code {
87 const char *library;
88 int code;
89};
90
91/* Include generated data (error codes) */
92#include "_ssl_data.h"
93
94/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
95 http://www.openssl.org/news/changelog.html
96 */
97#if OPENSSL_VERSION_NUMBER >= 0x10001000L
98# define HAVE_TLSv1_2 1
99#else
100# define HAVE_TLSv1_2 0
101#endif
102
Christian Heimes470fba12013-11-28 15:12:15 +0100103/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100104 * This includes the SSL_set_SSL_CTX() function.
105 */
106#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
107# define HAVE_SNI 1
108#else
109# define HAVE_SNI 0
110#endif
111
Benjamin Petersoncca27322015-01-23 16:35:37 -0500112/* ALPN added in OpenSSL 1.0.2 */
Benjamin Peterson07f05152015-01-27 11:10:18 -0500113#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x1000200fL && !defined(OPENSSL_NO_TLSEXT)
Benjamin Petersoncca27322015-01-23 16:35:37 -0500114# define HAVE_ALPN
115#endif
116
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000117enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000118 /* these mirror ssl.h */
119 PY_SSL_ERROR_NONE,
120 PY_SSL_ERROR_SSL,
121 PY_SSL_ERROR_WANT_READ,
122 PY_SSL_ERROR_WANT_WRITE,
123 PY_SSL_ERROR_WANT_X509_LOOKUP,
124 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
125 PY_SSL_ERROR_ZERO_RETURN,
126 PY_SSL_ERROR_WANT_CONNECT,
127 /* start of non ssl.h errorcodes */
128 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
129 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
130 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000131};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000132
Thomas Woutersed03b412007-08-28 21:37:11 +0000133enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000134 PY_SSL_CLIENT,
135 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000136};
137
138enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000139 PY_SSL_CERT_NONE,
140 PY_SSL_CERT_OPTIONAL,
141 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000142};
143
144enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000145 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200146 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000147 PY_SSL_VERSION_SSL23,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100148#if HAVE_TLSv1_2
149 PY_SSL_VERSION_TLS1,
150 PY_SSL_VERSION_TLS1_1,
151 PY_SSL_VERSION_TLS1_2
152#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000153 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000154#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100155};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200156
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000157#ifdef WITH_THREAD
158
159/* serves as a flag to see whether we've initialized the SSL thread support. */
160/* 0 means no, greater than 0 means yes */
161
162static unsigned int _ssl_locks_count = 0;
163
164#endif /* def WITH_THREAD */
165
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000166/* SSL socket object */
167
168#define X509_NAME_MAXLEN 256
169
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000170/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
171 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
172 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
173#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000174# define HAVE_SSL_CTX_CLEAR_OPTIONS
175#else
176# undef HAVE_SSL_CTX_CLEAR_OPTIONS
177#endif
178
Antoine Pitroud6494802011-07-21 01:11:30 +0200179/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
180 * older SSL, but let's be safe */
181#define PySSL_CB_MAXLEN 128
182
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100183
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000184typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000185 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000186 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100187#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -0500188 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100189 int npn_protocols_len;
190#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500191#ifdef HAVE_ALPN
192 unsigned char *alpn_protocols;
193 int alpn_protocols_len;
194#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100195#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200196 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100197#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100198 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000199} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000200
Antoine Pitrou152efa22010-05-16 18:19:27 +0000201typedef struct {
202 PyObject_HEAD
203 PyObject *Socket; /* weakref to socket on which we're layered */
204 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100205 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000206 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200207 char shutdown_seen_zero;
208 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200209 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200210 PyObject *owner; /* Python level "owner" passed to servername callback */
211 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000212} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000213
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200214typedef struct {
215 PyObject_HEAD
216 BIO *bio;
217 int eof_written;
218} PySSLMemoryBIO;
219
Antoine Pitrou152efa22010-05-16 18:19:27 +0000220static PyTypeObject PySSLContext_Type;
221static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200222static PyTypeObject PySSLMemoryBIO_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000223
224static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
225static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000226static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000227 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000228static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
229static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000230
Antoine Pitrou152efa22010-05-16 18:19:27 +0000231#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
232#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200233#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000234
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000235typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000236 SOCKET_IS_NONBLOCKING,
237 SOCKET_IS_BLOCKING,
238 SOCKET_HAS_TIMED_OUT,
239 SOCKET_HAS_BEEN_CLOSED,
240 SOCKET_TOO_LARGE_FOR_SELECT,
241 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000242} timeout_state;
243
Thomas Woutersed03b412007-08-28 21:37:11 +0000244/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000245#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200246#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000247
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200248/* Get the socket from a PySSLSocket, if it has one */
249#define GET_SOCKET(obj) ((obj)->Socket ? \
250 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200251
252/*
253 * SSL errors.
254 */
255
256PyDoc_STRVAR(SSLError_doc,
257"An error occurred in the SSL implementation.");
258
259PyDoc_STRVAR(SSLZeroReturnError_doc,
260"SSL/TLS session closed cleanly.");
261
262PyDoc_STRVAR(SSLWantReadError_doc,
263"Non-blocking SSL socket needs to read more data\n"
264"before the requested operation can be completed.");
265
266PyDoc_STRVAR(SSLWantWriteError_doc,
267"Non-blocking SSL socket needs to write more data\n"
268"before the requested operation can be completed.");
269
270PyDoc_STRVAR(SSLSyscallError_doc,
271"System error when attempting SSL operation.");
272
273PyDoc_STRVAR(SSLEOFError_doc,
274"SSL/TLS connection terminated abruptly.");
275
276static PyObject *
277SSLError_str(PyOSErrorObject *self)
278{
279 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
280 Py_INCREF(self->strerror);
281 return self->strerror;
282 }
283 else
284 return PyObject_Str(self->args);
285}
286
287static PyType_Slot sslerror_type_slots[] = {
288 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
289 {Py_tp_doc, SSLError_doc},
290 {Py_tp_str, SSLError_str},
291 {0, 0},
292};
293
294static PyType_Spec sslerror_type_spec = {
295 "ssl.SSLError",
296 sizeof(PyOSErrorObject),
297 0,
298 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
299 sslerror_type_slots
300};
301
302static void
303fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
304 int lineno, unsigned long errcode)
305{
306 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
307 PyObject *init_value, *msg, *key;
308 _Py_IDENTIFIER(reason);
309 _Py_IDENTIFIER(library);
310
311 if (errcode != 0) {
312 int lib, reason;
313
314 lib = ERR_GET_LIB(errcode);
315 reason = ERR_GET_REASON(errcode);
316 key = Py_BuildValue("ii", lib, reason);
317 if (key == NULL)
318 goto fail;
319 reason_obj = PyDict_GetItem(err_codes_to_names, key);
320 Py_DECREF(key);
321 if (reason_obj == NULL) {
322 /* XXX if reason < 100, it might reflect a library number (!!) */
323 PyErr_Clear();
324 }
325 key = PyLong_FromLong(lib);
326 if (key == NULL)
327 goto fail;
328 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
329 Py_DECREF(key);
330 if (lib_obj == NULL) {
331 PyErr_Clear();
332 }
333 if (errstr == NULL)
334 errstr = ERR_reason_error_string(errcode);
335 }
336 if (errstr == NULL)
337 errstr = "unknown error";
338
339 if (reason_obj && lib_obj)
340 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
341 lib_obj, reason_obj, errstr, lineno);
342 else if (lib_obj)
343 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
344 lib_obj, errstr, lineno);
345 else
346 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200347 if (msg == NULL)
348 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100349
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200350 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100351 if (init_value == NULL)
352 goto fail;
353
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200354 err_value = PyObject_CallObject(type, init_value);
355 Py_DECREF(init_value);
356 if (err_value == NULL)
357 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100358
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200359 if (reason_obj == NULL)
360 reason_obj = Py_None;
361 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
362 goto fail;
363 if (lib_obj == NULL)
364 lib_obj = Py_None;
365 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
366 goto fail;
367 PyErr_SetObject(type, err_value);
368fail:
369 Py_XDECREF(err_value);
370}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000371
372static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000373PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000374{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200375 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200376 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000377 int err;
378 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200379 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000380
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000381 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200382 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000383
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000384 if (obj->ssl != NULL) {
385 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000386
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000387 switch (err) {
388 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200389 errstr = "TLS/SSL connection has been closed (EOF)";
390 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000391 p = PY_SSL_ERROR_ZERO_RETURN;
392 break;
393 case SSL_ERROR_WANT_READ:
394 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200395 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000396 p = PY_SSL_ERROR_WANT_READ;
397 break;
398 case SSL_ERROR_WANT_WRITE:
399 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200400 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000401 errstr = "The operation did not complete (write)";
402 break;
403 case SSL_ERROR_WANT_X509_LOOKUP:
404 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000405 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000406 break;
407 case SSL_ERROR_WANT_CONNECT:
408 p = PY_SSL_ERROR_WANT_CONNECT;
409 errstr = "The operation did not complete (connect)";
410 break;
411 case SSL_ERROR_SYSCALL:
412 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000413 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200414 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000415 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000416 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200417 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000418 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200419 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000420 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000421 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000422 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200423 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000424 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200425 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000426 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000427 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200428 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000429 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000430 }
431 } else {
432 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000433 }
434 break;
435 }
436 case SSL_ERROR_SSL:
437 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000438 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200439 if (e == 0)
440 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000441 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000442 break;
443 }
444 default:
445 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
446 errstr = "Invalid error code";
447 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000448 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200449 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000450 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000451 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000452}
453
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000454static PyObject *
455_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
456
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200457 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000458 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200459 else
460 errcode = 0;
461 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000462 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000463 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000464}
465
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200466/*
467 * SSL objects
468 */
469
Antoine Pitrou152efa22010-05-16 18:19:27 +0000470static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100471newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000472 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200473 char *server_hostname,
474 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000475{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000476 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100477 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200478 PyObject *hostname;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200479 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000480
Antoine Pitrou152efa22010-05-16 18:19:27 +0000481 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000482 if (self == NULL)
483 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000484
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000485 self->peer_cert = NULL;
486 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000487 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100488 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200489 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200490 self->handshake_done = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200491 self->owner = NULL;
492 if (server_hostname != NULL) {
493 hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
494 "idna", "strict");
495 if (hostname == NULL) {
496 Py_DECREF(self);
497 return NULL;
498 }
499 self->server_hostname = hostname;
500 } else
501 self->server_hostname = NULL;
502
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100503 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000504
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000505 /* Make sure the SSL error state is initialized */
506 (void) ERR_get_state();
507 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000508
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000509 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000510 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000511 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200512 SSL_set_app_data(self->ssl, self);
513 if (sock) {
514 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
515 } else {
516 /* BIOs are reference counted and SSL_set_bio borrows our reference.
517 * To prevent a double free in memory_bio_dealloc() we need to take an
518 * extra reference here. */
519 CRYPTO_add(&inbio->bio->references, 1, CRYPTO_LOCK_BIO);
520 CRYPTO_add(&outbio->bio->references, 1, CRYPTO_LOCK_BIO);
521 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
522 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200523 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000524#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200525 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000526#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200527 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000528
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100529#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000530 if (server_hostname != NULL)
531 SSL_set_tlsext_host_name(self->ssl, server_hostname);
532#endif
533
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000534 /* If the socket is in non-blocking mode or timeout mode, set the BIO
535 * to non-blocking mode (blocking is the default)
536 */
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
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001844 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001845 PySSL_BEGIN_ALLOW_THREADS
1846 count = SSL_read(self->ssl, mem, len);
1847 err = SSL_get_error(self->ssl, count);
1848 PySSL_END_ALLOW_THREADS
1849 if (PyErr_CheckSignals())
1850 goto error;
1851 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001852 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001853 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001854 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001855 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1856 (SSL_get_shutdown(self->ssl) ==
1857 SSL_RECEIVED_SHUTDOWN))
1858 {
1859 count = 0;
1860 goto done;
1861 } else {
1862 sockstate = SOCKET_OPERATION_OK;
1863 }
1864 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001865 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001866 "The read operation timed out");
1867 goto error;
1868 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1869 break;
1870 }
1871 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1872 if (count <= 0) {
1873 PySSL_SetError(self, count, __FILE__, __LINE__);
1874 goto error;
1875 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001876
1877done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001878 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001879 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001880 _PyBytes_Resize(&dest, count);
1881 return dest;
1882 }
1883 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001884 PyBuffer_Release(&buf);
1885 return PyLong_FromLong(count);
1886 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001887
1888error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001889 Py_XDECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001890 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001891 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001892 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001893 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001894 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001895}
1896
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001897PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001898"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001899\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001900Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001901
Antoine Pitrou152efa22010-05-16 18:19:27 +00001902static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001903{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001904 int err, ssl_err, sockstate, nonblocking;
1905 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001906 PySocketSockObject *sock = GET_SOCKET(self);
Bill Janssen40a0f662008-08-12 16:56:25 +00001907
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001908 if (sock != NULL) {
1909 /* Guard against closed socket */
1910 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1911 _setSSLError("Underlying socket connection gone",
1912 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1913 return NULL;
1914 }
1915 Py_INCREF(sock);
1916
1917 /* Just in case the blocking state of the socket has been changed */
1918 nonblocking = (sock->sock_timeout >= 0.0);
1919 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1920 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001921 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001922
1923 while (1) {
1924 PySSL_BEGIN_ALLOW_THREADS
1925 /* Disable read-ahead so that unwrap can work correctly.
1926 * Otherwise OpenSSL might read in too much data,
1927 * eating clear text data that happens to be
1928 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001929 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001930 * function is used and the shutdown_seen_zero != 0
1931 * condition is met.
1932 */
1933 if (self->shutdown_seen_zero)
1934 SSL_set_read_ahead(self->ssl, 0);
1935 err = SSL_shutdown(self->ssl);
1936 PySSL_END_ALLOW_THREADS
1937 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1938 if (err > 0)
1939 break;
1940 if (err == 0) {
1941 /* Don't loop endlessly; instead preserve legacy
1942 behaviour of trying SSL_shutdown() only twice.
1943 This looks necessary for OpenSSL < 0.9.8m */
1944 if (++zeros > 1)
1945 break;
1946 /* Shutdown was sent, now try receiving */
1947 self->shutdown_seen_zero = 1;
1948 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001949 }
1950
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001951 /* Possibly retry shutdown until timeout or failure */
1952 ssl_err = SSL_get_error(self->ssl, err);
1953 if (ssl_err == SSL_ERROR_WANT_READ)
1954 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1955 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1956 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1957 else
1958 break;
1959 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1960 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001961 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001962 "The read operation timed out");
1963 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001964 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001965 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001966 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001967 }
1968 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1969 PyErr_SetString(PySSLErrorObject,
1970 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001971 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001972 }
1973 else if (sockstate != SOCKET_OPERATION_OK)
1974 /* Retain the SSL error code */
1975 break;
1976 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001977
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001978 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001979 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001980 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001981 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001982 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001983 /* It's already INCREF'ed */
1984 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001985 else
1986 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001987
1988error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001989 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001990 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001991}
1992
1993PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1994"shutdown(s) -> socket\n\
1995\n\
1996Does the SSL shutdown handshake with the remote end, and returns\n\
1997the underlying socket object.");
1998
Antoine Pitroud6494802011-07-21 01:11:30 +02001999static PyObject *
2000PySSL_tls_unique_cb(PySSLSocket *self)
2001{
2002 PyObject *retval = NULL;
2003 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002004 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002005
2006 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2007 /* if session is resumed XOR we are the client */
2008 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2009 }
2010 else {
2011 /* if a new session XOR we are the server */
2012 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2013 }
2014
2015 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002016 if (len == 0)
2017 Py_RETURN_NONE;
2018
2019 retval = PyBytes_FromStringAndSize(buf, len);
2020
2021 return retval;
2022}
2023
2024PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
2025"tls_unique_cb() -> bytes\n\
2026\n\
2027Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
2028\n\
2029If the TLS handshake is not yet complete, None is returned");
2030
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002031static PyGetSetDef ssl_getsetlist[] = {
2032 {"context", (getter) PySSL_get_context,
2033 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002034 {"server_side", (getter) PySSL_get_server_side, NULL,
2035 PySSL_get_server_side_doc},
2036 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2037 PySSL_get_server_hostname_doc},
2038 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2039 PySSL_get_owner_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002040 {NULL}, /* sentinel */
2041};
2042
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002043static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002044 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
2045 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
2046 PySSL_SSLwrite_doc},
2047 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
2048 PySSL_SSLread_doc},
2049 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
2050 PySSL_SSLpending_doc},
2051 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
2052 PySSL_peercert_doc},
2053 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002054 {"shared_ciphers", (PyCFunction)PySSL_shared_ciphers, METH_NOARGS},
Antoine Pitrou47e40422014-09-04 21:00:10 +02002055 {"version", (PyCFunction)PySSL_version, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002056#ifdef OPENSSL_NPN_NEGOTIATED
2057 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
2058#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002059#ifdef HAVE_ALPN
2060 {"selected_alpn_protocol", (PyCFunction)PySSL_selected_alpn_protocol, METH_NOARGS},
2061#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002062 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002063 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
2064 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02002065 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
2066 PySSL_tls_unique_cb_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002067 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002068};
2069
Antoine Pitrou152efa22010-05-16 18:19:27 +00002070static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002071 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002072 "_ssl._SSLSocket", /*tp_name*/
2073 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002074 0, /*tp_itemsize*/
2075 /* methods */
2076 (destructor)PySSL_dealloc, /*tp_dealloc*/
2077 0, /*tp_print*/
2078 0, /*tp_getattr*/
2079 0, /*tp_setattr*/
2080 0, /*tp_reserved*/
2081 0, /*tp_repr*/
2082 0, /*tp_as_number*/
2083 0, /*tp_as_sequence*/
2084 0, /*tp_as_mapping*/
2085 0, /*tp_hash*/
2086 0, /*tp_call*/
2087 0, /*tp_str*/
2088 0, /*tp_getattro*/
2089 0, /*tp_setattro*/
2090 0, /*tp_as_buffer*/
2091 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2092 0, /*tp_doc*/
2093 0, /*tp_traverse*/
2094 0, /*tp_clear*/
2095 0, /*tp_richcompare*/
2096 0, /*tp_weaklistoffset*/
2097 0, /*tp_iter*/
2098 0, /*tp_iternext*/
2099 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002100 0, /*tp_members*/
2101 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002102};
2103
Antoine Pitrou152efa22010-05-16 18:19:27 +00002104
2105/*
2106 * _SSLContext objects
2107 */
2108
2109static PyObject *
2110context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2111{
2112 char *kwlist[] = {"protocol", NULL};
2113 PySSLContext *self;
2114 int proto_version = PY_SSL_VERSION_SSL23;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002115 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002116 SSL_CTX *ctx = NULL;
2117
2118 if (!PyArg_ParseTupleAndKeywords(
2119 args, kwds, "i:_SSLContext", kwlist,
2120 &proto_version))
2121 return NULL;
2122
2123 PySSL_BEGIN_ALLOW_THREADS
2124 if (proto_version == PY_SSL_VERSION_TLS1)
2125 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002126#if HAVE_TLSv1_2
2127 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2128 ctx = SSL_CTX_new(TLSv1_1_method());
2129 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2130 ctx = SSL_CTX_new(TLSv1_2_method());
2131#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002132#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002133 else if (proto_version == PY_SSL_VERSION_SSL3)
2134 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002135#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002136#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002137 else if (proto_version == PY_SSL_VERSION_SSL2)
2138 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002139#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002140 else if (proto_version == PY_SSL_VERSION_SSL23)
2141 ctx = SSL_CTX_new(SSLv23_method());
2142 else
2143 proto_version = -1;
2144 PySSL_END_ALLOW_THREADS
2145
2146 if (proto_version == -1) {
2147 PyErr_SetString(PyExc_ValueError,
2148 "invalid protocol version");
2149 return NULL;
2150 }
2151 if (ctx == NULL) {
2152 PyErr_SetString(PySSLErrorObject,
2153 "failed to allocate SSL context");
2154 return NULL;
2155 }
2156
2157 assert(type != NULL && type->tp_alloc != NULL);
2158 self = (PySSLContext *) type->tp_alloc(type, 0);
2159 if (self == NULL) {
2160 SSL_CTX_free(ctx);
2161 return NULL;
2162 }
2163 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002164#ifdef OPENSSL_NPN_NEGOTIATED
2165 self->npn_protocols = NULL;
2166#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002167#ifdef HAVE_ALPN
2168 self->alpn_protocols = NULL;
2169#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002170#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002171 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002172#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002173 /* Don't check host name by default */
2174 self->check_hostname = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002175 /* Defaults */
2176 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002177 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2178 if (proto_version != PY_SSL_VERSION_SSL2)
2179 options |= SSL_OP_NO_SSLv2;
2180 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002181
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002182#ifndef OPENSSL_NO_ECDH
2183 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2184 prime256v1 by default. This is Apache mod_ssl's initialization
2185 policy, so we should be safe. */
2186#if defined(SSL_CTX_set_ecdh_auto)
2187 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2188#else
2189 {
2190 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2191 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2192 EC_KEY_free(key);
2193 }
2194#endif
2195#endif
2196
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002197#define SID_CTX "Python"
2198 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2199 sizeof(SID_CTX));
2200#undef SID_CTX
2201
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002202#ifdef X509_V_FLAG_TRUSTED_FIRST
2203 {
2204 /* Improve trust chain building when cross-signed intermediate
2205 certificates are present. See https://bugs.python.org/issue23476. */
2206 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2207 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2208 }
2209#endif
2210
Antoine Pitrou152efa22010-05-16 18:19:27 +00002211 return (PyObject *)self;
2212}
2213
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002214static int
2215context_traverse(PySSLContext *self, visitproc visit, void *arg)
2216{
2217#ifndef OPENSSL_NO_TLSEXT
2218 Py_VISIT(self->set_hostname);
2219#endif
2220 return 0;
2221}
2222
2223static int
2224context_clear(PySSLContext *self)
2225{
2226#ifndef OPENSSL_NO_TLSEXT
2227 Py_CLEAR(self->set_hostname);
2228#endif
2229 return 0;
2230}
2231
Antoine Pitrou152efa22010-05-16 18:19:27 +00002232static void
2233context_dealloc(PySSLContext *self)
2234{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002235 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002236 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002237#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002238 PyMem_FREE(self->npn_protocols);
2239#endif
2240#ifdef HAVE_ALPN
2241 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002242#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002243 Py_TYPE(self)->tp_free(self);
2244}
2245
2246static PyObject *
2247set_ciphers(PySSLContext *self, PyObject *args)
2248{
2249 int ret;
2250 const char *cipherlist;
2251
2252 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2253 return NULL;
2254 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2255 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002256 /* Clearing the error queue is necessary on some OpenSSL versions,
2257 otherwise the error will be reported again when another SSL call
2258 is done. */
2259 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002260 PyErr_SetString(PySSLErrorObject,
2261 "No cipher can be selected.");
2262 return NULL;
2263 }
2264 Py_RETURN_NONE;
2265}
2266
Benjamin Petersonc54de472015-01-28 12:06:39 -05002267#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002268static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002269do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2270 const unsigned char *server_protocols, unsigned int server_protocols_len,
2271 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002272{
Benjamin Peterson88615022015-01-23 17:30:26 -05002273 int ret;
2274 if (client_protocols == NULL) {
2275 client_protocols = (unsigned char *)"";
2276 client_protocols_len = 0;
2277 }
2278 if (server_protocols == NULL) {
2279 server_protocols = (unsigned char *)"";
2280 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002281 }
2282
Benjamin Peterson88615022015-01-23 17:30:26 -05002283 ret = SSL_select_next_proto(out, outlen,
2284 server_protocols, server_protocols_len,
2285 client_protocols, client_protocols_len);
2286 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2287 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002288
2289 return SSL_TLSEXT_ERR_OK;
2290}
2291
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002292/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2293static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002294_advertiseNPN_cb(SSL *s,
2295 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002296 void *args)
2297{
2298 PySSLContext *ssl_ctx = (PySSLContext *) args;
2299
2300 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002301 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002302 *len = 0;
2303 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002304 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002305 *len = ssl_ctx->npn_protocols_len;
2306 }
2307
2308 return SSL_TLSEXT_ERR_OK;
2309}
2310/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2311static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002312_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002313 unsigned char **out, unsigned char *outlen,
2314 const unsigned char *server, unsigned int server_len,
2315 void *args)
2316{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002317 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002318 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002319 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002320}
2321#endif
2322
2323static PyObject *
2324_set_npn_protocols(PySSLContext *self, PyObject *args)
2325{
2326#ifdef OPENSSL_NPN_NEGOTIATED
2327 Py_buffer protos;
2328
2329 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2330 return NULL;
2331
Christian Heimes5cb31c92012-09-20 12:42:54 +02002332 if (self->npn_protocols != NULL) {
2333 PyMem_Free(self->npn_protocols);
2334 }
2335
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002336 self->npn_protocols = PyMem_Malloc(protos.len);
2337 if (self->npn_protocols == NULL) {
2338 PyBuffer_Release(&protos);
2339 return PyErr_NoMemory();
2340 }
2341 memcpy(self->npn_protocols, protos.buf, protos.len);
2342 self->npn_protocols_len = (int) protos.len;
2343
2344 /* set both server and client callbacks, because the context can
2345 * be used to create both types of sockets */
2346 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2347 _advertiseNPN_cb,
2348 self);
2349 SSL_CTX_set_next_proto_select_cb(self->ctx,
2350 _selectNPN_cb,
2351 self);
2352
2353 PyBuffer_Release(&protos);
2354 Py_RETURN_NONE;
2355#else
2356 PyErr_SetString(PyExc_NotImplementedError,
2357 "The NPN extension requires OpenSSL 1.0.1 or later.");
2358 return NULL;
2359#endif
2360}
2361
Benjamin Petersoncca27322015-01-23 16:35:37 -05002362#ifdef HAVE_ALPN
2363static int
2364_selectALPN_cb(SSL *s,
2365 const unsigned char **out, unsigned char *outlen,
2366 const unsigned char *client_protocols, unsigned int client_protocols_len,
2367 void *args)
2368{
2369 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002370 return do_protocol_selection(1, (unsigned char **)out, outlen,
2371 ctx->alpn_protocols, ctx->alpn_protocols_len,
2372 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002373}
2374#endif
2375
2376static PyObject *
2377_set_alpn_protocols(PySSLContext *self, PyObject *args)
2378{
2379#ifdef HAVE_ALPN
2380 Py_buffer protos;
2381
2382 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2383 return NULL;
2384
2385 PyMem_FREE(self->alpn_protocols);
2386 self->alpn_protocols = PyMem_Malloc(protos.len);
2387 if (!self->alpn_protocols)
2388 return PyErr_NoMemory();
2389 memcpy(self->alpn_protocols, protos.buf, protos.len);
2390 self->alpn_protocols_len = protos.len;
2391 PyBuffer_Release(&protos);
2392
2393 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2394 return PyErr_NoMemory();
2395 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2396
2397 PyBuffer_Release(&protos);
2398 Py_RETURN_NONE;
2399#else
2400 PyErr_SetString(PyExc_NotImplementedError,
2401 "The ALPN extension requires OpenSSL 1.0.2 or later.");
2402 return NULL;
2403#endif
2404}
2405
Antoine Pitrou152efa22010-05-16 18:19:27 +00002406static PyObject *
2407get_verify_mode(PySSLContext *self, void *c)
2408{
2409 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2410 case SSL_VERIFY_NONE:
2411 return PyLong_FromLong(PY_SSL_CERT_NONE);
2412 case SSL_VERIFY_PEER:
2413 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2414 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2415 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2416 }
2417 PyErr_SetString(PySSLErrorObject,
2418 "invalid return value from SSL_CTX_get_verify_mode");
2419 return NULL;
2420}
2421
2422static int
2423set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2424{
2425 int n, mode;
2426 if (!PyArg_Parse(arg, "i", &n))
2427 return -1;
2428 if (n == PY_SSL_CERT_NONE)
2429 mode = SSL_VERIFY_NONE;
2430 else if (n == PY_SSL_CERT_OPTIONAL)
2431 mode = SSL_VERIFY_PEER;
2432 else if (n == PY_SSL_CERT_REQUIRED)
2433 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2434 else {
2435 PyErr_SetString(PyExc_ValueError,
2436 "invalid value for verify_mode");
2437 return -1;
2438 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01002439 if (mode == SSL_VERIFY_NONE && self->check_hostname) {
2440 PyErr_SetString(PyExc_ValueError,
2441 "Cannot set verify_mode to CERT_NONE when "
2442 "check_hostname is enabled.");
2443 return -1;
2444 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002445 SSL_CTX_set_verify(self->ctx, mode, NULL);
2446 return 0;
2447}
2448
2449static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01002450get_verify_flags(PySSLContext *self, void *c)
2451{
2452 X509_STORE *store;
2453 unsigned long flags;
2454
2455 store = SSL_CTX_get_cert_store(self->ctx);
2456 flags = X509_VERIFY_PARAM_get_flags(store->param);
2457 return PyLong_FromUnsignedLong(flags);
2458}
2459
2460static int
2461set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
2462{
2463 X509_STORE *store;
2464 unsigned long new_flags, flags, set, clear;
2465
2466 if (!PyArg_Parse(arg, "k", &new_flags))
2467 return -1;
2468 store = SSL_CTX_get_cert_store(self->ctx);
2469 flags = X509_VERIFY_PARAM_get_flags(store->param);
2470 clear = flags & ~new_flags;
2471 set = ~flags & new_flags;
2472 if (clear) {
2473 if (!X509_VERIFY_PARAM_clear_flags(store->param, clear)) {
2474 _setSSLError(NULL, 0, __FILE__, __LINE__);
2475 return -1;
2476 }
2477 }
2478 if (set) {
2479 if (!X509_VERIFY_PARAM_set_flags(store->param, set)) {
2480 _setSSLError(NULL, 0, __FILE__, __LINE__);
2481 return -1;
2482 }
2483 }
2484 return 0;
2485}
2486
2487static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002488get_options(PySSLContext *self, void *c)
2489{
2490 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2491}
2492
2493static int
2494set_options(PySSLContext *self, PyObject *arg, void *c)
2495{
2496 long new_opts, opts, set, clear;
2497 if (!PyArg_Parse(arg, "l", &new_opts))
2498 return -1;
2499 opts = SSL_CTX_get_options(self->ctx);
2500 clear = opts & ~new_opts;
2501 set = ~opts & new_opts;
2502 if (clear) {
2503#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2504 SSL_CTX_clear_options(self->ctx, clear);
2505#else
2506 PyErr_SetString(PyExc_ValueError,
2507 "can't clear options before OpenSSL 0.9.8m");
2508 return -1;
2509#endif
2510 }
2511 if (set)
2512 SSL_CTX_set_options(self->ctx, set);
2513 return 0;
2514}
2515
Christian Heimes1aa9a752013-12-02 02:41:19 +01002516static PyObject *
2517get_check_hostname(PySSLContext *self, void *c)
2518{
2519 return PyBool_FromLong(self->check_hostname);
2520}
2521
2522static int
2523set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
2524{
2525 int check_hostname;
2526 if (!PyArg_Parse(arg, "p", &check_hostname))
2527 return -1;
2528 if (check_hostname &&
2529 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
2530 PyErr_SetString(PyExc_ValueError,
2531 "check_hostname needs a SSL context with either "
2532 "CERT_OPTIONAL or CERT_REQUIRED");
2533 return -1;
2534 }
2535 self->check_hostname = check_hostname;
2536 return 0;
2537}
2538
2539
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002540typedef struct {
2541 PyThreadState *thread_state;
2542 PyObject *callable;
2543 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002544 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002545 int error;
2546} _PySSLPasswordInfo;
2547
2548static int
2549_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2550 const char *bad_type_error)
2551{
2552 /* Set the password and size fields of a _PySSLPasswordInfo struct
2553 from a unicode, bytes, or byte array object.
2554 The password field will be dynamically allocated and must be freed
2555 by the caller */
2556 PyObject *password_bytes = NULL;
2557 const char *data = NULL;
2558 Py_ssize_t size;
2559
2560 if (PyUnicode_Check(password)) {
2561 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2562 if (!password_bytes) {
2563 goto error;
2564 }
2565 data = PyBytes_AS_STRING(password_bytes);
2566 size = PyBytes_GET_SIZE(password_bytes);
2567 } else if (PyBytes_Check(password)) {
2568 data = PyBytes_AS_STRING(password);
2569 size = PyBytes_GET_SIZE(password);
2570 } else if (PyByteArray_Check(password)) {
2571 data = PyByteArray_AS_STRING(password);
2572 size = PyByteArray_GET_SIZE(password);
2573 } else {
2574 PyErr_SetString(PyExc_TypeError, bad_type_error);
2575 goto error;
2576 }
2577
Victor Stinner9ee02032013-06-23 15:08:23 +02002578 if (size > (Py_ssize_t)INT_MAX) {
2579 PyErr_Format(PyExc_ValueError,
2580 "password cannot be longer than %d bytes", INT_MAX);
2581 goto error;
2582 }
2583
Victor Stinner11ebff22013-07-07 17:07:52 +02002584 PyMem_Free(pw_info->password);
2585 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002586 if (!pw_info->password) {
2587 PyErr_SetString(PyExc_MemoryError,
2588 "unable to allocate password buffer");
2589 goto error;
2590 }
2591 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002592 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002593
2594 Py_XDECREF(password_bytes);
2595 return 1;
2596
2597error:
2598 Py_XDECREF(password_bytes);
2599 return 0;
2600}
2601
2602static int
2603_password_callback(char *buf, int size, int rwflag, void *userdata)
2604{
2605 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2606 PyObject *fn_ret = NULL;
2607
2608 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2609
2610 if (pw_info->callable) {
2611 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2612 if (!fn_ret) {
2613 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2614 core python API, so we could use it to add a frame here */
2615 goto error;
2616 }
2617
2618 if (!_pwinfo_set(pw_info, fn_ret,
2619 "password callback must return a string")) {
2620 goto error;
2621 }
2622 Py_CLEAR(fn_ret);
2623 }
2624
2625 if (pw_info->size > size) {
2626 PyErr_Format(PyExc_ValueError,
2627 "password cannot be longer than %d bytes", size);
2628 goto error;
2629 }
2630
2631 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2632 memcpy(buf, pw_info->password, pw_info->size);
2633 return pw_info->size;
2634
2635error:
2636 Py_XDECREF(fn_ret);
2637 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2638 pw_info->error = 1;
2639 return -1;
2640}
2641
Antoine Pitroub5218772010-05-21 09:56:06 +00002642static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002643load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2644{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002645 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2646 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002647 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002648 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2649 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2650 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002651 int r;
2652
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002653 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002654 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002655 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002656 "O|OO:load_cert_chain", kwlist,
2657 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002658 return NULL;
2659 if (keyfile == Py_None)
2660 keyfile = NULL;
2661 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2662 PyErr_SetString(PyExc_TypeError,
2663 "certfile should be a valid filesystem path");
2664 return NULL;
2665 }
2666 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2667 PyErr_SetString(PyExc_TypeError,
2668 "keyfile should be a valid filesystem path");
2669 goto error;
2670 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002671 if (password && password != Py_None) {
2672 if (PyCallable_Check(password)) {
2673 pw_info.callable = password;
2674 } else if (!_pwinfo_set(&pw_info, password,
2675 "password should be a string or callable")) {
2676 goto error;
2677 }
2678 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2679 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2680 }
2681 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002682 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2683 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002684 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002685 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002686 if (pw_info.error) {
2687 ERR_clear_error();
2688 /* the password callback has already set the error information */
2689 }
2690 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002691 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002692 PyErr_SetFromErrno(PyExc_IOError);
2693 }
2694 else {
2695 _setSSLError(NULL, 0, __FILE__, __LINE__);
2696 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002697 goto error;
2698 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002699 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002700 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002701 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2702 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002703 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2704 Py_CLEAR(keyfile_bytes);
2705 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002706 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002707 if (pw_info.error) {
2708 ERR_clear_error();
2709 /* the password callback has already set the error information */
2710 }
2711 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002712 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002713 PyErr_SetFromErrno(PyExc_IOError);
2714 }
2715 else {
2716 _setSSLError(NULL, 0, __FILE__, __LINE__);
2717 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002718 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002719 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002720 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002721 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002722 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002723 if (r != 1) {
2724 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002725 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002726 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002727 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2728 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002729 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002730 Py_RETURN_NONE;
2731
2732error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002733 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2734 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002735 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002736 Py_XDECREF(keyfile_bytes);
2737 Py_XDECREF(certfile_bytes);
2738 return NULL;
2739}
2740
Christian Heimesefff7062013-11-21 03:35:02 +01002741/* internal helper function, returns -1 on error
2742 */
2743static int
2744_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2745 int filetype)
2746{
2747 BIO *biobuf = NULL;
2748 X509_STORE *store;
2749 int retval = 0, err, loaded = 0;
2750
2751 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2752
2753 if (len <= 0) {
2754 PyErr_SetString(PyExc_ValueError,
2755 "Empty certificate data");
2756 return -1;
2757 } else if (len > INT_MAX) {
2758 PyErr_SetString(PyExc_OverflowError,
2759 "Certificate data is too long.");
2760 return -1;
2761 }
2762
Christian Heimes1dbf61f2013-11-22 00:34:18 +01002763 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01002764 if (biobuf == NULL) {
2765 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2766 return -1;
2767 }
2768
2769 store = SSL_CTX_get_cert_store(self->ctx);
2770 assert(store != NULL);
2771
2772 while (1) {
2773 X509 *cert = NULL;
2774 int r;
2775
2776 if (filetype == SSL_FILETYPE_ASN1) {
2777 cert = d2i_X509_bio(biobuf, NULL);
2778 } else {
2779 cert = PEM_read_bio_X509(biobuf, NULL,
2780 self->ctx->default_passwd_callback,
2781 self->ctx->default_passwd_callback_userdata);
2782 }
2783 if (cert == NULL) {
2784 break;
2785 }
2786 r = X509_STORE_add_cert(store, cert);
2787 X509_free(cert);
2788 if (!r) {
2789 err = ERR_peek_last_error();
2790 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2791 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2792 /* cert already in hash table, not an error */
2793 ERR_clear_error();
2794 } else {
2795 break;
2796 }
2797 }
2798 loaded++;
2799 }
2800
2801 err = ERR_peek_last_error();
2802 if ((filetype == SSL_FILETYPE_ASN1) &&
2803 (loaded > 0) &&
2804 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2805 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2806 /* EOF ASN1 file, not an error */
2807 ERR_clear_error();
2808 retval = 0;
2809 } else if ((filetype == SSL_FILETYPE_PEM) &&
2810 (loaded > 0) &&
2811 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2812 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2813 /* EOF PEM file, not an error */
2814 ERR_clear_error();
2815 retval = 0;
2816 } else {
2817 _setSSLError(NULL, 0, __FILE__, __LINE__);
2818 retval = -1;
2819 }
2820
2821 BIO_free(biobuf);
2822 return retval;
2823}
2824
2825
Antoine Pitrou152efa22010-05-16 18:19:27 +00002826static PyObject *
2827load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2828{
Christian Heimesefff7062013-11-21 03:35:02 +01002829 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2830 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002831 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2832 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002833 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002834
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002835 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002836 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002837 "|OOO:load_verify_locations", kwlist,
2838 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002839 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002840
Antoine Pitrou152efa22010-05-16 18:19:27 +00002841 if (cafile == Py_None)
2842 cafile = NULL;
2843 if (capath == Py_None)
2844 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002845 if (cadata == Py_None)
2846 cadata = NULL;
2847
2848 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002849 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002850 "cafile, capath and cadata cannot be all omitted");
2851 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002852 }
2853 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2854 PyErr_SetString(PyExc_TypeError,
2855 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002856 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002857 }
2858 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002859 PyErr_SetString(PyExc_TypeError,
2860 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002861 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002862 }
Christian Heimesefff7062013-11-21 03:35:02 +01002863
2864 /* validata cadata type and load cadata */
2865 if (cadata) {
2866 Py_buffer buf;
2867 PyObject *cadata_ascii = NULL;
2868
2869 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2870 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2871 PyBuffer_Release(&buf);
2872 PyErr_SetString(PyExc_TypeError,
2873 "cadata should be a contiguous buffer with "
2874 "a single dimension");
2875 goto error;
2876 }
2877 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2878 PyBuffer_Release(&buf);
2879 if (r == -1) {
2880 goto error;
2881 }
2882 } else {
2883 PyErr_Clear();
2884 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2885 if (cadata_ascii == NULL) {
2886 PyErr_SetString(PyExc_TypeError,
2887 "cadata should be a ASCII string or a "
2888 "bytes-like object");
2889 goto error;
2890 }
2891 r = _add_ca_certs(self,
2892 PyBytes_AS_STRING(cadata_ascii),
2893 PyBytes_GET_SIZE(cadata_ascii),
2894 SSL_FILETYPE_PEM);
2895 Py_DECREF(cadata_ascii);
2896 if (r == -1) {
2897 goto error;
2898 }
2899 }
2900 }
2901
2902 /* load cafile or capath */
2903 if (cafile || capath) {
2904 if (cafile)
2905 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2906 if (capath)
2907 capath_buf = PyBytes_AS_STRING(capath_bytes);
2908 PySSL_BEGIN_ALLOW_THREADS
2909 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2910 PySSL_END_ALLOW_THREADS
2911 if (r != 1) {
2912 ok = 0;
2913 if (errno != 0) {
2914 ERR_clear_error();
2915 PyErr_SetFromErrno(PyExc_IOError);
2916 }
2917 else {
2918 _setSSLError(NULL, 0, __FILE__, __LINE__);
2919 }
2920 goto error;
2921 }
2922 }
2923 goto end;
2924
2925 error:
2926 ok = 0;
2927 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002928 Py_XDECREF(cafile_bytes);
2929 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002930 if (ok) {
2931 Py_RETURN_NONE;
2932 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002933 return NULL;
2934 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002935}
2936
2937static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002938load_dh_params(PySSLContext *self, PyObject *filepath)
2939{
2940 FILE *f;
2941 DH *dh;
2942
Victor Stinnerdaf45552013-08-28 00:53:59 +02002943 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01002944 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002945 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01002946
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002947 errno = 0;
2948 PySSL_BEGIN_ALLOW_THREADS
2949 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002950 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002951 PySSL_END_ALLOW_THREADS
2952 if (dh == NULL) {
2953 if (errno != 0) {
2954 ERR_clear_error();
2955 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2956 }
2957 else {
2958 _setSSLError(NULL, 0, __FILE__, __LINE__);
2959 }
2960 return NULL;
2961 }
2962 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2963 _setSSLError(NULL, 0, __FILE__, __LINE__);
2964 DH_free(dh);
2965 Py_RETURN_NONE;
2966}
2967
2968static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002969context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2970{
Antoine Pitroud5323212010-10-22 18:19:07 +00002971 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002972 PySocketSockObject *sock;
2973 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002974 char *hostname = NULL;
2975 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002976
Antoine Pitroud5323212010-10-22 18:19:07 +00002977 /* server_hostname is either None (or absent), or to be encoded
2978 using the idna encoding. */
2979 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002980 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002981 &sock, &server_side,
2982 Py_TYPE(Py_None), &hostname_obj)) {
2983 PyErr_Clear();
2984 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2985 PySocketModule.Sock_Type,
2986 &sock, &server_side,
2987 "idna", &hostname))
2988 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002989 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002990
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002991 res = (PyObject *) newPySSLSocket(self, sock, server_side, hostname,
2992 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00002993 if (hostname != NULL)
2994 PyMem_Free(hostname);
2995 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002996}
2997
Antoine Pitroub0182c82010-10-12 20:09:02 +00002998static PyObject *
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002999context_wrap_bio(PySSLContext *self, PyObject *args, PyObject *kwds)
3000{
3001 char *kwlist[] = {"incoming", "outgoing", "server_side",
3002 "server_hostname", NULL};
3003 int server_side;
3004 char *hostname = NULL;
3005 PyObject *hostname_obj = Py_None, *res;
3006 PySSLMemoryBIO *incoming, *outgoing;
3007
3008 /* server_hostname is either None (or absent), or to be encoded
3009 using the idna encoding. */
3010 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!O!i|O:_wrap_bio", kwlist,
3011 &PySSLMemoryBIO_Type, &incoming,
3012 &PySSLMemoryBIO_Type, &outgoing,
3013 &server_side, &hostname_obj))
3014 return NULL;
3015 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003016 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3017 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003018 }
3019
3020 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3021 incoming, outgoing);
3022
3023 PyMem_Free(hostname);
3024 return res;
3025}
3026
3027static PyObject *
Antoine Pitroub0182c82010-10-12 20:09:02 +00003028session_stats(PySSLContext *self, PyObject *unused)
3029{
3030 int r;
3031 PyObject *value, *stats = PyDict_New();
3032 if (!stats)
3033 return NULL;
3034
3035#define ADD_STATS(SSL_NAME, KEY_NAME) \
3036 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3037 if (value == NULL) \
3038 goto error; \
3039 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3040 Py_DECREF(value); \
3041 if (r < 0) \
3042 goto error;
3043
3044 ADD_STATS(number, "number");
3045 ADD_STATS(connect, "connect");
3046 ADD_STATS(connect_good, "connect_good");
3047 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3048 ADD_STATS(accept, "accept");
3049 ADD_STATS(accept_good, "accept_good");
3050 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3051 ADD_STATS(accept, "accept");
3052 ADD_STATS(hits, "hits");
3053 ADD_STATS(misses, "misses");
3054 ADD_STATS(timeouts, "timeouts");
3055 ADD_STATS(cache_full, "cache_full");
3056
3057#undef ADD_STATS
3058
3059 return stats;
3060
3061error:
3062 Py_DECREF(stats);
3063 return NULL;
3064}
3065
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003066static PyObject *
3067set_default_verify_paths(PySSLContext *self, PyObject *unused)
3068{
3069 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3070 _setSSLError(NULL, 0, __FILE__, __LINE__);
3071 return NULL;
3072 }
3073 Py_RETURN_NONE;
3074}
3075
Antoine Pitrou501da612011-12-21 09:27:41 +01003076#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003077static PyObject *
3078set_ecdh_curve(PySSLContext *self, PyObject *name)
3079{
3080 PyObject *name_bytes;
3081 int nid;
3082 EC_KEY *key;
3083
3084 if (!PyUnicode_FSConverter(name, &name_bytes))
3085 return NULL;
3086 assert(PyBytes_Check(name_bytes));
3087 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3088 Py_DECREF(name_bytes);
3089 if (nid == 0) {
3090 PyErr_Format(PyExc_ValueError,
3091 "unknown elliptic curve name %R", name);
3092 return NULL;
3093 }
3094 key = EC_KEY_new_by_curve_name(nid);
3095 if (key == NULL) {
3096 _setSSLError(NULL, 0, __FILE__, __LINE__);
3097 return NULL;
3098 }
3099 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3100 EC_KEY_free(key);
3101 Py_RETURN_NONE;
3102}
Antoine Pitrou501da612011-12-21 09:27:41 +01003103#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003104
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003105#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003106static int
3107_servername_callback(SSL *s, int *al, void *args)
3108{
3109 int ret;
3110 PySSLContext *ssl_ctx = (PySSLContext *) args;
3111 PySSLSocket *ssl;
3112 PyObject *servername_o;
3113 PyObject *servername_idna;
3114 PyObject *result;
3115 /* The high-level ssl.SSLSocket object */
3116 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003117 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003118#ifdef WITH_THREAD
3119 PyGILState_STATE gstate = PyGILState_Ensure();
3120#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003121
3122 if (ssl_ctx->set_hostname == NULL) {
3123 /* remove race condition in this the call back while if removing the
3124 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003125#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003126 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003127#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003128 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003129 }
3130
3131 ssl = SSL_get_app_data(s);
3132 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003133
3134 /* The servername callback expects a argument that represents the current
3135 * SSL connection and that has a .context attribute that can be changed to
3136 * identify the requested hostname. Since the official API is the Python
3137 * level API we want to pass the callback a Python level object rather than
3138 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3139 * SSLObject) that will be passed. Otherwise if there's a socket then that
3140 * will be passed. If both do not exist only then the C-level object is
3141 * passed. */
3142 if (ssl->owner)
3143 ssl_socket = PyWeakref_GetObject(ssl->owner);
3144 else if (ssl->Socket)
3145 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3146 else
3147 ssl_socket = (PyObject *) ssl;
3148
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003149 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003150 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003151 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003152
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003153 if (servername == NULL) {
3154 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3155 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003156 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003157 else {
3158 servername_o = PyBytes_FromString(servername);
3159 if (servername_o == NULL) {
3160 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3161 goto error;
3162 }
3163 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3164 if (servername_idna == NULL) {
3165 PyErr_WriteUnraisable(servername_o);
3166 Py_DECREF(servername_o);
3167 goto error;
3168 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003169 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003170 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3171 servername_idna, ssl_ctx, NULL);
3172 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003173 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003174 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003175
3176 if (result == NULL) {
3177 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3178 *al = SSL_AD_HANDSHAKE_FAILURE;
3179 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3180 }
3181 else {
3182 if (result != Py_None) {
3183 *al = (int) PyLong_AsLong(result);
3184 if (PyErr_Occurred()) {
3185 PyErr_WriteUnraisable(result);
3186 *al = SSL_AD_INTERNAL_ERROR;
3187 }
3188 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3189 }
3190 else {
3191 ret = SSL_TLSEXT_ERR_OK;
3192 }
3193 Py_DECREF(result);
3194 }
3195
Stefan Krah20d60802013-01-17 17:07:17 +01003196#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003197 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003198#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003199 return ret;
3200
3201error:
3202 Py_DECREF(ssl_socket);
3203 *al = SSL_AD_INTERNAL_ERROR;
3204 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003205#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003206 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003207#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003208 return ret;
3209}
Antoine Pitroua5963382013-03-30 16:39:00 +01003210#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003211
3212PyDoc_STRVAR(PySSL_set_servername_callback_doc,
3213"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003214\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003215This sets a callback that will be called when a server name is provided by\n\
3216the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003217\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003218If the argument is None then the callback is disabled. The method is called\n\
3219with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01003220See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003221
3222static PyObject *
3223set_servername_callback(PySSLContext *self, PyObject *args)
3224{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003225#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003226 PyObject *cb;
3227
3228 if (!PyArg_ParseTuple(args, "O", &cb))
3229 return NULL;
3230
3231 Py_CLEAR(self->set_hostname);
3232 if (cb == Py_None) {
3233 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3234 }
3235 else {
3236 if (!PyCallable_Check(cb)) {
3237 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3238 PyErr_SetString(PyExc_TypeError,
3239 "not a callable object");
3240 return NULL;
3241 }
3242 Py_INCREF(cb);
3243 self->set_hostname = cb;
3244 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3245 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3246 }
3247 Py_RETURN_NONE;
3248#else
3249 PyErr_SetString(PyExc_NotImplementedError,
3250 "The TLS extension servername callback, "
3251 "SSL_CTX_set_tlsext_servername_callback, "
3252 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003253 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003254#endif
3255}
3256
Christian Heimes9a5395a2013-06-17 15:44:12 +02003257PyDoc_STRVAR(PySSL_get_stats_doc,
3258"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
3259\n\
3260Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
3261CA extension and certificate revocation lists inside the context's cert\n\
3262store.\n\
3263NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3264been used at least once.");
3265
3266static PyObject *
3267cert_store_stats(PySSLContext *self)
3268{
3269 X509_STORE *store;
3270 X509_OBJECT *obj;
3271 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
3272
3273 store = SSL_CTX_get_cert_store(self->ctx);
3274 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3275 obj = sk_X509_OBJECT_value(store->objs, i);
3276 switch (obj->type) {
3277 case X509_LU_X509:
3278 x509++;
3279 if (X509_check_ca(obj->data.x509)) {
3280 ca++;
3281 }
3282 break;
3283 case X509_LU_CRL:
3284 crl++;
3285 break;
3286 case X509_LU_PKEY:
3287 pkey++;
3288 break;
3289 default:
3290 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3291 * As far as I can tell they are internal states and never
3292 * stored in a cert store */
3293 break;
3294 }
3295 }
3296 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3297 "x509_ca", ca);
3298}
3299
3300PyDoc_STRVAR(PySSL_get_ca_certs_doc,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003301"get_ca_certs(binary_form=False) -> list of loaded certificate\n\
Christian Heimes9a5395a2013-06-17 15:44:12 +02003302\n\
3303Returns a list of dicts with information of loaded CA certs. If the\n\
3304optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
3305NOTE: Certificates in a capath directory aren't loaded unless they have\n\
3306been used at least once.");
3307
3308static PyObject *
Christian Heimesf22e8e52013-11-22 02:22:51 +01003309get_ca_certs(PySSLContext *self, PyObject *args, PyObject *kwds)
Christian Heimes9a5395a2013-06-17 15:44:12 +02003310{
Christian Heimesf22e8e52013-11-22 02:22:51 +01003311 char *kwlist[] = {"binary_form", NULL};
Christian Heimes9a5395a2013-06-17 15:44:12 +02003312 X509_STORE *store;
3313 PyObject *ci = NULL, *rlist = NULL;
3314 int i;
3315 int binary_mode = 0;
3316
Christian Heimesf22e8e52013-11-22 02:22:51 +01003317 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|p:get_ca_certs",
3318 kwlist, &binary_mode)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003319 return NULL;
3320 }
3321
3322 if ((rlist = PyList_New(0)) == NULL) {
3323 return NULL;
3324 }
3325
3326 store = SSL_CTX_get_cert_store(self->ctx);
3327 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3328 X509_OBJECT *obj;
3329 X509 *cert;
3330
3331 obj = sk_X509_OBJECT_value(store->objs, i);
3332 if (obj->type != X509_LU_X509) {
3333 /* not a x509 cert */
3334 continue;
3335 }
3336 /* CA for any purpose */
3337 cert = obj->data.x509;
3338 if (!X509_check_ca(cert)) {
3339 continue;
3340 }
3341 if (binary_mode) {
3342 ci = _certificate_to_der(cert);
3343 } else {
3344 ci = _decode_certificate(cert);
3345 }
3346 if (ci == NULL) {
3347 goto error;
3348 }
3349 if (PyList_Append(rlist, ci) == -1) {
3350 goto error;
3351 }
3352 Py_CLEAR(ci);
3353 }
3354 return rlist;
3355
3356 error:
3357 Py_XDECREF(ci);
3358 Py_XDECREF(rlist);
3359 return NULL;
3360}
3361
3362
Antoine Pitrou152efa22010-05-16 18:19:27 +00003363static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003364 {"check_hostname", (getter) get_check_hostname,
3365 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003366 {"options", (getter) get_options,
3367 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003368 {"verify_flags", (getter) get_verify_flags,
3369 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003370 {"verify_mode", (getter) get_verify_mode,
3371 (setter) set_verify_mode, NULL},
3372 {NULL}, /* sentinel */
3373};
3374
3375static struct PyMethodDef context_methods[] = {
3376 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3377 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003378 {"_wrap_bio", (PyCFunction) context_wrap_bio,
3379 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003380 {"set_ciphers", (PyCFunction) set_ciphers,
3381 METH_VARARGS, NULL},
Benjamin Petersoncca27322015-01-23 16:35:37 -05003382 {"_set_alpn_protocols", (PyCFunction) _set_alpn_protocols,
3383 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003384 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3385 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003386 {"load_cert_chain", (PyCFunction) load_cert_chain,
3387 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003388 {"load_dh_params", (PyCFunction) load_dh_params,
3389 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003390 {"load_verify_locations", (PyCFunction) load_verify_locations,
3391 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00003392 {"session_stats", (PyCFunction) session_stats,
3393 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003394 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3395 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003396#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003397 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3398 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003399#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003400 {"set_servername_callback", (PyCFunction) set_servername_callback,
3401 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02003402 {"cert_store_stats", (PyCFunction) cert_store_stats,
3403 METH_NOARGS, PySSL_get_stats_doc},
3404 {"get_ca_certs", (PyCFunction) get_ca_certs,
Christian Heimesf22e8e52013-11-22 02:22:51 +01003405 METH_VARARGS | METH_KEYWORDS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003406 {NULL, NULL} /* sentinel */
3407};
3408
3409static PyTypeObject PySSLContext_Type = {
3410 PyVarObject_HEAD_INIT(NULL, 0)
3411 "_ssl._SSLContext", /*tp_name*/
3412 sizeof(PySSLContext), /*tp_basicsize*/
3413 0, /*tp_itemsize*/
3414 (destructor)context_dealloc, /*tp_dealloc*/
3415 0, /*tp_print*/
3416 0, /*tp_getattr*/
3417 0, /*tp_setattr*/
3418 0, /*tp_reserved*/
3419 0, /*tp_repr*/
3420 0, /*tp_as_number*/
3421 0, /*tp_as_sequence*/
3422 0, /*tp_as_mapping*/
3423 0, /*tp_hash*/
3424 0, /*tp_call*/
3425 0, /*tp_str*/
3426 0, /*tp_getattro*/
3427 0, /*tp_setattro*/
3428 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003429 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003430 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003431 (traverseproc) context_traverse, /*tp_traverse*/
3432 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003433 0, /*tp_richcompare*/
3434 0, /*tp_weaklistoffset*/
3435 0, /*tp_iter*/
3436 0, /*tp_iternext*/
3437 context_methods, /*tp_methods*/
3438 0, /*tp_members*/
3439 context_getsetlist, /*tp_getset*/
3440 0, /*tp_base*/
3441 0, /*tp_dict*/
3442 0, /*tp_descr_get*/
3443 0, /*tp_descr_set*/
3444 0, /*tp_dictoffset*/
3445 0, /*tp_init*/
3446 0, /*tp_alloc*/
3447 context_new, /*tp_new*/
3448};
3449
3450
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003451/*
3452 * MemoryBIO objects
3453 */
3454
3455static PyObject *
3456memory_bio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
3457{
3458 char *kwlist[] = {NULL};
3459 BIO *bio;
3460 PySSLMemoryBIO *self;
3461
3462 if (!PyArg_ParseTupleAndKeywords(args, kwds, ":MemoryBIO", kwlist))
3463 return NULL;
3464
3465 bio = BIO_new(BIO_s_mem());
3466 if (bio == NULL) {
3467 PyErr_SetString(PySSLErrorObject,
3468 "failed to allocate BIO");
3469 return NULL;
3470 }
3471 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
3472 * just that no data is currently available. The SSL routines should retry
3473 * the read, which we can achieve by calling BIO_set_retry_read(). */
3474 BIO_set_retry_read(bio);
3475 BIO_set_mem_eof_return(bio, -1);
3476
3477 assert(type != NULL && type->tp_alloc != NULL);
3478 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
3479 if (self == NULL) {
3480 BIO_free(bio);
3481 return NULL;
3482 }
3483 self->bio = bio;
3484 self->eof_written = 0;
3485
3486 return (PyObject *) self;
3487}
3488
3489static void
3490memory_bio_dealloc(PySSLMemoryBIO *self)
3491{
3492 BIO_free(self->bio);
3493 Py_TYPE(self)->tp_free(self);
3494}
3495
3496static PyObject *
3497memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
3498{
3499 return PyLong_FromLong(BIO_ctrl_pending(self->bio));
3500}
3501
3502PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
3503"The number of bytes pending in the memory BIO.");
3504
3505static PyObject *
3506memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
3507{
3508 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
3509 && self->eof_written);
3510}
3511
3512PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
3513"Whether the memory BIO is at EOF.");
3514
3515static PyObject *
3516memory_bio_read(PySSLMemoryBIO *self, PyObject *args)
3517{
3518 int len = -1, avail, nbytes;
3519 PyObject *result;
3520
3521 if (!PyArg_ParseTuple(args, "|i:read", &len))
3522 return NULL;
3523
3524 avail = BIO_ctrl_pending(self->bio);
3525 if ((len < 0) || (len > avail))
3526 len = avail;
3527
3528 result = PyBytes_FromStringAndSize(NULL, len);
3529 if ((result == NULL) || (len == 0))
3530 return result;
3531
3532 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
3533 /* There should never be any short reads but check anyway. */
3534 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
3535 Py_DECREF(result);
3536 return NULL;
3537 }
3538
3539 return result;
3540}
3541
3542PyDoc_STRVAR(PySSL_memory_bio_read_doc,
3543"read([len]) -> bytes\n\
3544\n\
3545Read up to len bytes from the memory BIO.\n\
3546\n\
3547If len is not specified, read the entire buffer.\n\
3548If the return value is an empty bytes instance, this means either\n\
3549EOF or that no data is available. Use the \"eof\" property to\n\
3550distinguish between the two.");
3551
3552static PyObject *
3553memory_bio_write(PySSLMemoryBIO *self, PyObject *args)
3554{
3555 Py_buffer buf;
3556 int nbytes;
3557
3558 if (!PyArg_ParseTuple(args, "y*:write", &buf))
3559 return NULL;
3560
3561 if (buf.len > INT_MAX) {
3562 PyErr_Format(PyExc_OverflowError,
3563 "string longer than %d bytes", INT_MAX);
3564 goto error;
3565 }
3566
3567 if (self->eof_written) {
3568 PyErr_SetString(PySSLErrorObject,
3569 "cannot write() after write_eof()");
3570 goto error;
3571 }
3572
3573 nbytes = BIO_write(self->bio, buf.buf, buf.len);
3574 if (nbytes < 0) {
3575 _setSSLError(NULL, 0, __FILE__, __LINE__);
3576 goto error;
3577 }
3578
3579 PyBuffer_Release(&buf);
3580 return PyLong_FromLong(nbytes);
3581
3582error:
3583 PyBuffer_Release(&buf);
3584 return NULL;
3585}
3586
3587PyDoc_STRVAR(PySSL_memory_bio_write_doc,
3588"write(b) -> len\n\
3589\n\
3590Writes the bytes b into the memory BIO. Returns the number\n\
3591of bytes written.");
3592
3593static PyObject *
3594memory_bio_write_eof(PySSLMemoryBIO *self, PyObject *args)
3595{
3596 self->eof_written = 1;
3597 /* After an EOF is written, a zero return from read() should be a real EOF
3598 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
3599 BIO_clear_retry_flags(self->bio);
3600 BIO_set_mem_eof_return(self->bio, 0);
3601
3602 Py_RETURN_NONE;
3603}
3604
3605PyDoc_STRVAR(PySSL_memory_bio_write_eof_doc,
3606"write_eof()\n\
3607\n\
3608Write an EOF marker to the memory BIO.\n\
3609When all data has been read, the \"eof\" property will be True.");
3610
3611static PyGetSetDef memory_bio_getsetlist[] = {
3612 {"pending", (getter) memory_bio_get_pending, NULL,
3613 PySSL_memory_bio_pending_doc},
3614 {"eof", (getter) memory_bio_get_eof, NULL,
3615 PySSL_memory_bio_eof_doc},
3616 {NULL}, /* sentinel */
3617};
3618
3619static struct PyMethodDef memory_bio_methods[] = {
3620 {"read", (PyCFunction) memory_bio_read,
3621 METH_VARARGS, PySSL_memory_bio_read_doc},
3622 {"write", (PyCFunction) memory_bio_write,
3623 METH_VARARGS, PySSL_memory_bio_write_doc},
3624 {"write_eof", (PyCFunction) memory_bio_write_eof,
3625 METH_NOARGS, PySSL_memory_bio_write_eof_doc},
3626 {NULL, NULL} /* sentinel */
3627};
3628
3629static PyTypeObject PySSLMemoryBIO_Type = {
3630 PyVarObject_HEAD_INIT(NULL, 0)
3631 "_ssl.MemoryBIO", /*tp_name*/
3632 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
3633 0, /*tp_itemsize*/
3634 (destructor)memory_bio_dealloc, /*tp_dealloc*/
3635 0, /*tp_print*/
3636 0, /*tp_getattr*/
3637 0, /*tp_setattr*/
3638 0, /*tp_reserved*/
3639 0, /*tp_repr*/
3640 0, /*tp_as_number*/
3641 0, /*tp_as_sequence*/
3642 0, /*tp_as_mapping*/
3643 0, /*tp_hash*/
3644 0, /*tp_call*/
3645 0, /*tp_str*/
3646 0, /*tp_getattro*/
3647 0, /*tp_setattro*/
3648 0, /*tp_as_buffer*/
3649 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3650 0, /*tp_doc*/
3651 0, /*tp_traverse*/
3652 0, /*tp_clear*/
3653 0, /*tp_richcompare*/
3654 0, /*tp_weaklistoffset*/
3655 0, /*tp_iter*/
3656 0, /*tp_iternext*/
3657 memory_bio_methods, /*tp_methods*/
3658 0, /*tp_members*/
3659 memory_bio_getsetlist, /*tp_getset*/
3660 0, /*tp_base*/
3661 0, /*tp_dict*/
3662 0, /*tp_descr_get*/
3663 0, /*tp_descr_set*/
3664 0, /*tp_dictoffset*/
3665 0, /*tp_init*/
3666 0, /*tp_alloc*/
3667 memory_bio_new, /*tp_new*/
3668};
3669
Antoine Pitrou152efa22010-05-16 18:19:27 +00003670
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003671/* helper routines for seeding the SSL PRNG */
3672static PyObject *
3673PySSL_RAND_add(PyObject *self, PyObject *args)
3674{
3675 char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003676 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003677 double entropy;
3678
3679 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00003680 return NULL;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02003681 do {
3682 written = Py_MIN(len, INT_MAX);
3683 RAND_add(buf, (int)written, entropy);
3684 buf += written;
3685 len -= written;
3686 } while (len);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003687 Py_INCREF(Py_None);
3688 return Py_None;
3689}
3690
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003691PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003692"RAND_add(string, entropy)\n\
3693\n\
3694Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003695bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003696
3697static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003698PySSL_RAND(int len, int pseudo)
3699{
3700 int ok;
3701 PyObject *bytes;
3702 unsigned long err;
3703 const char *errstr;
3704 PyObject *v;
3705
Victor Stinner1e81a392013-12-19 16:47:04 +01003706 if (len < 0) {
3707 PyErr_SetString(PyExc_ValueError, "num must be positive");
3708 return NULL;
3709 }
3710
Victor Stinner99c8b162011-05-24 12:05:19 +02003711 bytes = PyBytes_FromStringAndSize(NULL, len);
3712 if (bytes == NULL)
3713 return NULL;
3714 if (pseudo) {
3715 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3716 if (ok == 0 || ok == 1)
3717 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3718 }
3719 else {
3720 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3721 if (ok == 1)
3722 return bytes;
3723 }
3724 Py_DECREF(bytes);
3725
3726 err = ERR_get_error();
3727 errstr = ERR_reason_error_string(err);
3728 v = Py_BuildValue("(ks)", err, errstr);
3729 if (v != NULL) {
3730 PyErr_SetObject(PySSLErrorObject, v);
3731 Py_DECREF(v);
3732 }
3733 return NULL;
3734}
3735
3736static PyObject *
3737PySSL_RAND_bytes(PyObject *self, PyObject *args)
3738{
3739 int len;
3740 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3741 return NULL;
3742 return PySSL_RAND(len, 0);
3743}
3744
3745PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3746"RAND_bytes(n) -> bytes\n\
3747\n\
3748Generate n cryptographically strong pseudo-random bytes.");
3749
3750static PyObject *
3751PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3752{
3753 int len;
3754 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3755 return NULL;
3756 return PySSL_RAND(len, 1);
3757}
3758
3759PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3760"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3761\n\
3762Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3763generated are cryptographically strong.");
3764
3765static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003766PySSL_RAND_status(PyObject *self)
3767{
Christian Heimes217cfd12007-12-02 14:31:20 +00003768 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003769}
3770
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003771PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003772"RAND_status() -> 0 or 1\n\
3773\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003774Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3775It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3776using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003777
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003778#ifdef HAVE_RAND_EGD
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003779static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003780PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003781{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003782 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003783 int bytes;
3784
Jesus Ceac8754a12012-09-11 02:00:58 +02003785 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003786 PyUnicode_FSConverter, &path))
3787 return NULL;
3788
3789 bytes = RAND_egd(PyBytes_AsString(path));
3790 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003791 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003792 PyErr_SetString(PySSLErrorObject,
3793 "EGD connection failed or EGD did not return "
3794 "enough data to seed the PRNG");
3795 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003796 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003797 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003798}
3799
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003800PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003801"RAND_egd(path) -> bytes\n\
3802\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003803Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3804Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003805fails or if it does not provide enough data to seed PRNG.");
Victor Stinnerbeeb5122014-11-28 13:28:25 +01003806#endif /* HAVE_RAND_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003807
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003808
Christian Heimes6d7ad132013-06-09 18:02:55 +02003809PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3810"get_default_verify_paths() -> tuple\n\
3811\n\
3812Return search paths and environment vars that are used by SSLContext's\n\
3813set_default_verify_paths() to load default CAs. The values are\n\
3814'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3815
3816static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003817PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003818{
3819 PyObject *ofile_env = NULL;
3820 PyObject *ofile = NULL;
3821 PyObject *odir_env = NULL;
3822 PyObject *odir = NULL;
3823
3824#define convert(info, target) { \
3825 const char *tmp = (info); \
3826 target = NULL; \
3827 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3828 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3829 target = PyBytes_FromString(tmp); } \
3830 if (!target) goto error; \
3831 } while(0)
3832
3833 convert(X509_get_default_cert_file_env(), ofile_env);
3834 convert(X509_get_default_cert_file(), ofile);
3835 convert(X509_get_default_cert_dir_env(), odir_env);
3836 convert(X509_get_default_cert_dir(), odir);
3837#undef convert
3838
Christian Heimes200bb1b2013-06-14 15:14:29 +02003839 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003840
3841 error:
3842 Py_XDECREF(ofile_env);
3843 Py_XDECREF(ofile);
3844 Py_XDECREF(odir_env);
3845 Py_XDECREF(odir);
3846 return NULL;
3847}
3848
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003849static PyObject*
3850asn1obj2py(ASN1_OBJECT *obj)
3851{
3852 int nid;
3853 const char *ln, *sn;
3854 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02003855 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003856
3857 nid = OBJ_obj2nid(obj);
3858 if (nid == NID_undef) {
3859 PyErr_Format(PyExc_ValueError, "Unknown object");
3860 return NULL;
3861 }
3862 sn = OBJ_nid2sn(nid);
3863 ln = OBJ_nid2ln(nid);
3864 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3865 if (buflen < 0) {
3866 _setSSLError(NULL, 0, __FILE__, __LINE__);
3867 return NULL;
3868 }
3869 if (buflen) {
3870 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3871 } else {
3872 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3873 }
3874}
3875
3876PyDoc_STRVAR(PySSL_txt2obj_doc,
3877"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3878\n\
3879Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3880objects are looked up by OID. With name=True short and long name are also\n\
3881matched.");
3882
3883static PyObject*
3884PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3885{
3886 char *kwlist[] = {"txt", "name", NULL};
3887 PyObject *result = NULL;
3888 char *txt;
3889 int name = 0;
3890 ASN1_OBJECT *obj;
3891
3892 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3893 kwlist, &txt, &name)) {
3894 return NULL;
3895 }
3896 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3897 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003898 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003899 return NULL;
3900 }
3901 result = asn1obj2py(obj);
3902 ASN1_OBJECT_free(obj);
3903 return result;
3904}
3905
3906PyDoc_STRVAR(PySSL_nid2obj_doc,
3907"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3908\n\
3909Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3910
3911static PyObject*
3912PySSL_nid2obj(PyObject *self, PyObject *args)
3913{
3914 PyObject *result = NULL;
3915 int nid;
3916 ASN1_OBJECT *obj;
3917
3918 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3919 return NULL;
3920 }
3921 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003922 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003923 return NULL;
3924 }
3925 obj = OBJ_nid2obj(nid);
3926 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01003927 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003928 return NULL;
3929 }
3930 result = asn1obj2py(obj);
3931 ASN1_OBJECT_free(obj);
3932 return result;
3933}
3934
Christian Heimes46bebee2013-06-09 19:03:31 +02003935#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01003936
3937static PyObject*
3938certEncodingType(DWORD encodingType)
3939{
3940 static PyObject *x509_asn = NULL;
3941 static PyObject *pkcs_7_asn = NULL;
3942
3943 if (x509_asn == NULL) {
3944 x509_asn = PyUnicode_InternFromString("x509_asn");
3945 if (x509_asn == NULL)
3946 return NULL;
3947 }
3948 if (pkcs_7_asn == NULL) {
3949 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
3950 if (pkcs_7_asn == NULL)
3951 return NULL;
3952 }
3953 switch(encodingType) {
3954 case X509_ASN_ENCODING:
3955 Py_INCREF(x509_asn);
3956 return x509_asn;
3957 case PKCS_7_ASN_ENCODING:
3958 Py_INCREF(pkcs_7_asn);
3959 return pkcs_7_asn;
3960 default:
3961 return PyLong_FromLong(encodingType);
3962 }
3963}
3964
3965static PyObject*
3966parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
3967{
3968 CERT_ENHKEY_USAGE *usage;
3969 DWORD size, error, i;
3970 PyObject *retval;
3971
3972 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
3973 error = GetLastError();
3974 if (error == CRYPT_E_NOT_FOUND) {
3975 Py_RETURN_TRUE;
3976 }
3977 return PyErr_SetFromWindowsErr(error);
3978 }
3979
3980 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
3981 if (usage == NULL) {
3982 return PyErr_NoMemory();
3983 }
3984
3985 /* Now get the actual enhanced usage property */
3986 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
3987 PyMem_Free(usage);
3988 error = GetLastError();
3989 if (error == CRYPT_E_NOT_FOUND) {
3990 Py_RETURN_TRUE;
3991 }
3992 return PyErr_SetFromWindowsErr(error);
3993 }
3994 retval = PySet_New(NULL);
3995 if (retval == NULL) {
3996 goto error;
3997 }
3998 for (i = 0; i < usage->cUsageIdentifier; ++i) {
3999 if (usage->rgpszUsageIdentifier[i]) {
4000 PyObject *oid;
4001 int err;
4002 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4003 if (oid == NULL) {
4004 Py_CLEAR(retval);
4005 goto error;
4006 }
4007 err = PySet_Add(retval, oid);
4008 Py_DECREF(oid);
4009 if (err == -1) {
4010 Py_CLEAR(retval);
4011 goto error;
4012 }
4013 }
4014 }
4015 error:
4016 PyMem_Free(usage);
4017 return retval;
4018}
4019
4020PyDoc_STRVAR(PySSL_enum_certificates_doc,
4021"enum_certificates(store_name) -> []\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02004022\n\
4023Retrieve certificates from Windows' cert store. store_name may be one of\n\
4024'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
Christian Heimes44109d72013-11-22 01:51:30 +01004025The function returns a list of (bytes, encoding_type, trust) tuples. The\n\
Christian Heimes46bebee2013-06-09 19:03:31 +02004026encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
Christian Heimes44109d72013-11-22 01:51:30 +01004027PKCS_7_ASN_ENCODING. The trust setting is either a set of OIDs or the\n\
4028boolean True.");
Bill Janssen40a0f662008-08-12 16:56:25 +00004029
Christian Heimes46bebee2013-06-09 19:03:31 +02004030static PyObject *
Christian Heimes44109d72013-11-22 01:51:30 +01004031PySSL_enum_certificates(PyObject *self, PyObject *args, PyObject *kwds)
Christian Heimes46bebee2013-06-09 19:03:31 +02004032{
Christian Heimes44109d72013-11-22 01:51:30 +01004033 char *kwlist[] = {"store_name", NULL};
Christian Heimes46bebee2013-06-09 19:03:31 +02004034 char *store_name;
Christian Heimes46bebee2013-06-09 19:03:31 +02004035 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004036 PCCERT_CONTEXT pCertCtx = NULL;
4037 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004038 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004039
Christian Heimes44109d72013-11-22 01:51:30 +01004040 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_certificates",
4041 kwlist, &store_name)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004042 return NULL;
4043 }
Christian Heimes44109d72013-11-22 01:51:30 +01004044 result = PyList_New(0);
4045 if (result == NULL) {
4046 return NULL;
4047 }
4048 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4049 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004050 Py_DECREF(result);
4051 return PyErr_SetFromWindowsErr(GetLastError());
4052 }
4053
Christian Heimes44109d72013-11-22 01:51:30 +01004054 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4055 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4056 pCertCtx->cbCertEncoded);
4057 if (!cert) {
4058 Py_CLEAR(result);
4059 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004060 }
Christian Heimes44109d72013-11-22 01:51:30 +01004061 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4062 Py_CLEAR(result);
4063 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004064 }
Christian Heimes44109d72013-11-22 01:51:30 +01004065 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4066 if (keyusage == Py_True) {
4067 Py_DECREF(keyusage);
4068 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004069 }
Christian Heimes44109d72013-11-22 01:51:30 +01004070 if (keyusage == NULL) {
4071 Py_CLEAR(result);
4072 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004073 }
Christian Heimes44109d72013-11-22 01:51:30 +01004074 if ((tup = PyTuple_New(3)) == NULL) {
4075 Py_CLEAR(result);
4076 break;
4077 }
4078 PyTuple_SET_ITEM(tup, 0, cert);
4079 cert = NULL;
4080 PyTuple_SET_ITEM(tup, 1, enc);
4081 enc = NULL;
4082 PyTuple_SET_ITEM(tup, 2, keyusage);
4083 keyusage = NULL;
4084 if (PyList_Append(result, tup) < 0) {
4085 Py_CLEAR(result);
4086 break;
4087 }
4088 Py_CLEAR(tup);
4089 }
4090 if (pCertCtx) {
4091 /* loop ended with an error, need to clean up context manually */
4092 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004093 }
4094
4095 /* In error cases cert, enc and tup may not be NULL */
4096 Py_XDECREF(cert);
4097 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004098 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004099 Py_XDECREF(tup);
4100
4101 if (!CertCloseStore(hStore, 0)) {
4102 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004103 Py_XDECREF(result);
4104 return PyErr_SetFromWindowsErr(GetLastError());
4105 }
4106 return result;
4107}
4108
4109PyDoc_STRVAR(PySSL_enum_crls_doc,
4110"enum_crls(store_name) -> []\n\
4111\n\
4112Retrieve CRLs from Windows' cert store. store_name may be one of\n\
4113'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
4114The function returns a list of (bytes, encoding_type) tuples. The\n\
4115encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
4116PKCS_7_ASN_ENCODING.");
4117
4118static PyObject *
4119PySSL_enum_crls(PyObject *self, PyObject *args, PyObject *kwds)
4120{
4121 char *kwlist[] = {"store_name", NULL};
4122 char *store_name;
4123 HCERTSTORE hStore = NULL;
4124 PCCRL_CONTEXT pCrlCtx = NULL;
4125 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4126 PyObject *result = NULL;
4127
4128 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_crls",
4129 kwlist, &store_name)) {
4130 return NULL;
4131 }
4132 result = PyList_New(0);
4133 if (result == NULL) {
4134 return NULL;
4135 }
4136 hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name);
4137 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004138 Py_DECREF(result);
4139 return PyErr_SetFromWindowsErr(GetLastError());
4140 }
Christian Heimes44109d72013-11-22 01:51:30 +01004141
4142 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4143 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4144 pCrlCtx->cbCrlEncoded);
4145 if (!crl) {
4146 Py_CLEAR(result);
4147 break;
4148 }
4149 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4150 Py_CLEAR(result);
4151 break;
4152 }
4153 if ((tup = PyTuple_New(2)) == NULL) {
4154 Py_CLEAR(result);
4155 break;
4156 }
4157 PyTuple_SET_ITEM(tup, 0, crl);
4158 crl = NULL;
4159 PyTuple_SET_ITEM(tup, 1, enc);
4160 enc = NULL;
4161
4162 if (PyList_Append(result, tup) < 0) {
4163 Py_CLEAR(result);
4164 break;
4165 }
4166 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004167 }
Christian Heimes44109d72013-11-22 01:51:30 +01004168 if (pCrlCtx) {
4169 /* loop ended with an error, need to clean up context manually */
4170 CertFreeCRLContext(pCrlCtx);
4171 }
4172
4173 /* In error cases cert, enc and tup may not be NULL */
4174 Py_XDECREF(crl);
4175 Py_XDECREF(enc);
4176 Py_XDECREF(tup);
4177
4178 if (!CertCloseStore(hStore, 0)) {
4179 /* This error case might shadow another exception.*/
4180 Py_XDECREF(result);
4181 return PyErr_SetFromWindowsErr(GetLastError());
4182 }
4183 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004184}
Christian Heimes44109d72013-11-22 01:51:30 +01004185
4186#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004187
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004188/* List of functions exported by this module. */
4189
4190static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004191 {"_test_decode_cert", PySSL_test_decode_certificate,
4192 METH_VARARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004193 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
4194 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02004195 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
4196 PySSL_RAND_bytes_doc},
4197 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
4198 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerbeeb5122014-11-28 13:28:25 +01004199#ifdef HAVE_RAND_EGD
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004200 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004201 PySSL_RAND_egd_doc},
Victor Stinnerbeeb5122014-11-28 13:28:25 +01004202#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004203 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
4204 PySSL_RAND_status_doc},
Christian Heimes200bb1b2013-06-14 15:14:29 +02004205 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02004206 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02004207#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004208 {"enum_certificates", (PyCFunction)PySSL_enum_certificates,
4209 METH_VARARGS | METH_KEYWORDS, PySSL_enum_certificates_doc},
4210 {"enum_crls", (PyCFunction)PySSL_enum_crls,
4211 METH_VARARGS | METH_KEYWORDS, PySSL_enum_crls_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02004212#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004213 {"txt2obj", (PyCFunction)PySSL_txt2obj,
4214 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
4215 {"nid2obj", (PyCFunction)PySSL_nid2obj,
4216 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004217 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004218};
4219
4220
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004221#ifdef WITH_THREAD
4222
4223/* an implementation of OpenSSL threading operations in terms
4224 of the Python C thread library */
4225
4226static PyThread_type_lock *_ssl_locks = NULL;
4227
Christian Heimes4d98ca92013-08-19 17:36:29 +02004228#if OPENSSL_VERSION_NUMBER >= 0x10000000
4229/* use new CRYPTO_THREADID API. */
4230static void
4231_ssl_threadid_callback(CRYPTO_THREADID *id)
4232{
4233 CRYPTO_THREADID_set_numeric(id,
4234 (unsigned long)PyThread_get_thread_ident());
4235}
4236#else
4237/* deprecated CRYPTO_set_id_callback() API. */
4238static unsigned long
4239_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004240 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004241}
Christian Heimes4d98ca92013-08-19 17:36:29 +02004242#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004243
Bill Janssen6e027db2007-11-15 22:23:56 +00004244static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004245 (int mode, int n, const char *file, int line) {
4246 /* this function is needed to perform locking on shared data
4247 structures. (Note that OpenSSL uses a number of global data
4248 structures that will be implicitly shared whenever multiple
4249 threads use OpenSSL.) Multi-threaded applications will
4250 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004251
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004252 locking_function() must be able to handle up to
4253 CRYPTO_num_locks() different mutex locks. It sets the n-th
4254 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004255
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004256 file and line are the file number of the function setting the
4257 lock. They can be useful for debugging.
4258 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004259
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004260 if ((_ssl_locks == NULL) ||
4261 (n < 0) || ((unsigned)n >= _ssl_locks_count))
4262 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004263
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004264 if (mode & CRYPTO_LOCK) {
4265 PyThread_acquire_lock(_ssl_locks[n], 1);
4266 } else {
4267 PyThread_release_lock(_ssl_locks[n]);
4268 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004269}
4270
4271static int _setup_ssl_threads(void) {
4272
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004273 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004274
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004275 if (_ssl_locks == NULL) {
4276 _ssl_locks_count = CRYPTO_num_locks();
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004277 _ssl_locks = PyMem_New(PyThread_type_lock, _ssl_locks_count);
4278 if (_ssl_locks == NULL) {
4279 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004280 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004281 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004282 memset(_ssl_locks, 0,
4283 sizeof(PyThread_type_lock) * _ssl_locks_count);
4284 for (i = 0; i < _ssl_locks_count; i++) {
4285 _ssl_locks[i] = PyThread_allocate_lock();
4286 if (_ssl_locks[i] == NULL) {
4287 unsigned int j;
4288 for (j = 0; j < i; j++) {
4289 PyThread_free_lock(_ssl_locks[j]);
4290 }
Victor Stinnerb6404912013-07-07 16:21:41 +02004291 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004292 return 0;
4293 }
4294 }
4295 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004296#if OPENSSL_VERSION_NUMBER >= 0x10000000
4297 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
4298#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004299 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02004300#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004301 }
4302 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004303}
4304
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004305#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004306
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004307PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004308"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00004309for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004310
Martin v. Löwis1a214512008-06-11 05:26:20 +00004311
4312static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004313 PyModuleDef_HEAD_INIT,
4314 "_ssl",
4315 module_doc,
4316 -1,
4317 PySSL_methods,
4318 NULL,
4319 NULL,
4320 NULL,
4321 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00004322};
4323
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004324
4325static void
4326parse_openssl_version(unsigned long libver,
4327 unsigned int *major, unsigned int *minor,
4328 unsigned int *fix, unsigned int *patch,
4329 unsigned int *status)
4330{
4331 *status = libver & 0xF;
4332 libver >>= 4;
4333 *patch = libver & 0xFF;
4334 libver >>= 8;
4335 *fix = libver & 0xFF;
4336 libver >>= 8;
4337 *minor = libver & 0xFF;
4338 libver >>= 8;
4339 *major = libver & 0xFF;
4340}
4341
Mark Hammondfe51c6d2002-08-02 02:27:13 +00004342PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00004343PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004344{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004345 PyObject *m, *d, *r;
4346 unsigned long libver;
4347 unsigned int major, minor, fix, patch, status;
4348 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004349 struct py_ssl_error_code *errcode;
4350 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004351
Antoine Pitrou152efa22010-05-16 18:19:27 +00004352 if (PyType_Ready(&PySSLContext_Type) < 0)
4353 return NULL;
4354 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004355 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004356 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
4357 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004358
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004359 m = PyModule_Create(&_sslmodule);
4360 if (m == NULL)
4361 return NULL;
4362 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004363
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004364 /* Load _socket module and its C API */
4365 socket_api = PySocketModule_ImportModuleAndAPI();
4366 if (!socket_api)
4367 return NULL;
4368 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004369
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004370 /* Init OpenSSL */
4371 SSL_load_error_strings();
4372 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004373#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004374 /* note that this will start threading if not already started */
4375 if (!_setup_ssl_threads()) {
4376 return NULL;
4377 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004378#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004379 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004380
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004381 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004382 sslerror_type_slots[0].pfunc = PyExc_OSError;
4383 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004384 if (PySSLErrorObject == NULL)
4385 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004386
Antoine Pitrou41032a62011-10-27 23:56:55 +02004387 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
4388 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
4389 PySSLErrorObject, NULL);
4390 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
4391 "ssl.SSLWantReadError", SSLWantReadError_doc,
4392 PySSLErrorObject, NULL);
4393 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
4394 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
4395 PySSLErrorObject, NULL);
4396 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
4397 "ssl.SSLSyscallError", SSLSyscallError_doc,
4398 PySSLErrorObject, NULL);
4399 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
4400 "ssl.SSLEOFError", SSLEOFError_doc,
4401 PySSLErrorObject, NULL);
4402 if (PySSLZeroReturnErrorObject == NULL
4403 || PySSLWantReadErrorObject == NULL
4404 || PySSLWantWriteErrorObject == NULL
4405 || PySSLSyscallErrorObject == NULL
4406 || PySSLEOFErrorObject == NULL)
4407 return NULL;
4408 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
4409 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
4410 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
4411 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
4412 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
4413 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004414 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004415 if (PyDict_SetItemString(d, "_SSLContext",
4416 (PyObject *)&PySSLContext_Type) != 0)
4417 return NULL;
4418 if (PyDict_SetItemString(d, "_SSLSocket",
4419 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004420 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004421 if (PyDict_SetItemString(d, "MemoryBIO",
4422 (PyObject *)&PySSLMemoryBIO_Type) != 0)
4423 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004424 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
4425 PY_SSL_ERROR_ZERO_RETURN);
4426 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
4427 PY_SSL_ERROR_WANT_READ);
4428 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
4429 PY_SSL_ERROR_WANT_WRITE);
4430 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
4431 PY_SSL_ERROR_WANT_X509_LOOKUP);
4432 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
4433 PY_SSL_ERROR_SYSCALL);
4434 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
4435 PY_SSL_ERROR_SSL);
4436 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
4437 PY_SSL_ERROR_WANT_CONNECT);
4438 /* non ssl.h errorcodes */
4439 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
4440 PY_SSL_ERROR_EOF);
4441 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
4442 PY_SSL_ERROR_INVALID_ERROR_CODE);
4443 /* cert requirements */
4444 PyModule_AddIntConstant(m, "CERT_NONE",
4445 PY_SSL_CERT_NONE);
4446 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
4447 PY_SSL_CERT_OPTIONAL);
4448 PyModule_AddIntConstant(m, "CERT_REQUIRED",
4449 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01004450 /* CRL verification for verification_flags */
4451 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
4452 0);
4453 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
4454 X509_V_FLAG_CRL_CHECK);
4455 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
4456 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
4457 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
4458 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05004459#ifdef X509_V_FLAG_TRUSTED_FIRST
4460 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
4461 X509_V_FLAG_TRUSTED_FIRST);
4462#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00004463
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004464 /* Alert Descriptions from ssl.h */
4465 /* note RESERVED constants no longer intended for use have been removed */
4466 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
4467
4468#define ADD_AD_CONSTANT(s) \
4469 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
4470 SSL_AD_##s)
4471
4472 ADD_AD_CONSTANT(CLOSE_NOTIFY);
4473 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
4474 ADD_AD_CONSTANT(BAD_RECORD_MAC);
4475 ADD_AD_CONSTANT(RECORD_OVERFLOW);
4476 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
4477 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
4478 ADD_AD_CONSTANT(BAD_CERTIFICATE);
4479 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
4480 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
4481 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
4482 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
4483 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
4484 ADD_AD_CONSTANT(UNKNOWN_CA);
4485 ADD_AD_CONSTANT(ACCESS_DENIED);
4486 ADD_AD_CONSTANT(DECODE_ERROR);
4487 ADD_AD_CONSTANT(DECRYPT_ERROR);
4488 ADD_AD_CONSTANT(PROTOCOL_VERSION);
4489 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
4490 ADD_AD_CONSTANT(INTERNAL_ERROR);
4491 ADD_AD_CONSTANT(USER_CANCELLED);
4492 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004493 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004494#ifdef SSL_AD_UNSUPPORTED_EXTENSION
4495 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
4496#endif
4497#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
4498 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
4499#endif
4500#ifdef SSL_AD_UNRECOGNIZED_NAME
4501 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
4502#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004503#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
4504 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
4505#endif
4506#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
4507 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
4508#endif
4509#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
4510 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
4511#endif
4512
4513#undef ADD_AD_CONSTANT
4514
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004515 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02004516#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004517 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
4518 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02004519#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05004520#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004521 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
4522 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05004523#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004524 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
4525 PY_SSL_VERSION_SSL23);
4526 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
4527 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004528#if HAVE_TLSv1_2
4529 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
4530 PY_SSL_VERSION_TLS1_1);
4531 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
4532 PY_SSL_VERSION_TLS1_2);
4533#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004534
Antoine Pitroub5218772010-05-21 09:56:06 +00004535 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01004536 PyModule_AddIntConstant(m, "OP_ALL",
4537 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00004538 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
4539 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
4540 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01004541#if HAVE_TLSv1_2
4542 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
4543 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
4544#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01004545 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
4546 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004547 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004548#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004549 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01004550#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01004551#ifdef SSL_OP_NO_COMPRESSION
4552 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
4553 SSL_OP_NO_COMPRESSION);
4554#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004555
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004556#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00004557 r = Py_True;
4558#else
4559 r = Py_False;
4560#endif
4561 Py_INCREF(r);
4562 PyModule_AddObject(m, "HAS_SNI", r);
4563
Antoine Pitroud6494802011-07-21 01:11:30 +02004564 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02004565 Py_INCREF(r);
4566 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
4567
Antoine Pitrou501da612011-12-21 09:27:41 +01004568#ifdef OPENSSL_NO_ECDH
4569 r = Py_False;
4570#else
4571 r = Py_True;
4572#endif
4573 Py_INCREF(r);
4574 PyModule_AddObject(m, "HAS_ECDH", r);
4575
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01004576#ifdef OPENSSL_NPN_NEGOTIATED
4577 r = Py_True;
4578#else
4579 r = Py_False;
4580#endif
4581 Py_INCREF(r);
4582 PyModule_AddObject(m, "HAS_NPN", r);
4583
Benjamin Petersoncca27322015-01-23 16:35:37 -05004584#ifdef HAVE_ALPN
4585 r = Py_True;
4586#else
4587 r = Py_False;
4588#endif
4589 Py_INCREF(r);
4590 PyModule_AddObject(m, "HAS_ALPN", r);
4591
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02004592 /* Mappings for error codes */
4593 err_codes_to_names = PyDict_New();
4594 err_names_to_codes = PyDict_New();
4595 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
4596 return NULL;
4597 errcode = error_codes;
4598 while (errcode->mnemonic != NULL) {
4599 PyObject *mnemo, *key;
4600 mnemo = PyUnicode_FromString(errcode->mnemonic);
4601 key = Py_BuildValue("ii", errcode->library, errcode->reason);
4602 if (mnemo == NULL || key == NULL)
4603 return NULL;
4604 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
4605 return NULL;
4606 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
4607 return NULL;
4608 Py_DECREF(key);
4609 Py_DECREF(mnemo);
4610 errcode++;
4611 }
4612 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
4613 return NULL;
4614 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
4615 return NULL;
4616
4617 lib_codes_to_names = PyDict_New();
4618 if (lib_codes_to_names == NULL)
4619 return NULL;
4620 libcode = library_codes;
4621 while (libcode->library != NULL) {
4622 PyObject *mnemo, *key;
4623 key = PyLong_FromLong(libcode->code);
4624 mnemo = PyUnicode_FromString(libcode->library);
4625 if (key == NULL || mnemo == NULL)
4626 return NULL;
4627 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
4628 return NULL;
4629 Py_DECREF(key);
4630 Py_DECREF(mnemo);
4631 libcode++;
4632 }
4633 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
4634 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02004635
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004636 /* OpenSSL version */
4637 /* SSLeay() gives us the version of the library linked against,
4638 which could be different from the headers version.
4639 */
4640 libver = SSLeay();
4641 r = PyLong_FromUnsignedLong(libver);
4642 if (r == NULL)
4643 return NULL;
4644 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
4645 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004646 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004647 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4648 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
4649 return NULL;
4650 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
4651 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
4652 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00004653
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02004654 libver = OPENSSL_VERSION_NUMBER;
4655 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
4656 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
4657 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
4658 return NULL;
4659
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00004660 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004661}