blob: 499e8ba269fa06ea9a02c8e00bf5570ee32fabe6 [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
17#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000018
Thomas Wouters1b7f8912007-09-19 03:06:30 +000019#ifdef WITH_THREAD
20#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020021
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020023#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
24 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
25#define PySSL_END_ALLOW_THREADS_S(save) \
26 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000027#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000028 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020029 PySSL_BEGIN_ALLOW_THREADS_S(_save);
30#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
31#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
32#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000033
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000034#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000035
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020036#define PySSL_BEGIN_ALLOW_THREADS_S(save)
37#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000038#define PySSL_BEGIN_ALLOW_THREADS
39#define PySSL_BLOCK_THREADS
40#define PySSL_UNBLOCK_THREADS
41#define PySSL_END_ALLOW_THREADS
42
43#endif
44
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000045enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000046 /* these mirror ssl.h */
47 PY_SSL_ERROR_NONE,
48 PY_SSL_ERROR_SSL,
49 PY_SSL_ERROR_WANT_READ,
50 PY_SSL_ERROR_WANT_WRITE,
51 PY_SSL_ERROR_WANT_X509_LOOKUP,
52 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
53 PY_SSL_ERROR_ZERO_RETURN,
54 PY_SSL_ERROR_WANT_CONNECT,
55 /* start of non ssl.h errorcodes */
56 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
57 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
58 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000059};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000060
Thomas Woutersed03b412007-08-28 21:37:11 +000061enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000062 PY_SSL_CLIENT,
63 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000064};
65
66enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000067 PY_SSL_CERT_NONE,
68 PY_SSL_CERT_OPTIONAL,
69 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +000070};
71
72enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000073 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +020074 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000075 PY_SSL_VERSION_SSL23,
76 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000077};
78
Antoine Pitrou3b36fb12012-06-22 21:11:52 +020079struct py_ssl_error_code {
80 const char *mnemonic;
81 int library, reason;
82};
83
84struct py_ssl_library_code {
85 const char *library;
86 int code;
87};
88
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000089/* Include symbols from _socket module */
90#include "socketmodule.h"
91
Benjamin Petersonb173f782009-05-05 22:31:58 +000092static PySocketModule_APIObject PySocketModule;
93
Thomas Woutersed03b412007-08-28 21:37:11 +000094#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000095#include <poll.h>
96#elif defined(HAVE_SYS_POLL_H)
97#include <sys/poll.h>
98#endif
99
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000100/* Include OpenSSL header files */
101#include "openssl/rsa.h"
102#include "openssl/crypto.h"
103#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000104#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000105#include "openssl/pem.h"
106#include "openssl/ssl.h"
107#include "openssl/err.h"
108#include "openssl/rand.h"
109
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200110/* Include generated data (error codes) */
111#include "_ssl_data.h"
112
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000113/* SSL error object */
114static PyObject *PySSLErrorObject;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200115static PyObject *PySSLZeroReturnErrorObject;
116static PyObject *PySSLWantReadErrorObject;
117static PyObject *PySSLWantWriteErrorObject;
118static PyObject *PySSLSyscallErrorObject;
119static PyObject *PySSLEOFErrorObject;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000120
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200121/* Error mappings */
122static PyObject *err_codes_to_names;
123static PyObject *err_names_to_codes;
124static PyObject *lib_codes_to_names;
125
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000126#ifdef WITH_THREAD
127
128/* serves as a flag to see whether we've initialized the SSL thread support. */
129/* 0 means no, greater than 0 means yes */
130
131static unsigned int _ssl_locks_count = 0;
132
133#endif /* def WITH_THREAD */
134
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000135/* SSL socket object */
136
137#define X509_NAME_MAXLEN 256
138
139/* RAND_* APIs got added to OpenSSL in 0.9.5 */
140#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
141# define HAVE_OPENSSL_RAND 1
142#else
143# undef HAVE_OPENSSL_RAND
144#endif
145
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000146/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
147 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
148 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
149#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000150# define HAVE_SSL_CTX_CLEAR_OPTIONS
151#else
152# undef HAVE_SSL_CTX_CLEAR_OPTIONS
153#endif
154
Antoine Pitroud6494802011-07-21 01:11:30 +0200155/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
156 * older SSL, but let's be safe */
157#define PySSL_CB_MAXLEN 128
158
159/* SSL_get_finished got added to OpenSSL in 0.9.5 */
160#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
161# define HAVE_OPENSSL_FINISHED 1
162#else
163# define HAVE_OPENSSL_FINISHED 0
164#endif
165
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100166/* ECDH support got added to OpenSSL in 0.9.8 */
167#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
168# define OPENSSL_NO_ECDH
169#endif
170
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100171/* compression support got added to OpenSSL in 0.9.8 */
172#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
173# define OPENSSL_NO_COMP
174#endif
175
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100176
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000177typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000178 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000179 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100180#ifdef OPENSSL_NPN_NEGOTIATED
181 char *npn_protocols;
182 int npn_protocols_len;
183#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000184} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000185
Antoine Pitrou152efa22010-05-16 18:19:27 +0000186typedef struct {
187 PyObject_HEAD
188 PyObject *Socket; /* weakref to socket on which we're layered */
189 SSL *ssl;
190 X509 *peer_cert;
191 int shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200192 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000193} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000194
Antoine Pitrou152efa22010-05-16 18:19:27 +0000195static PyTypeObject PySSLContext_Type;
196static PyTypeObject PySSLSocket_Type;
197
198static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
199static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000200static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000201 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000202static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
203static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000204
Antoine Pitrou152efa22010-05-16 18:19:27 +0000205#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
206#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000207
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000208typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000209 SOCKET_IS_NONBLOCKING,
210 SOCKET_IS_BLOCKING,
211 SOCKET_HAS_TIMED_OUT,
212 SOCKET_HAS_BEEN_CLOSED,
213 SOCKET_TOO_LARGE_FOR_SELECT,
214 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000215} timeout_state;
216
Thomas Woutersed03b412007-08-28 21:37:11 +0000217/* Wrap error strings with filename and line # */
218#define STRINGIFY1(x) #x
219#define STRINGIFY2(x) STRINGIFY1(x)
220#define ERRSTR1(x,y,z) (x ":" y ": " z)
221#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
222
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200223
224/*
225 * SSL errors.
226 */
227
228PyDoc_STRVAR(SSLError_doc,
229"An error occurred in the SSL implementation.");
230
231PyDoc_STRVAR(SSLZeroReturnError_doc,
232"SSL/TLS session closed cleanly.");
233
234PyDoc_STRVAR(SSLWantReadError_doc,
235"Non-blocking SSL socket needs to read more data\n"
236"before the requested operation can be completed.");
237
238PyDoc_STRVAR(SSLWantWriteError_doc,
239"Non-blocking SSL socket needs to write more data\n"
240"before the requested operation can be completed.");
241
242PyDoc_STRVAR(SSLSyscallError_doc,
243"System error when attempting SSL operation.");
244
245PyDoc_STRVAR(SSLEOFError_doc,
246"SSL/TLS connection terminated abruptly.");
247
248static PyObject *
249SSLError_str(PyOSErrorObject *self)
250{
251 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
252 Py_INCREF(self->strerror);
253 return self->strerror;
254 }
255 else
256 return PyObject_Str(self->args);
257}
258
259static PyType_Slot sslerror_type_slots[] = {
260 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
261 {Py_tp_doc, SSLError_doc},
262 {Py_tp_str, SSLError_str},
263 {0, 0},
264};
265
266static PyType_Spec sslerror_type_spec = {
267 "ssl.SSLError",
268 sizeof(PyOSErrorObject),
269 0,
270 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
271 sslerror_type_slots
272};
273
274static void
275fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
276 int lineno, unsigned long errcode)
277{
278 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
279 PyObject *init_value, *msg, *key;
280 _Py_IDENTIFIER(reason);
281 _Py_IDENTIFIER(library);
282
283 if (errcode != 0) {
284 int lib, reason;
285
286 lib = ERR_GET_LIB(errcode);
287 reason = ERR_GET_REASON(errcode);
288 key = Py_BuildValue("ii", lib, reason);
289 if (key == NULL)
290 goto fail;
291 reason_obj = PyDict_GetItem(err_codes_to_names, key);
292 Py_DECREF(key);
293 if (reason_obj == NULL) {
294 /* XXX if reason < 100, it might reflect a library number (!!) */
295 PyErr_Clear();
296 }
297 key = PyLong_FromLong(lib);
298 if (key == NULL)
299 goto fail;
300 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
301 Py_DECREF(key);
302 if (lib_obj == NULL) {
303 PyErr_Clear();
304 }
305 if (errstr == NULL)
306 errstr = ERR_reason_error_string(errcode);
307 }
308 if (errstr == NULL)
309 errstr = "unknown error";
310
311 if (reason_obj && lib_obj)
312 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
313 lib_obj, reason_obj, errstr, lineno);
314 else if (lib_obj)
315 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
316 lib_obj, errstr, lineno);
317 else
318 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
319
320 if (msg == NULL)
321 goto fail;
322 init_value = Py_BuildValue("iN", ssl_errno, msg);
323 err_value = PyObject_CallObject(type, init_value);
324 Py_DECREF(init_value);
325 if (err_value == NULL)
326 goto fail;
327 if (reason_obj == NULL)
328 reason_obj = Py_None;
329 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
330 goto fail;
331 if (lib_obj == NULL)
332 lib_obj = Py_None;
333 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
334 goto fail;
335 PyErr_SetObject(type, err_value);
336fail:
337 Py_XDECREF(err_value);
338}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000339
340static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000341PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000342{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200343 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200344 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000345 int err;
346 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200347 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000348
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000349 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200350 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000351
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000352 if (obj->ssl != NULL) {
353 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000354
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000355 switch (err) {
356 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200357 errstr = "TLS/SSL connection has been closed (EOF)";
358 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000359 p = PY_SSL_ERROR_ZERO_RETURN;
360 break;
361 case SSL_ERROR_WANT_READ:
362 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200363 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000364 p = PY_SSL_ERROR_WANT_READ;
365 break;
366 case SSL_ERROR_WANT_WRITE:
367 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200368 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000369 errstr = "The operation did not complete (write)";
370 break;
371 case SSL_ERROR_WANT_X509_LOOKUP:
372 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000373 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000374 break;
375 case SSL_ERROR_WANT_CONNECT:
376 p = PY_SSL_ERROR_WANT_CONNECT;
377 errstr = "The operation did not complete (connect)";
378 break;
379 case SSL_ERROR_SYSCALL:
380 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000381 if (e == 0) {
382 PySocketSockObject *s
383 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
384 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000385 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200386 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000387 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000388 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000389 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000390 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000391 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200392 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000393 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200394 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000395 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000396 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200397 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000398 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000399 }
400 } else {
401 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000402 }
403 break;
404 }
405 case SSL_ERROR_SSL:
406 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000407 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200408 if (e == 0)
409 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000410 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000411 break;
412 }
413 default:
414 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
415 errstr = "Invalid error code";
416 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000417 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200418 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000419 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000420 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000421}
422
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000423static PyObject *
424_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
425
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200426 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000427 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200428 else
429 errcode = 0;
430 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000431 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000432 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000433}
434
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200435/*
436 * SSL objects
437 */
438
Antoine Pitrou152efa22010-05-16 18:19:27 +0000439static PySSLSocket *
440newPySSLSocket(SSL_CTX *ctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000441 enum py_ssl_server_or_client socket_type,
442 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000443{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000444 PySSLSocket *self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000445
Antoine Pitrou152efa22010-05-16 18:19:27 +0000446 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000447 if (self == NULL)
448 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000449
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000450 self->peer_cert = NULL;
451 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000452 self->Socket = NULL;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200453 self->shutdown_seen_zero = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000454
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000455 /* Make sure the SSL error state is initialized */
456 (void) ERR_get_state();
457 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000458
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000459 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000460 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000461 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000462 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000463#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000464 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000465#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000466
Antoine Pitroud5323212010-10-22 18:19:07 +0000467#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
468 if (server_hostname != NULL)
469 SSL_set_tlsext_host_name(self->ssl, server_hostname);
470#endif
471
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000472 /* If the socket is in non-blocking mode or timeout mode, set the BIO
473 * to non-blocking mode (blocking is the default)
474 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000475 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000476 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
477 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
478 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000479
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000480 PySSL_BEGIN_ALLOW_THREADS
481 if (socket_type == PY_SSL_CLIENT)
482 SSL_set_connect_state(self->ssl);
483 else
484 SSL_set_accept_state(self->ssl);
485 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000486
Antoine Pitroud6494802011-07-21 01:11:30 +0200487 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000488 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000489 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000490}
491
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000492/* SSL object methods */
493
Antoine Pitrou152efa22010-05-16 18:19:27 +0000494static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000495{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000496 int ret;
497 int err;
498 int sockstate, nonblocking;
499 PySocketSockObject *sock
500 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000501
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000502 if (((PyObject*)sock) == Py_None) {
503 _setSSLError("Underlying socket connection gone",
504 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
505 return NULL;
506 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000507 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000508
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000509 /* just in case the blocking state of the socket has been changed */
510 nonblocking = (sock->sock_timeout >= 0.0);
511 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
512 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000513
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000514 /* Actually negotiate SSL connection */
515 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000516 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000517 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 ret = SSL_do_handshake(self->ssl);
519 err = SSL_get_error(self->ssl, ret);
520 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000521 if (PyErr_CheckSignals())
522 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000523 if (err == SSL_ERROR_WANT_READ) {
524 sockstate = check_socket_and_wait_for_timeout(sock, 0);
525 } else if (err == SSL_ERROR_WANT_WRITE) {
526 sockstate = check_socket_and_wait_for_timeout(sock, 1);
527 } else {
528 sockstate = SOCKET_OPERATION_OK;
529 }
530 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000531 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000532 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000533 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000534 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
535 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000536 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000537 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000538 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
539 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000540 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000541 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000542 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
543 break;
544 }
545 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000546 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000547 if (ret < 1)
548 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000549
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000550 if (self->peer_cert)
551 X509_free (self->peer_cert);
552 PySSL_BEGIN_ALLOW_THREADS
553 self->peer_cert = SSL_get_peer_certificate(self->ssl);
554 PySSL_END_ALLOW_THREADS
555
556 Py_INCREF(Py_None);
557 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000558
559error:
560 Py_DECREF(sock);
561 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000562}
563
Thomas Woutersed03b412007-08-28 21:37:11 +0000564static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000565_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000566
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000567 char namebuf[X509_NAME_MAXLEN];
568 int buflen;
569 PyObject *name_obj;
570 PyObject *value_obj;
571 PyObject *attr;
572 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000573
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000574 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
575 if (buflen < 0) {
576 _setSSLError(NULL, 0, __FILE__, __LINE__);
577 goto fail;
578 }
579 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
580 if (name_obj == NULL)
581 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000582
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000583 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
584 if (buflen < 0) {
585 _setSSLError(NULL, 0, __FILE__, __LINE__);
586 Py_DECREF(name_obj);
587 goto fail;
588 }
589 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000590 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000591 OPENSSL_free(valuebuf);
592 if (value_obj == NULL) {
593 Py_DECREF(name_obj);
594 goto fail;
595 }
596 attr = PyTuple_New(2);
597 if (attr == NULL) {
598 Py_DECREF(name_obj);
599 Py_DECREF(value_obj);
600 goto fail;
601 }
602 PyTuple_SET_ITEM(attr, 0, name_obj);
603 PyTuple_SET_ITEM(attr, 1, value_obj);
604 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000605
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000606 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000607 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000608}
609
610static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000611_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000612{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000613 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
614 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
615 PyObject *rdnt;
616 PyObject *attr = NULL; /* tuple to hold an attribute */
617 int entry_count = X509_NAME_entry_count(xname);
618 X509_NAME_ENTRY *entry;
619 ASN1_OBJECT *name;
620 ASN1_STRING *value;
621 int index_counter;
622 int rdn_level = -1;
623 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000625 dn = PyList_New(0);
626 if (dn == NULL)
627 return NULL;
628 /* now create another tuple to hold the top-level RDN */
629 rdn = PyList_New(0);
630 if (rdn == NULL)
631 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000632
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000633 for (index_counter = 0;
634 index_counter < entry_count;
635 index_counter++)
636 {
637 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000638
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000639 /* check to see if we've gotten to a new RDN */
640 if (rdn_level >= 0) {
641 if (rdn_level != entry->set) {
642 /* yes, new RDN */
643 /* add old RDN to DN */
644 rdnt = PyList_AsTuple(rdn);
645 Py_DECREF(rdn);
646 if (rdnt == NULL)
647 goto fail0;
648 retcode = PyList_Append(dn, rdnt);
649 Py_DECREF(rdnt);
650 if (retcode < 0)
651 goto fail0;
652 /* create new RDN */
653 rdn = PyList_New(0);
654 if (rdn == NULL)
655 goto fail0;
656 }
657 }
658 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000659
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000660 /* now add this attribute to the current RDN */
661 name = X509_NAME_ENTRY_get_object(entry);
662 value = X509_NAME_ENTRY_get_data(entry);
663 attr = _create_tuple_for_attribute(name, value);
664 /*
665 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
666 entry->set,
667 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
668 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
669 */
670 if (attr == NULL)
671 goto fail1;
672 retcode = PyList_Append(rdn, attr);
673 Py_DECREF(attr);
674 if (retcode < 0)
675 goto fail1;
676 }
677 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100678 if (rdn != NULL) {
679 if (PyList_GET_SIZE(rdn) > 0) {
680 rdnt = PyList_AsTuple(rdn);
681 Py_DECREF(rdn);
682 if (rdnt == NULL)
683 goto fail0;
684 retcode = PyList_Append(dn, rdnt);
685 Py_DECREF(rdnt);
686 if (retcode < 0)
687 goto fail0;
688 }
689 else {
690 Py_DECREF(rdn);
691 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000692 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000693
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000694 /* convert list to tuple */
695 rdnt = PyList_AsTuple(dn);
696 Py_DECREF(dn);
697 if (rdnt == NULL)
698 return NULL;
699 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000700
701 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000702 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000703
704 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000705 Py_XDECREF(dn);
706 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000707}
708
709static PyObject *
710_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000711
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000712 /* this code follows the procedure outlined in
713 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
714 function to extract the STACK_OF(GENERAL_NAME),
715 then iterates through the stack to add the
716 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000717
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000718 int i, j;
719 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200720 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000721 X509_EXTENSION *ext = NULL;
722 GENERAL_NAMES *names = NULL;
723 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000724 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000725 BIO *biobuf = NULL;
726 char buf[2048];
727 char *vptr;
728 int len;
729 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000730#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000731 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000732#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000733 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000734#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000735
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000736 if (certificate == NULL)
737 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000738
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000739 /* get a memory buffer */
740 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000741
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200742 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 while ((i = X509_get_ext_by_NID(
744 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000746 if (peer_alt_names == Py_None) {
747 peer_alt_names = PyList_New(0);
748 if (peer_alt_names == NULL)
749 goto fail;
750 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000751
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000752 /* now decode the altName */
753 ext = X509_get_ext(certificate, i);
754 if(!(method = X509V3_EXT_get(ext))) {
755 PyErr_SetString
756 (PySSLErrorObject,
757 ERRSTR("No method for internalizing subjectAltName!"));
758 goto fail;
759 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000760
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000761 p = ext->value->data;
762 if (method->it)
763 names = (GENERAL_NAMES*)
764 (ASN1_item_d2i(NULL,
765 &p,
766 ext->value->length,
767 ASN1_ITEM_ptr(method->it)));
768 else
769 names = (GENERAL_NAMES*)
770 (method->d2i(NULL,
771 &p,
772 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000773
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000775 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200776 int gntype;
777 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000778
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200780 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200781 switch (gntype) {
782 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 /* we special-case DirName as a tuple of
784 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000785
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000786 t = PyTuple_New(2);
787 if (t == NULL) {
788 goto fail;
789 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000790
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000791 v = PyUnicode_FromString("DirName");
792 if (v == NULL) {
793 Py_DECREF(t);
794 goto fail;
795 }
796 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000797
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000798 v = _create_tuple_for_X509_NAME (name->d.dirn);
799 if (v == NULL) {
800 Py_DECREF(t);
801 goto fail;
802 }
803 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200804 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000805
Christian Heimes824f7f32013-08-17 00:54:47 +0200806 case GEN_EMAIL:
807 case GEN_DNS:
808 case GEN_URI:
809 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
810 correctly, CVE-2013-4238 */
811 t = PyTuple_New(2);
812 if (t == NULL)
813 goto fail;
814 switch (gntype) {
815 case GEN_EMAIL:
816 v = PyUnicode_FromString("email");
817 as = name->d.rfc822Name;
818 break;
819 case GEN_DNS:
820 v = PyUnicode_FromString("DNS");
821 as = name->d.dNSName;
822 break;
823 case GEN_URI:
824 v = PyUnicode_FromString("URI");
825 as = name->d.uniformResourceIdentifier;
826 break;
827 }
828 if (v == NULL) {
829 Py_DECREF(t);
830 goto fail;
831 }
832 PyTuple_SET_ITEM(t, 0, v);
833 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
834 ASN1_STRING_length(as));
835 if (v == NULL) {
836 Py_DECREF(t);
837 goto fail;
838 }
839 PyTuple_SET_ITEM(t, 1, v);
840 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000841
Christian Heimes824f7f32013-08-17 00:54:47 +0200842 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000843 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200844 switch (gntype) {
845 /* check for new general name type */
846 case GEN_OTHERNAME:
847 case GEN_X400:
848 case GEN_EDIPARTY:
849 case GEN_IPADD:
850 case GEN_RID:
851 break;
852 default:
853 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
854 "Unknown general name type %d",
855 gntype) == -1) {
856 goto fail;
857 }
858 break;
859 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000860 (void) BIO_reset(biobuf);
861 GENERAL_NAME_print(biobuf, name);
862 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
863 if (len < 0) {
864 _setSSLError(NULL, 0, __FILE__, __LINE__);
865 goto fail;
866 }
867 vptr = strchr(buf, ':');
868 if (vptr == NULL)
869 goto fail;
870 t = PyTuple_New(2);
871 if (t == NULL)
872 goto fail;
873 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
874 if (v == NULL) {
875 Py_DECREF(t);
876 goto fail;
877 }
878 PyTuple_SET_ITEM(t, 0, v);
879 v = PyUnicode_FromStringAndSize((vptr + 1),
880 (len - (vptr - buf + 1)));
881 if (v == NULL) {
882 Py_DECREF(t);
883 goto fail;
884 }
885 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200886 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000887 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000888
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000889 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000890
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 if (PyList_Append(peer_alt_names, t) < 0) {
892 Py_DECREF(t);
893 goto fail;
894 }
895 Py_DECREF(t);
896 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100897 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000898 }
899 BIO_free(biobuf);
900 if (peer_alt_names != Py_None) {
901 v = PyList_AsTuple(peer_alt_names);
902 Py_DECREF(peer_alt_names);
903 return v;
904 } else {
905 return peer_alt_names;
906 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000907
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000908
909 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000910 if (biobuf != NULL)
911 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000912
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000913 if (peer_alt_names != Py_None) {
914 Py_XDECREF(peer_alt_names);
915 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000916
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000917 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000918}
919
920static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000921_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000922
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000923 PyObject *retval = NULL;
924 BIO *biobuf = NULL;
925 PyObject *peer;
926 PyObject *peer_alt_names = NULL;
927 PyObject *issuer;
928 PyObject *version;
929 PyObject *sn_obj;
930 ASN1_INTEGER *serialNumber;
931 char buf[2048];
932 int len;
933 ASN1_TIME *notBefore, *notAfter;
934 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000935
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 retval = PyDict_New();
937 if (retval == NULL)
938 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000939
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 peer = _create_tuple_for_X509_NAME(
941 X509_get_subject_name(certificate));
942 if (peer == NULL)
943 goto fail0;
944 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
945 Py_DECREF(peer);
946 goto fail0;
947 }
948 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000949
Antoine Pitroufb046912010-11-09 20:21:19 +0000950 issuer = _create_tuple_for_X509_NAME(
951 X509_get_issuer_name(certificate));
952 if (issuer == NULL)
953 goto fail0;
954 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000956 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000958 Py_DECREF(issuer);
959
960 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +0200961 if (version == NULL)
962 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +0000963 if (PyDict_SetItemString(retval, "version", version) < 0) {
964 Py_DECREF(version);
965 goto fail0;
966 }
967 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000968
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000969 /* get a memory buffer */
970 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000971
Antoine Pitroufb046912010-11-09 20:21:19 +0000972 (void) BIO_reset(biobuf);
973 serialNumber = X509_get_serialNumber(certificate);
974 /* should not exceed 20 octets, 160 bits, so buf is big enough */
975 i2a_ASN1_INTEGER(biobuf, serialNumber);
976 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
977 if (len < 0) {
978 _setSSLError(NULL, 0, __FILE__, __LINE__);
979 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000980 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000981 sn_obj = PyUnicode_FromStringAndSize(buf, len);
982 if (sn_obj == NULL)
983 goto fail1;
984 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
985 Py_DECREF(sn_obj);
986 goto fail1;
987 }
988 Py_DECREF(sn_obj);
989
990 (void) BIO_reset(biobuf);
991 notBefore = X509_get_notBefore(certificate);
992 ASN1_TIME_print(biobuf, notBefore);
993 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
994 if (len < 0) {
995 _setSSLError(NULL, 0, __FILE__, __LINE__);
996 goto fail1;
997 }
998 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
999 if (pnotBefore == NULL)
1000 goto fail1;
1001 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1002 Py_DECREF(pnotBefore);
1003 goto fail1;
1004 }
1005 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001006
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 (void) BIO_reset(biobuf);
1008 notAfter = X509_get_notAfter(certificate);
1009 ASN1_TIME_print(biobuf, notAfter);
1010 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1011 if (len < 0) {
1012 _setSSLError(NULL, 0, __FILE__, __LINE__);
1013 goto fail1;
1014 }
1015 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1016 if (pnotAfter == NULL)
1017 goto fail1;
1018 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1019 Py_DECREF(pnotAfter);
1020 goto fail1;
1021 }
1022 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001023
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001024 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001025
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001026 peer_alt_names = _get_peer_alt_names(certificate);
1027 if (peer_alt_names == NULL)
1028 goto fail1;
1029 else if (peer_alt_names != Py_None) {
1030 if (PyDict_SetItemString(retval, "subjectAltName",
1031 peer_alt_names) < 0) {
1032 Py_DECREF(peer_alt_names);
1033 goto fail1;
1034 }
1035 Py_DECREF(peer_alt_names);
1036 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001037
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001038 BIO_free(biobuf);
1039 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001040
1041 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001042 if (biobuf != NULL)
1043 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001044 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001045 Py_XDECREF(retval);
1046 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001047}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001048
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001049
1050static PyObject *
1051PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1052
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001053 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001054 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001055 X509 *x=NULL;
1056 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001057
Antoine Pitroufb046912010-11-09 20:21:19 +00001058 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1059 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001060 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001061
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001062 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1063 PyErr_SetString(PySSLErrorObject,
1064 "Can't malloc memory to read file");
1065 goto fail0;
1066 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001067
Victor Stinner3800e1e2010-05-16 21:23:48 +00001068 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069 PyErr_SetString(PySSLErrorObject,
1070 "Can't open file");
1071 goto fail0;
1072 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001073
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001074 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1075 if (x == NULL) {
1076 PyErr_SetString(PySSLErrorObject,
1077 "Error decoding PEM-encoded file");
1078 goto fail0;
1079 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001080
Antoine Pitroufb046912010-11-09 20:21:19 +00001081 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001082 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001083
1084 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001085 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001086 if (cert != NULL) BIO_free(cert);
1087 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001088}
1089
1090
1091static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001092PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001093{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001094 PyObject *retval = NULL;
1095 int len;
1096 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001097 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001098
Antoine Pitrou721738f2012-08-15 23:20:39 +02001099 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001100 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001101
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001102 if (!self->peer_cert)
1103 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001104
Antoine Pitrou721738f2012-08-15 23:20:39 +02001105 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001106 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001107
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001108 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001109
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 bytes_buf = NULL;
1111 len = i2d_X509(self->peer_cert, &bytes_buf);
1112 if (len < 0) {
1113 PySSL_SetError(self, len, __FILE__, __LINE__);
1114 return NULL;
1115 }
1116 /* this is actually an immutable bytes sequence */
1117 retval = PyBytes_FromStringAndSize
1118 ((const char *) bytes_buf, len);
1119 OPENSSL_free(bytes_buf);
1120 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001121
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001122 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001123 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001124 if ((verification & SSL_VERIFY_PEER) == 0)
1125 return PyDict_New();
1126 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001127 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001128 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001129}
1130
1131PyDoc_STRVAR(PySSL_peercert_doc,
1132"peer_certificate([der=False]) -> certificate\n\
1133\n\
1134Returns the certificate for the peer. If no certificate was provided,\n\
1135returns None. If a certificate was provided, but not validated, returns\n\
1136an empty dictionary. Otherwise returns a dict containing information\n\
1137about the peer certificate.\n\
1138\n\
1139If the optional argument is True, returns a DER-encoded copy of the\n\
1140peer certificate, or None if no certificate was provided. This will\n\
1141return the certificate even if it wasn't validated.");
1142
Antoine Pitrou152efa22010-05-16 18:19:27 +00001143static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001144
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001146 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 char *cipher_name;
1148 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001149
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001151 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001152 current = SSL_get_current_cipher(self->ssl);
1153 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001154 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001155
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001156 retval = PyTuple_New(3);
1157 if (retval == NULL)
1158 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001159
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001160 cipher_name = (char *) SSL_CIPHER_get_name(current);
1161 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001162 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001163 PyTuple_SET_ITEM(retval, 0, Py_None);
1164 } else {
1165 v = PyUnicode_FromString(cipher_name);
1166 if (v == NULL)
1167 goto fail0;
1168 PyTuple_SET_ITEM(retval, 0, v);
1169 }
Gregory P. Smithf3489092014-01-17 12:08:49 -08001170 cipher_protocol = (char *) SSL_CIPHER_get_version(current);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001171 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001172 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001173 PyTuple_SET_ITEM(retval, 1, Py_None);
1174 } else {
1175 v = PyUnicode_FromString(cipher_protocol);
1176 if (v == NULL)
1177 goto fail0;
1178 PyTuple_SET_ITEM(retval, 1, v);
1179 }
1180 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1181 if (v == NULL)
1182 goto fail0;
1183 PyTuple_SET_ITEM(retval, 2, v);
1184 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001185
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001186 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001187 Py_DECREF(retval);
1188 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001189}
1190
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001191#ifdef OPENSSL_NPN_NEGOTIATED
1192static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1193 const unsigned char *out;
1194 unsigned int outlen;
1195
Victor Stinner4569cd52013-06-23 14:58:43 +02001196 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001197 &out, &outlen);
1198
1199 if (out == NULL)
1200 Py_RETURN_NONE;
1201 return PyUnicode_FromStringAndSize((char *) out, outlen);
1202}
1203#endif
1204
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001205static PyObject *PySSL_compression(PySSLSocket *self) {
1206#ifdef OPENSSL_NO_COMP
1207 Py_RETURN_NONE;
1208#else
1209 const COMP_METHOD *comp_method;
1210 const char *short_name;
1211
1212 if (self->ssl == NULL)
1213 Py_RETURN_NONE;
1214 comp_method = SSL_get_current_compression(self->ssl);
1215 if (comp_method == NULL || comp_method->type == NID_undef)
1216 Py_RETURN_NONE;
1217 short_name = OBJ_nid2sn(comp_method->type);
1218 if (short_name == NULL)
1219 Py_RETURN_NONE;
1220 return PyUnicode_DecodeFSDefault(short_name);
1221#endif
1222}
1223
Antoine Pitrou152efa22010-05-16 18:19:27 +00001224static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001225{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001226 if (self->peer_cert) /* Possible not to have one? */
1227 X509_free (self->peer_cert);
1228 if (self->ssl)
1229 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001230 Py_XDECREF(self->Socket);
1231 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001232}
1233
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001234/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001235 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001236 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001237 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001238
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001239static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001240check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001241{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001242 fd_set fds;
1243 struct timeval tv;
1244 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001245
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001246 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1247 if (s->sock_timeout < 0.0)
1248 return SOCKET_IS_BLOCKING;
1249 else if (s->sock_timeout == 0.0)
1250 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001251
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001252 /* Guard against closed socket */
1253 if (s->sock_fd < 0)
1254 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001255
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001256 /* Prefer poll, if available, since you can poll() any fd
1257 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001258#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001259 {
1260 struct pollfd pollfd;
1261 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 pollfd.fd = s->sock_fd;
1264 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001265
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001266 /* s->sock_timeout is in seconds, timeout in ms */
1267 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1268 PySSL_BEGIN_ALLOW_THREADS
1269 rc = poll(&pollfd, 1, timeout);
1270 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001271
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001272 goto normal_return;
1273 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001274#endif
1275
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001277 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001279
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 /* Construct the arguments to select */
1281 tv.tv_sec = (int)s->sock_timeout;
1282 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1283 FD_ZERO(&fds);
1284 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001285
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001286 /* See if the socket is ready */
1287 PySSL_BEGIN_ALLOW_THREADS
1288 if (writing)
1289 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1290 else
1291 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1292 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001293
Bill Janssen6e027db2007-11-15 22:23:56 +00001294#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001295normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001296#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001297 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1298 (when we are able to write or when there's something to read) */
1299 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001300}
1301
Antoine Pitrou152efa22010-05-16 18:19:27 +00001302static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001303{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001304 Py_buffer buf;
1305 int len;
1306 int sockstate;
1307 int err;
1308 int nonblocking;
1309 PySocketSockObject *sock
1310 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001311
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001312 if (((PyObject*)sock) == Py_None) {
1313 _setSSLError("Underlying socket connection gone",
1314 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1315 return NULL;
1316 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001317 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001318
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001319 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1320 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001321 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001322 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001323
Victor Stinner6efa9652013-06-25 00:42:31 +02001324 if (buf.len > INT_MAX) {
1325 PyErr_Format(PyExc_OverflowError,
1326 "string longer than %d bytes", INT_MAX);
1327 goto error;
1328 }
1329
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 /* just in case the blocking state of the socket has been changed */
1331 nonblocking = (sock->sock_timeout >= 0.0);
1332 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1333 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1334
1335 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1336 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001337 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 "The write operation timed out");
1339 goto error;
1340 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1341 PyErr_SetString(PySSLErrorObject,
1342 "Underlying socket has been closed.");
1343 goto error;
1344 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1345 PyErr_SetString(PySSLErrorObject,
1346 "Underlying socket too large for select().");
1347 goto error;
1348 }
1349 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001350 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001351 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001352 err = SSL_get_error(self->ssl, len);
1353 PySSL_END_ALLOW_THREADS
1354 if (PyErr_CheckSignals()) {
1355 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001356 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001357 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001358 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001360 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 } else {
1362 sockstate = SOCKET_OPERATION_OK;
1363 }
1364 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001365 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 "The write operation timed out");
1367 goto error;
1368 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1369 PyErr_SetString(PySSLErrorObject,
1370 "Underlying socket has been closed.");
1371 goto error;
1372 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1373 break;
1374 }
1375 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001376
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001377 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 PyBuffer_Release(&buf);
1379 if (len > 0)
1380 return PyLong_FromLong(len);
1381 else
1382 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001383
1384error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001385 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001386 PyBuffer_Release(&buf);
1387 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001388}
1389
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001390PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001391"write(s) -> len\n\
1392\n\
1393Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001394of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001395
Antoine Pitrou152efa22010-05-16 18:19:27 +00001396static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001397{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001398 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001399
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001400 PySSL_BEGIN_ALLOW_THREADS
1401 count = SSL_pending(self->ssl);
1402 PySSL_END_ALLOW_THREADS
1403 if (count < 0)
1404 return PySSL_SetError(self, count, __FILE__, __LINE__);
1405 else
1406 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001407}
1408
1409PyDoc_STRVAR(PySSL_SSLpending_doc,
1410"pending() -> count\n\
1411\n\
1412Returns the number of already decrypted bytes available for read,\n\
1413pending on the connection.\n");
1414
Antoine Pitrou152efa22010-05-16 18:19:27 +00001415static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001416{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001417 PyObject *dest = NULL;
1418 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001419 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001420 int len, count;
1421 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001422 int sockstate;
1423 int err;
1424 int nonblocking;
1425 PySocketSockObject *sock
1426 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001427
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001428 if (((PyObject*)sock) == Py_None) {
1429 _setSSLError("Underlying socket connection gone",
1430 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1431 return NULL;
1432 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001433 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001434
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001435 buf.obj = NULL;
1436 buf.buf = NULL;
1437 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001438 goto error;
1439
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001440 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1441 dest = PyBytes_FromStringAndSize(NULL, len);
1442 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001443 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001444 mem = PyBytes_AS_STRING(dest);
1445 }
1446 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001447 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001448 mem = buf.buf;
1449 if (len <= 0 || len > buf.len) {
1450 len = (int) buf.len;
1451 if (buf.len != len) {
1452 PyErr_SetString(PyExc_OverflowError,
1453 "maximum length can't fit in a C 'int'");
1454 goto error;
1455 }
1456 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001457 }
1458
1459 /* just in case the blocking state of the socket has been changed */
1460 nonblocking = (sock->sock_timeout >= 0.0);
1461 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1462 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1463
1464 /* first check if there are bytes ready to be read */
1465 PySSL_BEGIN_ALLOW_THREADS
1466 count = SSL_pending(self->ssl);
1467 PySSL_END_ALLOW_THREADS
1468
1469 if (!count) {
1470 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1471 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001472 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001473 "The read operation timed out");
1474 goto error;
1475 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1476 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001477 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001478 goto error;
1479 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1480 count = 0;
1481 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001482 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001483 }
1484 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001485 PySSL_BEGIN_ALLOW_THREADS
1486 count = SSL_read(self->ssl, mem, len);
1487 err = SSL_get_error(self->ssl, count);
1488 PySSL_END_ALLOW_THREADS
1489 if (PyErr_CheckSignals())
1490 goto error;
1491 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001492 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001493 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001494 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001495 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1496 (SSL_get_shutdown(self->ssl) ==
1497 SSL_RECEIVED_SHUTDOWN))
1498 {
1499 count = 0;
1500 goto done;
1501 } else {
1502 sockstate = SOCKET_OPERATION_OK;
1503 }
1504 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001505 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001506 "The read operation timed out");
1507 goto error;
1508 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1509 break;
1510 }
1511 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1512 if (count <= 0) {
1513 PySSL_SetError(self, count, __FILE__, __LINE__);
1514 goto error;
1515 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001516
1517done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001518 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001519 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001520 _PyBytes_Resize(&dest, count);
1521 return dest;
1522 }
1523 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 PyBuffer_Release(&buf);
1525 return PyLong_FromLong(count);
1526 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001527
1528error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001529 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001530 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001531 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001532 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001533 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001534 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001535}
1536
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001537PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001538"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001539\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001540Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001541
Antoine Pitrou152efa22010-05-16 18:19:27 +00001542static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001543{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001544 int err, ssl_err, sockstate, nonblocking;
1545 int zeros = 0;
1546 PySocketSockObject *sock
1547 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001548
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001549 /* Guard against closed socket */
1550 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1551 _setSSLError("Underlying socket connection gone",
1552 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1553 return NULL;
1554 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001555 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001556
1557 /* Just in case the blocking state of the socket has been changed */
1558 nonblocking = (sock->sock_timeout >= 0.0);
1559 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1560 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1561
1562 while (1) {
1563 PySSL_BEGIN_ALLOW_THREADS
1564 /* Disable read-ahead so that unwrap can work correctly.
1565 * Otherwise OpenSSL might read in too much data,
1566 * eating clear text data that happens to be
1567 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001568 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001569 * function is used and the shutdown_seen_zero != 0
1570 * condition is met.
1571 */
1572 if (self->shutdown_seen_zero)
1573 SSL_set_read_ahead(self->ssl, 0);
1574 err = SSL_shutdown(self->ssl);
1575 PySSL_END_ALLOW_THREADS
1576 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1577 if (err > 0)
1578 break;
1579 if (err == 0) {
1580 /* Don't loop endlessly; instead preserve legacy
1581 behaviour of trying SSL_shutdown() only twice.
1582 This looks necessary for OpenSSL < 0.9.8m */
1583 if (++zeros > 1)
1584 break;
1585 /* Shutdown was sent, now try receiving */
1586 self->shutdown_seen_zero = 1;
1587 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001588 }
1589
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001590 /* Possibly retry shutdown until timeout or failure */
1591 ssl_err = SSL_get_error(self->ssl, err);
1592 if (ssl_err == SSL_ERROR_WANT_READ)
1593 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1594 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1595 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1596 else
1597 break;
1598 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1599 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001600 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001601 "The read operation timed out");
1602 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001603 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001604 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001605 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001606 }
1607 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1608 PyErr_SetString(PySSLErrorObject,
1609 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001610 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001611 }
1612 else if (sockstate != SOCKET_OPERATION_OK)
1613 /* Retain the SSL error code */
1614 break;
1615 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001616
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001617 if (err < 0) {
1618 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001619 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001620 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001621 else
1622 /* It's already INCREF'ed */
1623 return (PyObject *) sock;
1624
1625error:
1626 Py_DECREF(sock);
1627 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001628}
1629
1630PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1631"shutdown(s) -> socket\n\
1632\n\
1633Does the SSL shutdown handshake with the remote end, and returns\n\
1634the underlying socket object.");
1635
Antoine Pitroud6494802011-07-21 01:11:30 +02001636#if HAVE_OPENSSL_FINISHED
1637static PyObject *
1638PySSL_tls_unique_cb(PySSLSocket *self)
1639{
1640 PyObject *retval = NULL;
1641 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001642 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001643
1644 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1645 /* if session is resumed XOR we are the client */
1646 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1647 }
1648 else {
1649 /* if a new session XOR we are the server */
1650 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1651 }
1652
1653 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001654 if (len == 0)
1655 Py_RETURN_NONE;
1656
1657 retval = PyBytes_FromStringAndSize(buf, len);
1658
1659 return retval;
1660}
1661
1662PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1663"tls_unique_cb() -> bytes\n\
1664\n\
1665Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1666\n\
1667If the TLS handshake is not yet complete, None is returned");
1668
1669#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001670
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001671static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001672 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1673 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1674 PySSL_SSLwrite_doc},
1675 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1676 PySSL_SSLread_doc},
1677 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1678 PySSL_SSLpending_doc},
1679 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1680 PySSL_peercert_doc},
1681 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001682#ifdef OPENSSL_NPN_NEGOTIATED
1683 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1684#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001685 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001686 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1687 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001688#if HAVE_OPENSSL_FINISHED
1689 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1690 PySSL_tls_unique_cb_doc},
1691#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001692 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001693};
1694
Antoine Pitrou152efa22010-05-16 18:19:27 +00001695static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001696 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001697 "_ssl._SSLSocket", /*tp_name*/
1698 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001699 0, /*tp_itemsize*/
1700 /* methods */
1701 (destructor)PySSL_dealloc, /*tp_dealloc*/
1702 0, /*tp_print*/
1703 0, /*tp_getattr*/
1704 0, /*tp_setattr*/
1705 0, /*tp_reserved*/
1706 0, /*tp_repr*/
1707 0, /*tp_as_number*/
1708 0, /*tp_as_sequence*/
1709 0, /*tp_as_mapping*/
1710 0, /*tp_hash*/
1711 0, /*tp_call*/
1712 0, /*tp_str*/
1713 0, /*tp_getattro*/
1714 0, /*tp_setattro*/
1715 0, /*tp_as_buffer*/
1716 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1717 0, /*tp_doc*/
1718 0, /*tp_traverse*/
1719 0, /*tp_clear*/
1720 0, /*tp_richcompare*/
1721 0, /*tp_weaklistoffset*/
1722 0, /*tp_iter*/
1723 0, /*tp_iternext*/
1724 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001725};
1726
Antoine Pitrou152efa22010-05-16 18:19:27 +00001727
1728/*
1729 * _SSLContext objects
1730 */
1731
1732static PyObject *
1733context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1734{
1735 char *kwlist[] = {"protocol", NULL};
1736 PySSLContext *self;
1737 int proto_version = PY_SSL_VERSION_SSL23;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01001738 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00001739 SSL_CTX *ctx = NULL;
1740
1741 if (!PyArg_ParseTupleAndKeywords(
1742 args, kwds, "i:_SSLContext", kwlist,
1743 &proto_version))
1744 return NULL;
1745
1746 PySSL_BEGIN_ALLOW_THREADS
1747 if (proto_version == PY_SSL_VERSION_TLS1)
1748 ctx = SSL_CTX_new(TLSv1_method());
1749 else if (proto_version == PY_SSL_VERSION_SSL3)
1750 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001751#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001752 else if (proto_version == PY_SSL_VERSION_SSL2)
1753 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001754#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001755 else if (proto_version == PY_SSL_VERSION_SSL23)
1756 ctx = SSL_CTX_new(SSLv23_method());
1757 else
1758 proto_version = -1;
1759 PySSL_END_ALLOW_THREADS
1760
1761 if (proto_version == -1) {
1762 PyErr_SetString(PyExc_ValueError,
1763 "invalid protocol version");
1764 return NULL;
1765 }
1766 if (ctx == NULL) {
1767 PyErr_SetString(PySSLErrorObject,
1768 "failed to allocate SSL context");
1769 return NULL;
1770 }
1771
1772 assert(type != NULL && type->tp_alloc != NULL);
1773 self = (PySSLContext *) type->tp_alloc(type, 0);
1774 if (self == NULL) {
1775 SSL_CTX_free(ctx);
1776 return NULL;
1777 }
1778 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001779#ifdef OPENSSL_NPN_NEGOTIATED
1780 self->npn_protocols = NULL;
1781#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001782 /* Defaults */
1783 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01001784 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
1785 if (proto_version != PY_SSL_VERSION_SSL2)
1786 options |= SSL_OP_NO_SSLv2;
1787 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001788
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001789#define SID_CTX "Python"
1790 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1791 sizeof(SID_CTX));
1792#undef SID_CTX
1793
Antoine Pitrou152efa22010-05-16 18:19:27 +00001794 return (PyObject *)self;
1795}
1796
1797static void
1798context_dealloc(PySSLContext *self)
1799{
1800 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001801#ifdef OPENSSL_NPN_NEGOTIATED
1802 PyMem_Free(self->npn_protocols);
1803#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001804 Py_TYPE(self)->tp_free(self);
1805}
1806
1807static PyObject *
1808set_ciphers(PySSLContext *self, PyObject *args)
1809{
1810 int ret;
1811 const char *cipherlist;
1812
1813 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1814 return NULL;
1815 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1816 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001817 /* Clearing the error queue is necessary on some OpenSSL versions,
1818 otherwise the error will be reported again when another SSL call
1819 is done. */
1820 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001821 PyErr_SetString(PySSLErrorObject,
1822 "No cipher can be selected.");
1823 return NULL;
1824 }
1825 Py_RETURN_NONE;
1826}
1827
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001828#ifdef OPENSSL_NPN_NEGOTIATED
1829/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1830static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001831_advertiseNPN_cb(SSL *s,
1832 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001833 void *args)
1834{
1835 PySSLContext *ssl_ctx = (PySSLContext *) args;
1836
1837 if (ssl_ctx->npn_protocols == NULL) {
1838 *data = (unsigned char *) "";
1839 *len = 0;
1840 } else {
1841 *data = (unsigned char *) ssl_ctx->npn_protocols;
1842 *len = ssl_ctx->npn_protocols_len;
1843 }
1844
1845 return SSL_TLSEXT_ERR_OK;
1846}
1847/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1848static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001849_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001850 unsigned char **out, unsigned char *outlen,
1851 const unsigned char *server, unsigned int server_len,
1852 void *args)
1853{
1854 PySSLContext *ssl_ctx = (PySSLContext *) args;
1855
1856 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1857 int client_len;
1858
1859 if (client == NULL) {
1860 client = (unsigned char *) "";
1861 client_len = 0;
1862 } else {
1863 client_len = ssl_ctx->npn_protocols_len;
1864 }
1865
1866 SSL_select_next_proto(out, outlen,
1867 server, server_len,
1868 client, client_len);
1869
1870 return SSL_TLSEXT_ERR_OK;
1871}
1872#endif
1873
1874static PyObject *
1875_set_npn_protocols(PySSLContext *self, PyObject *args)
1876{
1877#ifdef OPENSSL_NPN_NEGOTIATED
1878 Py_buffer protos;
1879
1880 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1881 return NULL;
1882
Christian Heimes5cb31c92012-09-20 12:42:54 +02001883 if (self->npn_protocols != NULL) {
1884 PyMem_Free(self->npn_protocols);
1885 }
1886
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001887 self->npn_protocols = PyMem_Malloc(protos.len);
1888 if (self->npn_protocols == NULL) {
1889 PyBuffer_Release(&protos);
1890 return PyErr_NoMemory();
1891 }
1892 memcpy(self->npn_protocols, protos.buf, protos.len);
1893 self->npn_protocols_len = (int) protos.len;
1894
1895 /* set both server and client callbacks, because the context can
1896 * be used to create both types of sockets */
1897 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
1898 _advertiseNPN_cb,
1899 self);
1900 SSL_CTX_set_next_proto_select_cb(self->ctx,
1901 _selectNPN_cb,
1902 self);
1903
1904 PyBuffer_Release(&protos);
1905 Py_RETURN_NONE;
1906#else
1907 PyErr_SetString(PyExc_NotImplementedError,
1908 "The NPN extension requires OpenSSL 1.0.1 or later.");
1909 return NULL;
1910#endif
1911}
1912
Antoine Pitrou152efa22010-05-16 18:19:27 +00001913static PyObject *
1914get_verify_mode(PySSLContext *self, void *c)
1915{
1916 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1917 case SSL_VERIFY_NONE:
1918 return PyLong_FromLong(PY_SSL_CERT_NONE);
1919 case SSL_VERIFY_PEER:
1920 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1921 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1922 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1923 }
1924 PyErr_SetString(PySSLErrorObject,
1925 "invalid return value from SSL_CTX_get_verify_mode");
1926 return NULL;
1927}
1928
1929static int
1930set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1931{
1932 int n, mode;
1933 if (!PyArg_Parse(arg, "i", &n))
1934 return -1;
1935 if (n == PY_SSL_CERT_NONE)
1936 mode = SSL_VERIFY_NONE;
1937 else if (n == PY_SSL_CERT_OPTIONAL)
1938 mode = SSL_VERIFY_PEER;
1939 else if (n == PY_SSL_CERT_REQUIRED)
1940 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1941 else {
1942 PyErr_SetString(PyExc_ValueError,
1943 "invalid value for verify_mode");
1944 return -1;
1945 }
1946 SSL_CTX_set_verify(self->ctx, mode, NULL);
1947 return 0;
1948}
1949
1950static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001951get_options(PySSLContext *self, void *c)
1952{
1953 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1954}
1955
1956static int
1957set_options(PySSLContext *self, PyObject *arg, void *c)
1958{
1959 long new_opts, opts, set, clear;
1960 if (!PyArg_Parse(arg, "l", &new_opts))
1961 return -1;
1962 opts = SSL_CTX_get_options(self->ctx);
1963 clear = opts & ~new_opts;
1964 set = ~opts & new_opts;
1965 if (clear) {
1966#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1967 SSL_CTX_clear_options(self->ctx, clear);
1968#else
1969 PyErr_SetString(PyExc_ValueError,
1970 "can't clear options before OpenSSL 0.9.8m");
1971 return -1;
1972#endif
1973 }
1974 if (set)
1975 SSL_CTX_set_options(self->ctx, set);
1976 return 0;
1977}
1978
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001979typedef struct {
1980 PyThreadState *thread_state;
1981 PyObject *callable;
1982 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02001983 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001984 int error;
1985} _PySSLPasswordInfo;
1986
1987static int
1988_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1989 const char *bad_type_error)
1990{
1991 /* Set the password and size fields of a _PySSLPasswordInfo struct
1992 from a unicode, bytes, or byte array object.
1993 The password field will be dynamically allocated and must be freed
1994 by the caller */
1995 PyObject *password_bytes = NULL;
1996 const char *data = NULL;
1997 Py_ssize_t size;
1998
1999 if (PyUnicode_Check(password)) {
2000 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2001 if (!password_bytes) {
2002 goto error;
2003 }
2004 data = PyBytes_AS_STRING(password_bytes);
2005 size = PyBytes_GET_SIZE(password_bytes);
2006 } else if (PyBytes_Check(password)) {
2007 data = PyBytes_AS_STRING(password);
2008 size = PyBytes_GET_SIZE(password);
2009 } else if (PyByteArray_Check(password)) {
2010 data = PyByteArray_AS_STRING(password);
2011 size = PyByteArray_GET_SIZE(password);
2012 } else {
2013 PyErr_SetString(PyExc_TypeError, bad_type_error);
2014 goto error;
2015 }
2016
Victor Stinner9ee02032013-06-23 15:08:23 +02002017 if (size > (Py_ssize_t)INT_MAX) {
2018 PyErr_Format(PyExc_ValueError,
2019 "password cannot be longer than %d bytes", INT_MAX);
2020 goto error;
2021 }
2022
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002023 free(pw_info->password);
2024 pw_info->password = malloc(size);
2025 if (!pw_info->password) {
2026 PyErr_SetString(PyExc_MemoryError,
2027 "unable to allocate password buffer");
2028 goto error;
2029 }
2030 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002031 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002032
2033 Py_XDECREF(password_bytes);
2034 return 1;
2035
2036error:
2037 Py_XDECREF(password_bytes);
2038 return 0;
2039}
2040
2041static int
2042_password_callback(char *buf, int size, int rwflag, void *userdata)
2043{
2044 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2045 PyObject *fn_ret = NULL;
2046
2047 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2048
2049 if (pw_info->callable) {
2050 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2051 if (!fn_ret) {
2052 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2053 core python API, so we could use it to add a frame here */
2054 goto error;
2055 }
2056
2057 if (!_pwinfo_set(pw_info, fn_ret,
2058 "password callback must return a string")) {
2059 goto error;
2060 }
2061 Py_CLEAR(fn_ret);
2062 }
2063
2064 if (pw_info->size > size) {
2065 PyErr_Format(PyExc_ValueError,
2066 "password cannot be longer than %d bytes", size);
2067 goto error;
2068 }
2069
2070 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2071 memcpy(buf, pw_info->password, pw_info->size);
2072 return pw_info->size;
2073
2074error:
2075 Py_XDECREF(fn_ret);
2076 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2077 pw_info->error = 1;
2078 return -1;
2079}
2080
Antoine Pitroub5218772010-05-21 09:56:06 +00002081static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002082load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2083{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002084 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2085 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002086 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002087 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2088 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2089 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002090 int r;
2091
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002092 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002093 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002094 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002095 "O|OO:load_cert_chain", kwlist,
2096 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002097 return NULL;
2098 if (keyfile == Py_None)
2099 keyfile = NULL;
2100 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2101 PyErr_SetString(PyExc_TypeError,
2102 "certfile should be a valid filesystem path");
2103 return NULL;
2104 }
2105 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2106 PyErr_SetString(PyExc_TypeError,
2107 "keyfile should be a valid filesystem path");
2108 goto error;
2109 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002110 if (password && password != Py_None) {
2111 if (PyCallable_Check(password)) {
2112 pw_info.callable = password;
2113 } else if (!_pwinfo_set(&pw_info, password,
2114 "password should be a string or callable")) {
2115 goto error;
2116 }
2117 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2118 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2119 }
2120 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002121 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2122 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002123 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002124 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002125 if (pw_info.error) {
2126 ERR_clear_error();
2127 /* the password callback has already set the error information */
2128 }
2129 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002130 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002131 PyErr_SetFromErrno(PyExc_IOError);
2132 }
2133 else {
2134 _setSSLError(NULL, 0, __FILE__, __LINE__);
2135 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002136 goto error;
2137 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002138 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002139 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002140 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2141 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002142 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2143 Py_CLEAR(keyfile_bytes);
2144 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002145 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002146 if (pw_info.error) {
2147 ERR_clear_error();
2148 /* the password callback has already set the error information */
2149 }
2150 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002151 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002152 PyErr_SetFromErrno(PyExc_IOError);
2153 }
2154 else {
2155 _setSSLError(NULL, 0, __FILE__, __LINE__);
2156 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002157 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002158 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002159 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002160 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002161 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002162 if (r != 1) {
2163 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002164 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002165 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002166 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2167 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2168 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002169 Py_RETURN_NONE;
2170
2171error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002172 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2173 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2174 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002175 Py_XDECREF(keyfile_bytes);
2176 Py_XDECREF(certfile_bytes);
2177 return NULL;
2178}
2179
2180static PyObject *
2181load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2182{
2183 char *kwlist[] = {"cafile", "capath", NULL};
2184 PyObject *cafile = NULL, *capath = NULL;
2185 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2186 const char *cafile_buf = NULL, *capath_buf = NULL;
2187 int r;
2188
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002189 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002190 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2191 "|OO:load_verify_locations", kwlist,
2192 &cafile, &capath))
2193 return NULL;
2194 if (cafile == Py_None)
2195 cafile = NULL;
2196 if (capath == Py_None)
2197 capath = NULL;
2198 if (cafile == NULL && capath == NULL) {
2199 PyErr_SetString(PyExc_TypeError,
2200 "cafile and capath cannot be both omitted");
2201 return NULL;
2202 }
2203 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2204 PyErr_SetString(PyExc_TypeError,
2205 "cafile should be a valid filesystem path");
2206 return NULL;
2207 }
2208 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002209 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002210 PyErr_SetString(PyExc_TypeError,
2211 "capath should be a valid filesystem path");
2212 return NULL;
2213 }
2214 if (cafile)
2215 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2216 if (capath)
2217 capath_buf = PyBytes_AS_STRING(capath_bytes);
2218 PySSL_BEGIN_ALLOW_THREADS
2219 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2220 PySSL_END_ALLOW_THREADS
2221 Py_XDECREF(cafile_bytes);
2222 Py_XDECREF(capath_bytes);
2223 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002224 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002225 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002226 PyErr_SetFromErrno(PyExc_IOError);
2227 }
2228 else {
2229 _setSSLError(NULL, 0, __FILE__, __LINE__);
2230 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002231 return NULL;
2232 }
2233 Py_RETURN_NONE;
2234}
2235
2236static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002237load_dh_params(PySSLContext *self, PyObject *filepath)
2238{
2239 FILE *f;
2240 DH *dh;
2241
2242 f = _Py_fopen(filepath, "rb");
2243 if (f == NULL) {
2244 if (!PyErr_Occurred())
2245 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2246 return NULL;
2247 }
2248 errno = 0;
2249 PySSL_BEGIN_ALLOW_THREADS
2250 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002251 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002252 PySSL_END_ALLOW_THREADS
2253 if (dh == NULL) {
2254 if (errno != 0) {
2255 ERR_clear_error();
2256 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2257 }
2258 else {
2259 _setSSLError(NULL, 0, __FILE__, __LINE__);
2260 }
2261 return NULL;
2262 }
2263 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2264 _setSSLError(NULL, 0, __FILE__, __LINE__);
2265 DH_free(dh);
2266 Py_RETURN_NONE;
2267}
2268
2269static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002270context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2271{
Antoine Pitroud5323212010-10-22 18:19:07 +00002272 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002273 PySocketSockObject *sock;
2274 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002275 char *hostname = NULL;
2276 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002277
Antoine Pitroud5323212010-10-22 18:19:07 +00002278 /* server_hostname is either None (or absent), or to be encoded
2279 using the idna encoding. */
2280 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002281 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002282 &sock, &server_side,
2283 Py_TYPE(Py_None), &hostname_obj)) {
2284 PyErr_Clear();
2285 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2286 PySocketModule.Sock_Type,
2287 &sock, &server_side,
2288 "idna", &hostname))
2289 return NULL;
2290#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
2291 PyMem_Free(hostname);
2292 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2293 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002294 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002295#endif
2296 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002297
Antoine Pitroud5323212010-10-22 18:19:07 +00002298 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
2299 hostname);
2300 if (hostname != NULL)
2301 PyMem_Free(hostname);
2302 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002303}
2304
Antoine Pitroub0182c82010-10-12 20:09:02 +00002305static PyObject *
2306session_stats(PySSLContext *self, PyObject *unused)
2307{
2308 int r;
2309 PyObject *value, *stats = PyDict_New();
2310 if (!stats)
2311 return NULL;
2312
2313#define ADD_STATS(SSL_NAME, KEY_NAME) \
2314 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2315 if (value == NULL) \
2316 goto error; \
2317 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2318 Py_DECREF(value); \
2319 if (r < 0) \
2320 goto error;
2321
2322 ADD_STATS(number, "number");
2323 ADD_STATS(connect, "connect");
2324 ADD_STATS(connect_good, "connect_good");
2325 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2326 ADD_STATS(accept, "accept");
2327 ADD_STATS(accept_good, "accept_good");
2328 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2329 ADD_STATS(accept, "accept");
2330 ADD_STATS(hits, "hits");
2331 ADD_STATS(misses, "misses");
2332 ADD_STATS(timeouts, "timeouts");
2333 ADD_STATS(cache_full, "cache_full");
2334
2335#undef ADD_STATS
2336
2337 return stats;
2338
2339error:
2340 Py_DECREF(stats);
2341 return NULL;
2342}
2343
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002344static PyObject *
2345set_default_verify_paths(PySSLContext *self, PyObject *unused)
2346{
2347 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2348 _setSSLError(NULL, 0, __FILE__, __LINE__);
2349 return NULL;
2350 }
2351 Py_RETURN_NONE;
2352}
2353
Antoine Pitrou501da612011-12-21 09:27:41 +01002354#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002355static PyObject *
2356set_ecdh_curve(PySSLContext *self, PyObject *name)
2357{
2358 PyObject *name_bytes;
2359 int nid;
2360 EC_KEY *key;
2361
2362 if (!PyUnicode_FSConverter(name, &name_bytes))
2363 return NULL;
2364 assert(PyBytes_Check(name_bytes));
2365 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2366 Py_DECREF(name_bytes);
2367 if (nid == 0) {
2368 PyErr_Format(PyExc_ValueError,
2369 "unknown elliptic curve name %R", name);
2370 return NULL;
2371 }
2372 key = EC_KEY_new_by_curve_name(nid);
2373 if (key == NULL) {
2374 _setSSLError(NULL, 0, __FILE__, __LINE__);
2375 return NULL;
2376 }
2377 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2378 EC_KEY_free(key);
2379 Py_RETURN_NONE;
2380}
Antoine Pitrou501da612011-12-21 09:27:41 +01002381#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002382
Antoine Pitrou152efa22010-05-16 18:19:27 +00002383static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002384 {"options", (getter) get_options,
2385 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002386 {"verify_mode", (getter) get_verify_mode,
2387 (setter) set_verify_mode, NULL},
2388 {NULL}, /* sentinel */
2389};
2390
2391static struct PyMethodDef context_methods[] = {
2392 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2393 METH_VARARGS | METH_KEYWORDS, NULL},
2394 {"set_ciphers", (PyCFunction) set_ciphers,
2395 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002396 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2397 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002398 {"load_cert_chain", (PyCFunction) load_cert_chain,
2399 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002400 {"load_dh_params", (PyCFunction) load_dh_params,
2401 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002402 {"load_verify_locations", (PyCFunction) load_verify_locations,
2403 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002404 {"session_stats", (PyCFunction) session_stats,
2405 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002406 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2407 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002408#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002409 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2410 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002411#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002412 {NULL, NULL} /* sentinel */
2413};
2414
2415static PyTypeObject PySSLContext_Type = {
2416 PyVarObject_HEAD_INIT(NULL, 0)
2417 "_ssl._SSLContext", /*tp_name*/
2418 sizeof(PySSLContext), /*tp_basicsize*/
2419 0, /*tp_itemsize*/
2420 (destructor)context_dealloc, /*tp_dealloc*/
2421 0, /*tp_print*/
2422 0, /*tp_getattr*/
2423 0, /*tp_setattr*/
2424 0, /*tp_reserved*/
2425 0, /*tp_repr*/
2426 0, /*tp_as_number*/
2427 0, /*tp_as_sequence*/
2428 0, /*tp_as_mapping*/
2429 0, /*tp_hash*/
2430 0, /*tp_call*/
2431 0, /*tp_str*/
2432 0, /*tp_getattro*/
2433 0, /*tp_setattro*/
2434 0, /*tp_as_buffer*/
2435 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2436 0, /*tp_doc*/
2437 0, /*tp_traverse*/
2438 0, /*tp_clear*/
2439 0, /*tp_richcompare*/
2440 0, /*tp_weaklistoffset*/
2441 0, /*tp_iter*/
2442 0, /*tp_iternext*/
2443 context_methods, /*tp_methods*/
2444 0, /*tp_members*/
2445 context_getsetlist, /*tp_getset*/
2446 0, /*tp_base*/
2447 0, /*tp_dict*/
2448 0, /*tp_descr_get*/
2449 0, /*tp_descr_set*/
2450 0, /*tp_dictoffset*/
2451 0, /*tp_init*/
2452 0, /*tp_alloc*/
2453 context_new, /*tp_new*/
2454};
2455
2456
2457
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002458#ifdef HAVE_OPENSSL_RAND
2459
2460/* helper routines for seeding the SSL PRNG */
2461static PyObject *
2462PySSL_RAND_add(PyObject *self, PyObject *args)
2463{
2464 char *buf;
2465 int len;
2466 double entropy;
2467
2468 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002469 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002470 RAND_add(buf, len, entropy);
2471 Py_INCREF(Py_None);
2472 return Py_None;
2473}
2474
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002475PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002476"RAND_add(string, entropy)\n\
2477\n\
2478Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002479bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002480
2481static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002482PySSL_RAND(int len, int pseudo)
2483{
2484 int ok;
2485 PyObject *bytes;
2486 unsigned long err;
2487 const char *errstr;
2488 PyObject *v;
2489
Victor Stinner1e81a392013-12-19 16:47:04 +01002490 if (len < 0) {
2491 PyErr_SetString(PyExc_ValueError, "num must be positive");
2492 return NULL;
2493 }
2494
Victor Stinner99c8b162011-05-24 12:05:19 +02002495 bytes = PyBytes_FromStringAndSize(NULL, len);
2496 if (bytes == NULL)
2497 return NULL;
2498 if (pseudo) {
2499 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2500 if (ok == 0 || ok == 1)
2501 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2502 }
2503 else {
2504 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2505 if (ok == 1)
2506 return bytes;
2507 }
2508 Py_DECREF(bytes);
2509
2510 err = ERR_get_error();
2511 errstr = ERR_reason_error_string(err);
2512 v = Py_BuildValue("(ks)", err, errstr);
2513 if (v != NULL) {
2514 PyErr_SetObject(PySSLErrorObject, v);
2515 Py_DECREF(v);
2516 }
2517 return NULL;
2518}
2519
2520static PyObject *
2521PySSL_RAND_bytes(PyObject *self, PyObject *args)
2522{
2523 int len;
2524 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2525 return NULL;
2526 return PySSL_RAND(len, 0);
2527}
2528
2529PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2530"RAND_bytes(n) -> bytes\n\
2531\n\
2532Generate n cryptographically strong pseudo-random bytes.");
2533
2534static PyObject *
2535PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2536{
2537 int len;
2538 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2539 return NULL;
2540 return PySSL_RAND(len, 1);
2541}
2542
2543PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2544"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2545\n\
2546Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2547generated are cryptographically strong.");
2548
2549static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002550PySSL_RAND_status(PyObject *self)
2551{
Christian Heimes217cfd12007-12-02 14:31:20 +00002552 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002553}
2554
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002555PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002556"RAND_status() -> 0 or 1\n\
2557\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002558Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2559It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2560using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002561
2562static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002563PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002564{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002565 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002566 int bytes;
2567
Jesus Ceac8754a12012-09-11 02:00:58 +02002568 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002569 PyUnicode_FSConverter, &path))
2570 return NULL;
2571
2572 bytes = RAND_egd(PyBytes_AsString(path));
2573 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002574 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002575 PyErr_SetString(PySSLErrorObject,
2576 "EGD connection failed or EGD did not return "
2577 "enough data to seed the PRNG");
2578 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002579 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002580 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002581}
2582
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002583PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002584"RAND_egd(path) -> bytes\n\
2585\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002586Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2587Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02002588fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002589
Christian Heimesf77b4b22013-08-21 13:26:05 +02002590#endif /* HAVE_OPENSSL_RAND */
2591
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002592
Bill Janssen40a0f662008-08-12 16:56:25 +00002593
2594
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002595/* List of functions exported by this module. */
2596
2597static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002598 {"_test_decode_cert", PySSL_test_decode_certificate,
2599 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002600#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002601 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2602 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002603 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2604 PySSL_RAND_bytes_doc},
2605 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2606 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002607 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002608 PySSL_RAND_egd_doc},
2609 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2610 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002611#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002612 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002613};
2614
2615
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002616#ifdef WITH_THREAD
2617
2618/* an implementation of OpenSSL threading operations in terms
2619 of the Python C thread library */
2620
2621static PyThread_type_lock *_ssl_locks = NULL;
2622
Christian Heimes4d98ca92013-08-19 17:36:29 +02002623#if OPENSSL_VERSION_NUMBER >= 0x10000000
2624/* use new CRYPTO_THREADID API. */
2625static void
2626_ssl_threadid_callback(CRYPTO_THREADID *id)
2627{
2628 CRYPTO_THREADID_set_numeric(id,
2629 (unsigned long)PyThread_get_thread_ident());
2630}
2631#else
2632/* deprecated CRYPTO_set_id_callback() API. */
2633static unsigned long
2634_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002635 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002636}
Christian Heimes4d98ca92013-08-19 17:36:29 +02002637#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002638
Bill Janssen6e027db2007-11-15 22:23:56 +00002639static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002640 (int mode, int n, const char *file, int line) {
2641 /* this function is needed to perform locking on shared data
2642 structures. (Note that OpenSSL uses a number of global data
2643 structures that will be implicitly shared whenever multiple
2644 threads use OpenSSL.) Multi-threaded applications will
2645 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002646
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002647 locking_function() must be able to handle up to
2648 CRYPTO_num_locks() different mutex locks. It sets the n-th
2649 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002650
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002651 file and line are the file number of the function setting the
2652 lock. They can be useful for debugging.
2653 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002654
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002655 if ((_ssl_locks == NULL) ||
2656 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2657 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002658
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002659 if (mode & CRYPTO_LOCK) {
2660 PyThread_acquire_lock(_ssl_locks[n], 1);
2661 } else {
2662 PyThread_release_lock(_ssl_locks[n]);
2663 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002664}
2665
2666static int _setup_ssl_threads(void) {
2667
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002668 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002669
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002670 if (_ssl_locks == NULL) {
2671 _ssl_locks_count = CRYPTO_num_locks();
2672 _ssl_locks = (PyThread_type_lock *)
2673 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2674 if (_ssl_locks == NULL)
2675 return 0;
2676 memset(_ssl_locks, 0,
2677 sizeof(PyThread_type_lock) * _ssl_locks_count);
2678 for (i = 0; i < _ssl_locks_count; i++) {
2679 _ssl_locks[i] = PyThread_allocate_lock();
2680 if (_ssl_locks[i] == NULL) {
2681 unsigned int j;
2682 for (j = 0; j < i; j++) {
2683 PyThread_free_lock(_ssl_locks[j]);
2684 }
2685 free(_ssl_locks);
2686 return 0;
2687 }
2688 }
2689 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02002690#if OPENSSL_VERSION_NUMBER >= 0x10000000
2691 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
2692#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002693 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02002694#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002695 }
2696 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002697}
2698
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002699#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002700
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002701PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002702"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002703for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002704
Martin v. Löwis1a214512008-06-11 05:26:20 +00002705
2706static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002707 PyModuleDef_HEAD_INIT,
2708 "_ssl",
2709 module_doc,
2710 -1,
2711 PySSL_methods,
2712 NULL,
2713 NULL,
2714 NULL,
2715 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002716};
2717
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002718
2719static void
2720parse_openssl_version(unsigned long libver,
2721 unsigned int *major, unsigned int *minor,
2722 unsigned int *fix, unsigned int *patch,
2723 unsigned int *status)
2724{
2725 *status = libver & 0xF;
2726 libver >>= 4;
2727 *patch = libver & 0xFF;
2728 libver >>= 8;
2729 *fix = libver & 0xFF;
2730 libver >>= 8;
2731 *minor = libver & 0xFF;
2732 libver >>= 8;
2733 *major = libver & 0xFF;
2734}
2735
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002736PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002737PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002738{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002739 PyObject *m, *d, *r;
2740 unsigned long libver;
2741 unsigned int major, minor, fix, patch, status;
2742 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002743 struct py_ssl_error_code *errcode;
2744 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002745
Antoine Pitrou152efa22010-05-16 18:19:27 +00002746 if (PyType_Ready(&PySSLContext_Type) < 0)
2747 return NULL;
2748 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002749 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002750
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002751 m = PyModule_Create(&_sslmodule);
2752 if (m == NULL)
2753 return NULL;
2754 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002755
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002756 /* Load _socket module and its C API */
2757 socket_api = PySocketModule_ImportModuleAndAPI();
2758 if (!socket_api)
2759 return NULL;
2760 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002761
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002762 /* Init OpenSSL */
2763 SSL_load_error_strings();
2764 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002765#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002766 /* note that this will start threading if not already started */
2767 if (!_setup_ssl_threads()) {
2768 return NULL;
2769 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002770#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002771 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002772
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002773 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002774 sslerror_type_slots[0].pfunc = PyExc_OSError;
2775 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002776 if (PySSLErrorObject == NULL)
2777 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002778
Antoine Pitrou41032a62011-10-27 23:56:55 +02002779 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2780 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2781 PySSLErrorObject, NULL);
2782 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2783 "ssl.SSLWantReadError", SSLWantReadError_doc,
2784 PySSLErrorObject, NULL);
2785 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2786 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2787 PySSLErrorObject, NULL);
2788 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2789 "ssl.SSLSyscallError", SSLSyscallError_doc,
2790 PySSLErrorObject, NULL);
2791 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2792 "ssl.SSLEOFError", SSLEOFError_doc,
2793 PySSLErrorObject, NULL);
2794 if (PySSLZeroReturnErrorObject == NULL
2795 || PySSLWantReadErrorObject == NULL
2796 || PySSLWantWriteErrorObject == NULL
2797 || PySSLSyscallErrorObject == NULL
2798 || PySSLEOFErrorObject == NULL)
2799 return NULL;
2800 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2801 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2802 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2803 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2804 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2805 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002806 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002807 if (PyDict_SetItemString(d, "_SSLContext",
2808 (PyObject *)&PySSLContext_Type) != 0)
2809 return NULL;
2810 if (PyDict_SetItemString(d, "_SSLSocket",
2811 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002812 return NULL;
2813 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2814 PY_SSL_ERROR_ZERO_RETURN);
2815 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2816 PY_SSL_ERROR_WANT_READ);
2817 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2818 PY_SSL_ERROR_WANT_WRITE);
2819 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2820 PY_SSL_ERROR_WANT_X509_LOOKUP);
2821 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2822 PY_SSL_ERROR_SYSCALL);
2823 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2824 PY_SSL_ERROR_SSL);
2825 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2826 PY_SSL_ERROR_WANT_CONNECT);
2827 /* non ssl.h errorcodes */
2828 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2829 PY_SSL_ERROR_EOF);
2830 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2831 PY_SSL_ERROR_INVALID_ERROR_CODE);
2832 /* cert requirements */
2833 PyModule_AddIntConstant(m, "CERT_NONE",
2834 PY_SSL_CERT_NONE);
2835 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2836 PY_SSL_CERT_OPTIONAL);
2837 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2838 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002839
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002840 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002841#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002842 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2843 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002844#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002845 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2846 PY_SSL_VERSION_SSL3);
2847 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2848 PY_SSL_VERSION_SSL23);
2849 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2850 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002851
Antoine Pitroub5218772010-05-21 09:56:06 +00002852 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01002853 PyModule_AddIntConstant(m, "OP_ALL",
2854 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00002855 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2856 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2857 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou6db49442011-12-19 13:27:11 +01002858 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
2859 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002860 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002861#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002862 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002863#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002864#ifdef SSL_OP_NO_COMPRESSION
2865 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
2866 SSL_OP_NO_COMPRESSION);
2867#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00002868
Antoine Pitroud5323212010-10-22 18:19:07 +00002869#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2870 r = Py_True;
2871#else
2872 r = Py_False;
2873#endif
2874 Py_INCREF(r);
2875 PyModule_AddObject(m, "HAS_SNI", r);
2876
Antoine Pitroud6494802011-07-21 01:11:30 +02002877#if HAVE_OPENSSL_FINISHED
2878 r = Py_True;
2879#else
2880 r = Py_False;
2881#endif
2882 Py_INCREF(r);
2883 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2884
Antoine Pitrou501da612011-12-21 09:27:41 +01002885#ifdef OPENSSL_NO_ECDH
2886 r = Py_False;
2887#else
2888 r = Py_True;
2889#endif
2890 Py_INCREF(r);
2891 PyModule_AddObject(m, "HAS_ECDH", r);
2892
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002893#ifdef OPENSSL_NPN_NEGOTIATED
2894 r = Py_True;
2895#else
2896 r = Py_False;
2897#endif
2898 Py_INCREF(r);
2899 PyModule_AddObject(m, "HAS_NPN", r);
2900
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002901 /* Mappings for error codes */
2902 err_codes_to_names = PyDict_New();
2903 err_names_to_codes = PyDict_New();
2904 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
2905 return NULL;
2906 errcode = error_codes;
2907 while (errcode->mnemonic != NULL) {
2908 PyObject *mnemo, *key;
2909 mnemo = PyUnicode_FromString(errcode->mnemonic);
2910 key = Py_BuildValue("ii", errcode->library, errcode->reason);
2911 if (mnemo == NULL || key == NULL)
2912 return NULL;
2913 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
2914 return NULL;
2915 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
2916 return NULL;
2917 Py_DECREF(key);
2918 Py_DECREF(mnemo);
2919 errcode++;
2920 }
2921 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
2922 return NULL;
2923 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
2924 return NULL;
2925
2926 lib_codes_to_names = PyDict_New();
2927 if (lib_codes_to_names == NULL)
2928 return NULL;
2929 libcode = library_codes;
2930 while (libcode->library != NULL) {
2931 PyObject *mnemo, *key;
2932 key = PyLong_FromLong(libcode->code);
2933 mnemo = PyUnicode_FromString(libcode->library);
2934 if (key == NULL || mnemo == NULL)
2935 return NULL;
2936 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
2937 return NULL;
2938 Py_DECREF(key);
2939 Py_DECREF(mnemo);
2940 libcode++;
2941 }
2942 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
2943 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02002944
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002945 /* OpenSSL version */
2946 /* SSLeay() gives us the version of the library linked against,
2947 which could be different from the headers version.
2948 */
2949 libver = SSLeay();
2950 r = PyLong_FromUnsignedLong(libver);
2951 if (r == NULL)
2952 return NULL;
2953 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2954 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002955 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002956 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2957 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2958 return NULL;
2959 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2960 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2961 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002962
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002963 libver = OPENSSL_VERSION_NUMBER;
2964 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2965 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2966 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2967 return NULL;
2968
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002969 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002970}