blob: 434729fa9ab1d9bd72bbfe62490eb2ee8bd5be3d [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"
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020021#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
22 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
23#define PySSL_END_ALLOW_THREADS_S(save) \
24 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000025#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000026 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020027 PySSL_BEGIN_ALLOW_THREADS_S(_save);
28#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
29#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
30#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000031
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000032#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000033
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020034#define PySSL_BEGIN_ALLOW_THREADS_S(save)
35#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036#define PySSL_BEGIN_ALLOW_THREADS
37#define PySSL_BLOCK_THREADS
38#define PySSL_UNBLOCK_THREADS
39#define PySSL_END_ALLOW_THREADS
40
41#endif
42
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000043enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000044 /* these mirror ssl.h */
45 PY_SSL_ERROR_NONE,
46 PY_SSL_ERROR_SSL,
47 PY_SSL_ERROR_WANT_READ,
48 PY_SSL_ERROR_WANT_WRITE,
49 PY_SSL_ERROR_WANT_X509_LOOKUP,
50 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
51 PY_SSL_ERROR_ZERO_RETURN,
52 PY_SSL_ERROR_WANT_CONNECT,
53 /* start of non ssl.h errorcodes */
54 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
55 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
56 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000057};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000058
Thomas Woutersed03b412007-08-28 21:37:11 +000059enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000060 PY_SSL_CLIENT,
61 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000062};
63
64enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000065 PY_SSL_CERT_NONE,
66 PY_SSL_CERT_OPTIONAL,
67 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +000068};
69
70enum py_ssl_version {
Victor Stinner3de49192011-05-09 00:42:58 +020071#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000072 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +020073#endif
74 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;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000453
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000454 /* Make sure the SSL error state is initialized */
455 (void) ERR_get_state();
456 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000457
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000458 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000459 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000460 PySSL_END_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000461 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000462#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000463 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000464#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000465
Antoine Pitroud5323212010-10-22 18:19:07 +0000466#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
467 if (server_hostname != NULL)
468 SSL_set_tlsext_host_name(self->ssl, server_hostname);
469#endif
470
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000471 /* If the socket is in non-blocking mode or timeout mode, set the BIO
472 * to non-blocking mode (blocking is the default)
473 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000474 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000475 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
476 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
477 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000478
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000479 PySSL_BEGIN_ALLOW_THREADS
480 if (socket_type == PY_SSL_CLIENT)
481 SSL_set_connect_state(self->ssl);
482 else
483 SSL_set_accept_state(self->ssl);
484 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000485
Antoine Pitroud6494802011-07-21 01:11:30 +0200486 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000487 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000488 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000489}
490
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000491/* SSL object methods */
492
Antoine Pitrou152efa22010-05-16 18:19:27 +0000493static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000494{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000495 int ret;
496 int err;
497 int sockstate, nonblocking;
498 PySocketSockObject *sock
499 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000500
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000501 if (((PyObject*)sock) == Py_None) {
502 _setSSLError("Underlying socket connection gone",
503 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
504 return NULL;
505 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000506 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000507
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000508 /* just in case the blocking state of the socket has been changed */
509 nonblocking = (sock->sock_timeout >= 0.0);
510 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
511 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000512
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000513 /* Actually negotiate SSL connection */
514 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000515 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000516 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000517 ret = SSL_do_handshake(self->ssl);
518 err = SSL_get_error(self->ssl, ret);
519 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000520 if (PyErr_CheckSignals())
521 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000522 if (err == SSL_ERROR_WANT_READ) {
523 sockstate = check_socket_and_wait_for_timeout(sock, 0);
524 } else if (err == SSL_ERROR_WANT_WRITE) {
525 sockstate = check_socket_and_wait_for_timeout(sock, 1);
526 } else {
527 sockstate = SOCKET_OPERATION_OK;
528 }
529 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000530 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000531 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000532 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000533 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
534 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000535 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000536 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000537 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
538 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000539 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000540 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000541 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
542 break;
543 }
544 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000545 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000546 if (ret < 1)
547 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000548
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000549 if (self->peer_cert)
550 X509_free (self->peer_cert);
551 PySSL_BEGIN_ALLOW_THREADS
552 self->peer_cert = SSL_get_peer_certificate(self->ssl);
553 PySSL_END_ALLOW_THREADS
554
555 Py_INCREF(Py_None);
556 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000557
558error:
559 Py_DECREF(sock);
560 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000561}
562
Thomas Woutersed03b412007-08-28 21:37:11 +0000563static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000564_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000565
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000566 char namebuf[X509_NAME_MAXLEN];
567 int buflen;
568 PyObject *name_obj;
569 PyObject *value_obj;
570 PyObject *attr;
571 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000572
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000573 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
574 if (buflen < 0) {
575 _setSSLError(NULL, 0, __FILE__, __LINE__);
576 goto fail;
577 }
578 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
579 if (name_obj == NULL)
580 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000581
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000582 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
583 if (buflen < 0) {
584 _setSSLError(NULL, 0, __FILE__, __LINE__);
585 Py_DECREF(name_obj);
586 goto fail;
587 }
588 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000589 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 OPENSSL_free(valuebuf);
591 if (value_obj == NULL) {
592 Py_DECREF(name_obj);
593 goto fail;
594 }
595 attr = PyTuple_New(2);
596 if (attr == NULL) {
597 Py_DECREF(name_obj);
598 Py_DECREF(value_obj);
599 goto fail;
600 }
601 PyTuple_SET_ITEM(attr, 0, name_obj);
602 PyTuple_SET_ITEM(attr, 1, value_obj);
603 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000604
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000605 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000606 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000607}
608
609static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000610_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000611{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000612 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
613 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
614 PyObject *rdnt;
615 PyObject *attr = NULL; /* tuple to hold an attribute */
616 int entry_count = X509_NAME_entry_count(xname);
617 X509_NAME_ENTRY *entry;
618 ASN1_OBJECT *name;
619 ASN1_STRING *value;
620 int index_counter;
621 int rdn_level = -1;
622 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000623
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000624 dn = PyList_New(0);
625 if (dn == NULL)
626 return NULL;
627 /* now create another tuple to hold the top-level RDN */
628 rdn = PyList_New(0);
629 if (rdn == NULL)
630 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000631
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000632 for (index_counter = 0;
633 index_counter < entry_count;
634 index_counter++)
635 {
636 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000637
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000638 /* check to see if we've gotten to a new RDN */
639 if (rdn_level >= 0) {
640 if (rdn_level != entry->set) {
641 /* yes, new RDN */
642 /* add old RDN to DN */
643 rdnt = PyList_AsTuple(rdn);
644 Py_DECREF(rdn);
645 if (rdnt == NULL)
646 goto fail0;
647 retcode = PyList_Append(dn, rdnt);
648 Py_DECREF(rdnt);
649 if (retcode < 0)
650 goto fail0;
651 /* create new RDN */
652 rdn = PyList_New(0);
653 if (rdn == NULL)
654 goto fail0;
655 }
656 }
657 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000658
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000659 /* now add this attribute to the current RDN */
660 name = X509_NAME_ENTRY_get_object(entry);
661 value = X509_NAME_ENTRY_get_data(entry);
662 attr = _create_tuple_for_attribute(name, value);
663 /*
664 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
665 entry->set,
666 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
667 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
668 */
669 if (attr == NULL)
670 goto fail1;
671 retcode = PyList_Append(rdn, attr);
672 Py_DECREF(attr);
673 if (retcode < 0)
674 goto fail1;
675 }
676 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100677 if (rdn != NULL) {
678 if (PyList_GET_SIZE(rdn) > 0) {
679 rdnt = PyList_AsTuple(rdn);
680 Py_DECREF(rdn);
681 if (rdnt == NULL)
682 goto fail0;
683 retcode = PyList_Append(dn, rdnt);
684 Py_DECREF(rdnt);
685 if (retcode < 0)
686 goto fail0;
687 }
688 else {
689 Py_DECREF(rdn);
690 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000691 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000692
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000693 /* convert list to tuple */
694 rdnt = PyList_AsTuple(dn);
695 Py_DECREF(dn);
696 if (rdnt == NULL)
697 return NULL;
698 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000699
700 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000701 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000702
703 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000704 Py_XDECREF(dn);
705 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000706}
707
708static PyObject *
709_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000710
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000711 /* this code follows the procedure outlined in
712 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
713 function to extract the STACK_OF(GENERAL_NAME),
714 then iterates through the stack to add the
715 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000716
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000717 int i, j;
718 PyObject *peer_alt_names = Py_None;
719 PyObject *v, *t;
720 X509_EXTENSION *ext = NULL;
721 GENERAL_NAMES *names = NULL;
722 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000723 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000724 BIO *biobuf = NULL;
725 char buf[2048];
726 char *vptr;
727 int len;
728 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000729#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000730 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000731#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000732 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000733#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000734
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 if (certificate == NULL)
736 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000737
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000738 /* get a memory buffer */
739 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000740
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200741 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000742 while ((i = X509_get_ext_by_NID(
743 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000744
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 if (peer_alt_names == Py_None) {
746 peer_alt_names = PyList_New(0);
747 if (peer_alt_names == NULL)
748 goto fail;
749 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000750
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000751 /* now decode the altName */
752 ext = X509_get_ext(certificate, i);
753 if(!(method = X509V3_EXT_get(ext))) {
754 PyErr_SetString
755 (PySSLErrorObject,
756 ERRSTR("No method for internalizing subjectAltName!"));
757 goto fail;
758 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000759
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000760 p = ext->value->data;
761 if (method->it)
762 names = (GENERAL_NAMES*)
763 (ASN1_item_d2i(NULL,
764 &p,
765 ext->value->length,
766 ASN1_ITEM_ptr(method->it)));
767 else
768 names = (GENERAL_NAMES*)
769 (method->d2i(NULL,
770 &p,
771 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000772
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000773 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000774
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000775 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000776
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000777 name = sk_GENERAL_NAME_value(names, j);
778 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000779
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000780 /* we special-case DirName as a tuple of
781 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000782
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 t = PyTuple_New(2);
784 if (t == NULL) {
785 goto fail;
786 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000787
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000788 v = PyUnicode_FromString("DirName");
789 if (v == NULL) {
790 Py_DECREF(t);
791 goto fail;
792 }
793 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000794
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000795 v = _create_tuple_for_X509_NAME (name->d.dirn);
796 if (v == NULL) {
797 Py_DECREF(t);
798 goto fail;
799 }
800 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000801
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000802 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000803
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000804 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000806 (void) BIO_reset(biobuf);
807 GENERAL_NAME_print(biobuf, name);
808 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
809 if (len < 0) {
810 _setSSLError(NULL, 0, __FILE__, __LINE__);
811 goto fail;
812 }
813 vptr = strchr(buf, ':');
814 if (vptr == NULL)
815 goto fail;
816 t = PyTuple_New(2);
817 if (t == NULL)
818 goto fail;
819 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
820 if (v == NULL) {
821 Py_DECREF(t);
822 goto fail;
823 }
824 PyTuple_SET_ITEM(t, 0, v);
825 v = PyUnicode_FromStringAndSize((vptr + 1),
826 (len - (vptr - buf + 1)));
827 if (v == NULL) {
828 Py_DECREF(t);
829 goto fail;
830 }
831 PyTuple_SET_ITEM(t, 1, v);
832 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000833
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000835
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000836 if (PyList_Append(peer_alt_names, t) < 0) {
837 Py_DECREF(t);
838 goto fail;
839 }
840 Py_DECREF(t);
841 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100842 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000843 }
844 BIO_free(biobuf);
845 if (peer_alt_names != Py_None) {
846 v = PyList_AsTuple(peer_alt_names);
847 Py_DECREF(peer_alt_names);
848 return v;
849 } else {
850 return peer_alt_names;
851 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000852
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000853
854 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000855 if (biobuf != NULL)
856 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000857
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000858 if (peer_alt_names != Py_None) {
859 Py_XDECREF(peer_alt_names);
860 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000861
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000862 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000863}
864
865static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000866_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000867
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000868 PyObject *retval = NULL;
869 BIO *biobuf = NULL;
870 PyObject *peer;
871 PyObject *peer_alt_names = NULL;
872 PyObject *issuer;
873 PyObject *version;
874 PyObject *sn_obj;
875 ASN1_INTEGER *serialNumber;
876 char buf[2048];
877 int len;
878 ASN1_TIME *notBefore, *notAfter;
879 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000880
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000881 retval = PyDict_New();
882 if (retval == NULL)
883 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000884
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000885 peer = _create_tuple_for_X509_NAME(
886 X509_get_subject_name(certificate));
887 if (peer == NULL)
888 goto fail0;
889 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
890 Py_DECREF(peer);
891 goto fail0;
892 }
893 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000894
Antoine Pitroufb046912010-11-09 20:21:19 +0000895 issuer = _create_tuple_for_X509_NAME(
896 X509_get_issuer_name(certificate));
897 if (issuer == NULL)
898 goto fail0;
899 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000900 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000901 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000903 Py_DECREF(issuer);
904
905 version = PyLong_FromLong(X509_get_version(certificate) + 1);
906 if (PyDict_SetItemString(retval, "version", version) < 0) {
907 Py_DECREF(version);
908 goto fail0;
909 }
910 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000911
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000912 /* get a memory buffer */
913 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000914
Antoine Pitroufb046912010-11-09 20:21:19 +0000915 (void) BIO_reset(biobuf);
916 serialNumber = X509_get_serialNumber(certificate);
917 /* should not exceed 20 octets, 160 bits, so buf is big enough */
918 i2a_ASN1_INTEGER(biobuf, serialNumber);
919 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
920 if (len < 0) {
921 _setSSLError(NULL, 0, __FILE__, __LINE__);
922 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000923 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000924 sn_obj = PyUnicode_FromStringAndSize(buf, len);
925 if (sn_obj == NULL)
926 goto fail1;
927 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
928 Py_DECREF(sn_obj);
929 goto fail1;
930 }
931 Py_DECREF(sn_obj);
932
933 (void) BIO_reset(biobuf);
934 notBefore = X509_get_notBefore(certificate);
935 ASN1_TIME_print(biobuf, notBefore);
936 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
937 if (len < 0) {
938 _setSSLError(NULL, 0, __FILE__, __LINE__);
939 goto fail1;
940 }
941 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
942 if (pnotBefore == NULL)
943 goto fail1;
944 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
945 Py_DECREF(pnotBefore);
946 goto fail1;
947 }
948 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000949
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000950 (void) BIO_reset(biobuf);
951 notAfter = X509_get_notAfter(certificate);
952 ASN1_TIME_print(biobuf, notAfter);
953 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
954 if (len < 0) {
955 _setSSLError(NULL, 0, __FILE__, __LINE__);
956 goto fail1;
957 }
958 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
959 if (pnotAfter == NULL)
960 goto fail1;
961 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
962 Py_DECREF(pnotAfter);
963 goto fail1;
964 }
965 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000966
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000967 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000968
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000969 peer_alt_names = _get_peer_alt_names(certificate);
970 if (peer_alt_names == NULL)
971 goto fail1;
972 else if (peer_alt_names != Py_None) {
973 if (PyDict_SetItemString(retval, "subjectAltName",
974 peer_alt_names) < 0) {
975 Py_DECREF(peer_alt_names);
976 goto fail1;
977 }
978 Py_DECREF(peer_alt_names);
979 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000980
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000981 BIO_free(biobuf);
982 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000983
984 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000985 if (biobuf != NULL)
986 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000987 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000988 Py_XDECREF(retval);
989 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000990}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000991
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000992
993static PyObject *
994PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
995
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000996 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +0000997 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000998 X509 *x=NULL;
999 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001000
Antoine Pitroufb046912010-11-09 20:21:19 +00001001 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1002 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001003 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001004
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001005 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1006 PyErr_SetString(PySSLErrorObject,
1007 "Can't malloc memory to read file");
1008 goto fail0;
1009 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001010
Victor Stinner3800e1e2010-05-16 21:23:48 +00001011 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001012 PyErr_SetString(PySSLErrorObject,
1013 "Can't open file");
1014 goto fail0;
1015 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001016
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001017 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1018 if (x == NULL) {
1019 PyErr_SetString(PySSLErrorObject,
1020 "Error decoding PEM-encoded file");
1021 goto fail0;
1022 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001023
Antoine Pitroufb046912010-11-09 20:21:19 +00001024 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001025 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001026
1027 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001028 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001029 if (cert != NULL) BIO_free(cert);
1030 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001031}
1032
1033
1034static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001035PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001036{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001037 PyObject *retval = NULL;
1038 int len;
1039 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001040 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001041
Antoine Pitrou721738f2012-08-15 23:20:39 +02001042 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001043 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001044
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001045 if (!self->peer_cert)
1046 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001047
Antoine Pitrou721738f2012-08-15 23:20:39 +02001048 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001049 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001050
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001051 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001052
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001053 bytes_buf = NULL;
1054 len = i2d_X509(self->peer_cert, &bytes_buf);
1055 if (len < 0) {
1056 PySSL_SetError(self, len, __FILE__, __LINE__);
1057 return NULL;
1058 }
1059 /* this is actually an immutable bytes sequence */
1060 retval = PyBytes_FromStringAndSize
1061 ((const char *) bytes_buf, len);
1062 OPENSSL_free(bytes_buf);
1063 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001064
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001065 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001066 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001067 if ((verification & SSL_VERIFY_PEER) == 0)
1068 return PyDict_New();
1069 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001070 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001071 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001072}
1073
1074PyDoc_STRVAR(PySSL_peercert_doc,
1075"peer_certificate([der=False]) -> certificate\n\
1076\n\
1077Returns the certificate for the peer. If no certificate was provided,\n\
1078returns None. If a certificate was provided, but not validated, returns\n\
1079an empty dictionary. Otherwise returns a dict containing information\n\
1080about the peer certificate.\n\
1081\n\
1082If the optional argument is True, returns a DER-encoded copy of the\n\
1083peer certificate, or None if no certificate was provided. This will\n\
1084return the certificate even if it wasn't validated.");
1085
Antoine Pitrou152efa22010-05-16 18:19:27 +00001086static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001087
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001088 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001089 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001090 char *cipher_name;
1091 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001092
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001093 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001094 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001095 current = SSL_get_current_cipher(self->ssl);
1096 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001097 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001098
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 retval = PyTuple_New(3);
1100 if (retval == NULL)
1101 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001102
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 cipher_name = (char *) SSL_CIPHER_get_name(current);
1104 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001105 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001106 PyTuple_SET_ITEM(retval, 0, Py_None);
1107 } else {
1108 v = PyUnicode_FromString(cipher_name);
1109 if (v == NULL)
1110 goto fail0;
1111 PyTuple_SET_ITEM(retval, 0, v);
1112 }
1113 cipher_protocol = SSL_CIPHER_get_version(current);
1114 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001115 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001116 PyTuple_SET_ITEM(retval, 1, Py_None);
1117 } else {
1118 v = PyUnicode_FromString(cipher_protocol);
1119 if (v == NULL)
1120 goto fail0;
1121 PyTuple_SET_ITEM(retval, 1, v);
1122 }
1123 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1124 if (v == NULL)
1125 goto fail0;
1126 PyTuple_SET_ITEM(retval, 2, v);
1127 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001128
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001129 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001130 Py_DECREF(retval);
1131 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001132}
1133
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001134#ifdef OPENSSL_NPN_NEGOTIATED
1135static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1136 const unsigned char *out;
1137 unsigned int outlen;
1138
Victor Stinner4569cd52013-06-23 14:58:43 +02001139 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001140 &out, &outlen);
1141
1142 if (out == NULL)
1143 Py_RETURN_NONE;
1144 return PyUnicode_FromStringAndSize((char *) out, outlen);
1145}
1146#endif
1147
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001148static PyObject *PySSL_compression(PySSLSocket *self) {
1149#ifdef OPENSSL_NO_COMP
1150 Py_RETURN_NONE;
1151#else
1152 const COMP_METHOD *comp_method;
1153 const char *short_name;
1154
1155 if (self->ssl == NULL)
1156 Py_RETURN_NONE;
1157 comp_method = SSL_get_current_compression(self->ssl);
1158 if (comp_method == NULL || comp_method->type == NID_undef)
1159 Py_RETURN_NONE;
1160 short_name = OBJ_nid2sn(comp_method->type);
1161 if (short_name == NULL)
1162 Py_RETURN_NONE;
1163 return PyUnicode_DecodeFSDefault(short_name);
1164#endif
1165}
1166
Antoine Pitrou152efa22010-05-16 18:19:27 +00001167static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001168{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001169 if (self->peer_cert) /* Possible not to have one? */
1170 X509_free (self->peer_cert);
1171 if (self->ssl)
1172 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001173 Py_XDECREF(self->Socket);
1174 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001175}
1176
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001177/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001178 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001179 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001180 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001181
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001182static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001183check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001184{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001185 fd_set fds;
1186 struct timeval tv;
1187 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001188
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001189 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1190 if (s->sock_timeout < 0.0)
1191 return SOCKET_IS_BLOCKING;
1192 else if (s->sock_timeout == 0.0)
1193 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001194
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001195 /* Guard against closed socket */
1196 if (s->sock_fd < 0)
1197 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001199 /* Prefer poll, if available, since you can poll() any fd
1200 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001201#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001202 {
1203 struct pollfd pollfd;
1204 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001205
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001206 pollfd.fd = s->sock_fd;
1207 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001208
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001209 /* s->sock_timeout is in seconds, timeout in ms */
1210 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1211 PySSL_BEGIN_ALLOW_THREADS
1212 rc = poll(&pollfd, 1, timeout);
1213 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001214
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001215 goto normal_return;
1216 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001217#endif
1218
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001219 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001220 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001221 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001222
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001223 /* Construct the arguments to select */
1224 tv.tv_sec = (int)s->sock_timeout;
1225 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1226 FD_ZERO(&fds);
1227 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001228
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001229 /* See if the socket is ready */
1230 PySSL_BEGIN_ALLOW_THREADS
1231 if (writing)
1232 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1233 else
1234 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1235 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001236
Bill Janssen6e027db2007-11-15 22:23:56 +00001237#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001238normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001239#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001240 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1241 (when we are able to write or when there's something to read) */
1242 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001243}
1244
Antoine Pitrou152efa22010-05-16 18:19:27 +00001245static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001246{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001247 Py_buffer buf;
1248 int len;
1249 int sockstate;
1250 int err;
1251 int nonblocking;
1252 PySocketSockObject *sock
1253 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001254
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001255 if (((PyObject*)sock) == Py_None) {
1256 _setSSLError("Underlying socket connection gone",
1257 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1258 return NULL;
1259 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001260 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001261
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001262 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1263 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001264 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001265 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001266
Victor Stinner6efa9652013-06-25 00:42:31 +02001267 if (buf.len > INT_MAX) {
1268 PyErr_Format(PyExc_OverflowError,
1269 "string longer than %d bytes", INT_MAX);
1270 goto error;
1271 }
1272
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001273 /* just in case the blocking state of the socket has been changed */
1274 nonblocking = (sock->sock_timeout >= 0.0);
1275 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1276 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1277
1278 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1279 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001280 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 "The write operation timed out");
1282 goto error;
1283 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1284 PyErr_SetString(PySSLErrorObject,
1285 "Underlying socket has been closed.");
1286 goto error;
1287 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1288 PyErr_SetString(PySSLErrorObject,
1289 "Underlying socket too large for select().");
1290 goto error;
1291 }
1292 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001293 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001294 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 err = SSL_get_error(self->ssl, len);
1296 PySSL_END_ALLOW_THREADS
1297 if (PyErr_CheckSignals()) {
1298 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001299 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001300 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001301 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001302 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001303 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001304 } else {
1305 sockstate = SOCKET_OPERATION_OK;
1306 }
1307 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001308 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001309 "The write operation timed out");
1310 goto error;
1311 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1312 PyErr_SetString(PySSLErrorObject,
1313 "Underlying socket has been closed.");
1314 goto error;
1315 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1316 break;
1317 }
1318 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001319
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001320 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001321 PyBuffer_Release(&buf);
1322 if (len > 0)
1323 return PyLong_FromLong(len);
1324 else
1325 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001326
1327error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001328 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 PyBuffer_Release(&buf);
1330 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001331}
1332
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001333PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001334"write(s) -> len\n\
1335\n\
1336Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001337of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001338
Antoine Pitrou152efa22010-05-16 18:19:27 +00001339static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001340{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001341 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001342
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001343 PySSL_BEGIN_ALLOW_THREADS
1344 count = SSL_pending(self->ssl);
1345 PySSL_END_ALLOW_THREADS
1346 if (count < 0)
1347 return PySSL_SetError(self, count, __FILE__, __LINE__);
1348 else
1349 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001350}
1351
1352PyDoc_STRVAR(PySSL_SSLpending_doc,
1353"pending() -> count\n\
1354\n\
1355Returns the number of already decrypted bytes available for read,\n\
1356pending on the connection.\n");
1357
Antoine Pitrou152efa22010-05-16 18:19:27 +00001358static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001359{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001360 PyObject *dest = NULL;
1361 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001362 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001363 int len, count;
1364 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001365 int sockstate;
1366 int err;
1367 int nonblocking;
1368 PySocketSockObject *sock
1369 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001370
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001371 if (((PyObject*)sock) == Py_None) {
1372 _setSSLError("Underlying socket connection gone",
1373 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1374 return NULL;
1375 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001376 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001377
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001378 buf.obj = NULL;
1379 buf.buf = NULL;
1380 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001381 goto error;
1382
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001383 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1384 dest = PyBytes_FromStringAndSize(NULL, len);
1385 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001386 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001387 mem = PyBytes_AS_STRING(dest);
1388 }
1389 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001390 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001391 mem = buf.buf;
1392 if (len <= 0 || len > buf.len) {
1393 len = (int) buf.len;
1394 if (buf.len != len) {
1395 PyErr_SetString(PyExc_OverflowError,
1396 "maximum length can't fit in a C 'int'");
1397 goto error;
1398 }
1399 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001400 }
1401
1402 /* just in case the blocking state of the socket has been changed */
1403 nonblocking = (sock->sock_timeout >= 0.0);
1404 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1405 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1406
1407 /* first check if there are bytes ready to be read */
1408 PySSL_BEGIN_ALLOW_THREADS
1409 count = SSL_pending(self->ssl);
1410 PySSL_END_ALLOW_THREADS
1411
1412 if (!count) {
1413 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1414 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001415 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001416 "The read operation timed out");
1417 goto error;
1418 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1419 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001420 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001421 goto error;
1422 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1423 count = 0;
1424 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001425 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001426 }
1427 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001428 PySSL_BEGIN_ALLOW_THREADS
1429 count = SSL_read(self->ssl, mem, len);
1430 err = SSL_get_error(self->ssl, count);
1431 PySSL_END_ALLOW_THREADS
1432 if (PyErr_CheckSignals())
1433 goto error;
1434 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001435 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001436 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001437 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001438 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1439 (SSL_get_shutdown(self->ssl) ==
1440 SSL_RECEIVED_SHUTDOWN))
1441 {
1442 count = 0;
1443 goto done;
1444 } else {
1445 sockstate = SOCKET_OPERATION_OK;
1446 }
1447 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001448 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001449 "The read operation timed out");
1450 goto error;
1451 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1452 break;
1453 }
1454 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1455 if (count <= 0) {
1456 PySSL_SetError(self, count, __FILE__, __LINE__);
1457 goto error;
1458 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001459
1460done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001461 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001462 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001463 _PyBytes_Resize(&dest, count);
1464 return dest;
1465 }
1466 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001467 PyBuffer_Release(&buf);
1468 return PyLong_FromLong(count);
1469 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001470
1471error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001472 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001473 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001474 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001475 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001476 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001477 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001478}
1479
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001480PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001481"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001482\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001483Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001484
Antoine Pitrou152efa22010-05-16 18:19:27 +00001485static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001486{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001487 int err, ssl_err, sockstate, nonblocking;
1488 int zeros = 0;
1489 PySocketSockObject *sock
1490 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001491
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001492 /* Guard against closed socket */
1493 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1494 _setSSLError("Underlying socket connection gone",
1495 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1496 return NULL;
1497 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001498 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001499
1500 /* Just in case the blocking state of the socket has been changed */
1501 nonblocking = (sock->sock_timeout >= 0.0);
1502 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1503 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1504
1505 while (1) {
1506 PySSL_BEGIN_ALLOW_THREADS
1507 /* Disable read-ahead so that unwrap can work correctly.
1508 * Otherwise OpenSSL might read in too much data,
1509 * eating clear text data that happens to be
1510 * transmitted after the SSL shutdown.
1511 * Should be safe to call repeatedly everytime this
1512 * function is used and the shutdown_seen_zero != 0
1513 * condition is met.
1514 */
1515 if (self->shutdown_seen_zero)
1516 SSL_set_read_ahead(self->ssl, 0);
1517 err = SSL_shutdown(self->ssl);
1518 PySSL_END_ALLOW_THREADS
1519 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1520 if (err > 0)
1521 break;
1522 if (err == 0) {
1523 /* Don't loop endlessly; instead preserve legacy
1524 behaviour of trying SSL_shutdown() only twice.
1525 This looks necessary for OpenSSL < 0.9.8m */
1526 if (++zeros > 1)
1527 break;
1528 /* Shutdown was sent, now try receiving */
1529 self->shutdown_seen_zero = 1;
1530 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001531 }
1532
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001533 /* Possibly retry shutdown until timeout or failure */
1534 ssl_err = SSL_get_error(self->ssl, err);
1535 if (ssl_err == SSL_ERROR_WANT_READ)
1536 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1537 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1538 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1539 else
1540 break;
1541 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1542 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001543 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001544 "The read operation timed out");
1545 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001546 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001547 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001548 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001549 }
1550 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1551 PyErr_SetString(PySSLErrorObject,
1552 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001553 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001554 }
1555 else if (sockstate != SOCKET_OPERATION_OK)
1556 /* Retain the SSL error code */
1557 break;
1558 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001559
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001560 if (err < 0) {
1561 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001562 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001563 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001564 else
1565 /* It's already INCREF'ed */
1566 return (PyObject *) sock;
1567
1568error:
1569 Py_DECREF(sock);
1570 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001571}
1572
1573PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1574"shutdown(s) -> socket\n\
1575\n\
1576Does the SSL shutdown handshake with the remote end, and returns\n\
1577the underlying socket object.");
1578
Antoine Pitroud6494802011-07-21 01:11:30 +02001579#if HAVE_OPENSSL_FINISHED
1580static PyObject *
1581PySSL_tls_unique_cb(PySSLSocket *self)
1582{
1583 PyObject *retval = NULL;
1584 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001585 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001586
1587 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1588 /* if session is resumed XOR we are the client */
1589 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1590 }
1591 else {
1592 /* if a new session XOR we are the server */
1593 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1594 }
1595
1596 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001597 if (len == 0)
1598 Py_RETURN_NONE;
1599
1600 retval = PyBytes_FromStringAndSize(buf, len);
1601
1602 return retval;
1603}
1604
1605PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1606"tls_unique_cb() -> bytes\n\
1607\n\
1608Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1609\n\
1610If the TLS handshake is not yet complete, None is returned");
1611
1612#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001613
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001614static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001615 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1616 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1617 PySSL_SSLwrite_doc},
1618 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1619 PySSL_SSLread_doc},
1620 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1621 PySSL_SSLpending_doc},
1622 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1623 PySSL_peercert_doc},
1624 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001625#ifdef OPENSSL_NPN_NEGOTIATED
1626 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1627#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001628 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001629 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1630 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001631#if HAVE_OPENSSL_FINISHED
1632 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1633 PySSL_tls_unique_cb_doc},
1634#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001635 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001636};
1637
Antoine Pitrou152efa22010-05-16 18:19:27 +00001638static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001639 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001640 "_ssl._SSLSocket", /*tp_name*/
1641 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001642 0, /*tp_itemsize*/
1643 /* methods */
1644 (destructor)PySSL_dealloc, /*tp_dealloc*/
1645 0, /*tp_print*/
1646 0, /*tp_getattr*/
1647 0, /*tp_setattr*/
1648 0, /*tp_reserved*/
1649 0, /*tp_repr*/
1650 0, /*tp_as_number*/
1651 0, /*tp_as_sequence*/
1652 0, /*tp_as_mapping*/
1653 0, /*tp_hash*/
1654 0, /*tp_call*/
1655 0, /*tp_str*/
1656 0, /*tp_getattro*/
1657 0, /*tp_setattro*/
1658 0, /*tp_as_buffer*/
1659 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1660 0, /*tp_doc*/
1661 0, /*tp_traverse*/
1662 0, /*tp_clear*/
1663 0, /*tp_richcompare*/
1664 0, /*tp_weaklistoffset*/
1665 0, /*tp_iter*/
1666 0, /*tp_iternext*/
1667 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001668};
1669
Antoine Pitrou152efa22010-05-16 18:19:27 +00001670
1671/*
1672 * _SSLContext objects
1673 */
1674
1675static PyObject *
1676context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1677{
1678 char *kwlist[] = {"protocol", NULL};
1679 PySSLContext *self;
1680 int proto_version = PY_SSL_VERSION_SSL23;
1681 SSL_CTX *ctx = NULL;
1682
1683 if (!PyArg_ParseTupleAndKeywords(
1684 args, kwds, "i:_SSLContext", kwlist,
1685 &proto_version))
1686 return NULL;
1687
1688 PySSL_BEGIN_ALLOW_THREADS
1689 if (proto_version == PY_SSL_VERSION_TLS1)
1690 ctx = SSL_CTX_new(TLSv1_method());
1691 else if (proto_version == PY_SSL_VERSION_SSL3)
1692 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001693#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001694 else if (proto_version == PY_SSL_VERSION_SSL2)
1695 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001696#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001697 else if (proto_version == PY_SSL_VERSION_SSL23)
1698 ctx = SSL_CTX_new(SSLv23_method());
1699 else
1700 proto_version = -1;
1701 PySSL_END_ALLOW_THREADS
1702
1703 if (proto_version == -1) {
1704 PyErr_SetString(PyExc_ValueError,
1705 "invalid protocol version");
1706 return NULL;
1707 }
1708 if (ctx == NULL) {
1709 PyErr_SetString(PySSLErrorObject,
1710 "failed to allocate SSL context");
1711 return NULL;
1712 }
1713
1714 assert(type != NULL && type->tp_alloc != NULL);
1715 self = (PySSLContext *) type->tp_alloc(type, 0);
1716 if (self == NULL) {
1717 SSL_CTX_free(ctx);
1718 return NULL;
1719 }
1720 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001721#ifdef OPENSSL_NPN_NEGOTIATED
1722 self->npn_protocols = NULL;
1723#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001724 /* Defaults */
1725 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001726 SSL_CTX_set_options(self->ctx,
1727 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001728
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001729#define SID_CTX "Python"
1730 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1731 sizeof(SID_CTX));
1732#undef SID_CTX
1733
Antoine Pitrou152efa22010-05-16 18:19:27 +00001734 return (PyObject *)self;
1735}
1736
1737static void
1738context_dealloc(PySSLContext *self)
1739{
1740 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001741#ifdef OPENSSL_NPN_NEGOTIATED
1742 PyMem_Free(self->npn_protocols);
1743#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001744 Py_TYPE(self)->tp_free(self);
1745}
1746
1747static PyObject *
1748set_ciphers(PySSLContext *self, PyObject *args)
1749{
1750 int ret;
1751 const char *cipherlist;
1752
1753 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1754 return NULL;
1755 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1756 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001757 /* Clearing the error queue is necessary on some OpenSSL versions,
1758 otherwise the error will be reported again when another SSL call
1759 is done. */
1760 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001761 PyErr_SetString(PySSLErrorObject,
1762 "No cipher can be selected.");
1763 return NULL;
1764 }
1765 Py_RETURN_NONE;
1766}
1767
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001768#ifdef OPENSSL_NPN_NEGOTIATED
1769/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1770static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001771_advertiseNPN_cb(SSL *s,
1772 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001773 void *args)
1774{
1775 PySSLContext *ssl_ctx = (PySSLContext *) args;
1776
1777 if (ssl_ctx->npn_protocols == NULL) {
1778 *data = (unsigned char *) "";
1779 *len = 0;
1780 } else {
1781 *data = (unsigned char *) ssl_ctx->npn_protocols;
1782 *len = ssl_ctx->npn_protocols_len;
1783 }
1784
1785 return SSL_TLSEXT_ERR_OK;
1786}
1787/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1788static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001789_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001790 unsigned char **out, unsigned char *outlen,
1791 const unsigned char *server, unsigned int server_len,
1792 void *args)
1793{
1794 PySSLContext *ssl_ctx = (PySSLContext *) args;
1795
1796 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1797 int client_len;
1798
1799 if (client == NULL) {
1800 client = (unsigned char *) "";
1801 client_len = 0;
1802 } else {
1803 client_len = ssl_ctx->npn_protocols_len;
1804 }
1805
1806 SSL_select_next_proto(out, outlen,
1807 server, server_len,
1808 client, client_len);
1809
1810 return SSL_TLSEXT_ERR_OK;
1811}
1812#endif
1813
1814static PyObject *
1815_set_npn_protocols(PySSLContext *self, PyObject *args)
1816{
1817#ifdef OPENSSL_NPN_NEGOTIATED
1818 Py_buffer protos;
1819
1820 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1821 return NULL;
1822
Christian Heimes5cb31c92012-09-20 12:42:54 +02001823 if (self->npn_protocols != NULL) {
1824 PyMem_Free(self->npn_protocols);
1825 }
1826
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001827 self->npn_protocols = PyMem_Malloc(protos.len);
1828 if (self->npn_protocols == NULL) {
1829 PyBuffer_Release(&protos);
1830 return PyErr_NoMemory();
1831 }
1832 memcpy(self->npn_protocols, protos.buf, protos.len);
1833 self->npn_protocols_len = (int) protos.len;
1834
1835 /* set both server and client callbacks, because the context can
1836 * be used to create both types of sockets */
1837 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
1838 _advertiseNPN_cb,
1839 self);
1840 SSL_CTX_set_next_proto_select_cb(self->ctx,
1841 _selectNPN_cb,
1842 self);
1843
1844 PyBuffer_Release(&protos);
1845 Py_RETURN_NONE;
1846#else
1847 PyErr_SetString(PyExc_NotImplementedError,
1848 "The NPN extension requires OpenSSL 1.0.1 or later.");
1849 return NULL;
1850#endif
1851}
1852
Antoine Pitrou152efa22010-05-16 18:19:27 +00001853static PyObject *
1854get_verify_mode(PySSLContext *self, void *c)
1855{
1856 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1857 case SSL_VERIFY_NONE:
1858 return PyLong_FromLong(PY_SSL_CERT_NONE);
1859 case SSL_VERIFY_PEER:
1860 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1861 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1862 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1863 }
1864 PyErr_SetString(PySSLErrorObject,
1865 "invalid return value from SSL_CTX_get_verify_mode");
1866 return NULL;
1867}
1868
1869static int
1870set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1871{
1872 int n, mode;
1873 if (!PyArg_Parse(arg, "i", &n))
1874 return -1;
1875 if (n == PY_SSL_CERT_NONE)
1876 mode = SSL_VERIFY_NONE;
1877 else if (n == PY_SSL_CERT_OPTIONAL)
1878 mode = SSL_VERIFY_PEER;
1879 else if (n == PY_SSL_CERT_REQUIRED)
1880 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1881 else {
1882 PyErr_SetString(PyExc_ValueError,
1883 "invalid value for verify_mode");
1884 return -1;
1885 }
1886 SSL_CTX_set_verify(self->ctx, mode, NULL);
1887 return 0;
1888}
1889
1890static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001891get_options(PySSLContext *self, void *c)
1892{
1893 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1894}
1895
1896static int
1897set_options(PySSLContext *self, PyObject *arg, void *c)
1898{
1899 long new_opts, opts, set, clear;
1900 if (!PyArg_Parse(arg, "l", &new_opts))
1901 return -1;
1902 opts = SSL_CTX_get_options(self->ctx);
1903 clear = opts & ~new_opts;
1904 set = ~opts & new_opts;
1905 if (clear) {
1906#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1907 SSL_CTX_clear_options(self->ctx, clear);
1908#else
1909 PyErr_SetString(PyExc_ValueError,
1910 "can't clear options before OpenSSL 0.9.8m");
1911 return -1;
1912#endif
1913 }
1914 if (set)
1915 SSL_CTX_set_options(self->ctx, set);
1916 return 0;
1917}
1918
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001919typedef struct {
1920 PyThreadState *thread_state;
1921 PyObject *callable;
1922 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02001923 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001924 int error;
1925} _PySSLPasswordInfo;
1926
1927static int
1928_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1929 const char *bad_type_error)
1930{
1931 /* Set the password and size fields of a _PySSLPasswordInfo struct
1932 from a unicode, bytes, or byte array object.
1933 The password field will be dynamically allocated and must be freed
1934 by the caller */
1935 PyObject *password_bytes = NULL;
1936 const char *data = NULL;
1937 Py_ssize_t size;
1938
1939 if (PyUnicode_Check(password)) {
1940 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
1941 if (!password_bytes) {
1942 goto error;
1943 }
1944 data = PyBytes_AS_STRING(password_bytes);
1945 size = PyBytes_GET_SIZE(password_bytes);
1946 } else if (PyBytes_Check(password)) {
1947 data = PyBytes_AS_STRING(password);
1948 size = PyBytes_GET_SIZE(password);
1949 } else if (PyByteArray_Check(password)) {
1950 data = PyByteArray_AS_STRING(password);
1951 size = PyByteArray_GET_SIZE(password);
1952 } else {
1953 PyErr_SetString(PyExc_TypeError, bad_type_error);
1954 goto error;
1955 }
1956
Victor Stinner9ee02032013-06-23 15:08:23 +02001957 if (size > (Py_ssize_t)INT_MAX) {
1958 PyErr_Format(PyExc_ValueError,
1959 "password cannot be longer than %d bytes", INT_MAX);
1960 goto error;
1961 }
1962
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001963 free(pw_info->password);
1964 pw_info->password = malloc(size);
1965 if (!pw_info->password) {
1966 PyErr_SetString(PyExc_MemoryError,
1967 "unable to allocate password buffer");
1968 goto error;
1969 }
1970 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02001971 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001972
1973 Py_XDECREF(password_bytes);
1974 return 1;
1975
1976error:
1977 Py_XDECREF(password_bytes);
1978 return 0;
1979}
1980
1981static int
1982_password_callback(char *buf, int size, int rwflag, void *userdata)
1983{
1984 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
1985 PyObject *fn_ret = NULL;
1986
1987 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
1988
1989 if (pw_info->callable) {
1990 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
1991 if (!fn_ret) {
1992 /* TODO: It would be nice to move _ctypes_add_traceback() into the
1993 core python API, so we could use it to add a frame here */
1994 goto error;
1995 }
1996
1997 if (!_pwinfo_set(pw_info, fn_ret,
1998 "password callback must return a string")) {
1999 goto error;
2000 }
2001 Py_CLEAR(fn_ret);
2002 }
2003
2004 if (pw_info->size > size) {
2005 PyErr_Format(PyExc_ValueError,
2006 "password cannot be longer than %d bytes", size);
2007 goto error;
2008 }
2009
2010 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2011 memcpy(buf, pw_info->password, pw_info->size);
2012 return pw_info->size;
2013
2014error:
2015 Py_XDECREF(fn_ret);
2016 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2017 pw_info->error = 1;
2018 return -1;
2019}
2020
Antoine Pitroub5218772010-05-21 09:56:06 +00002021static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002022load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2023{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002024 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2025 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002026 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002027 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2028 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2029 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002030 int r;
2031
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002032 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002033 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002034 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002035 "O|OO:load_cert_chain", kwlist,
2036 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002037 return NULL;
2038 if (keyfile == Py_None)
2039 keyfile = NULL;
2040 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2041 PyErr_SetString(PyExc_TypeError,
2042 "certfile should be a valid filesystem path");
2043 return NULL;
2044 }
2045 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2046 PyErr_SetString(PyExc_TypeError,
2047 "keyfile should be a valid filesystem path");
2048 goto error;
2049 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002050 if (password && password != Py_None) {
2051 if (PyCallable_Check(password)) {
2052 pw_info.callable = password;
2053 } else if (!_pwinfo_set(&pw_info, password,
2054 "password should be a string or callable")) {
2055 goto error;
2056 }
2057 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2058 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2059 }
2060 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002061 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2062 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002063 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002064 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002065 if (pw_info.error) {
2066 ERR_clear_error();
2067 /* the password callback has already set the error information */
2068 }
2069 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002070 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002071 PyErr_SetFromErrno(PyExc_IOError);
2072 }
2073 else {
2074 _setSSLError(NULL, 0, __FILE__, __LINE__);
2075 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002076 goto error;
2077 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002078 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002079 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002080 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2081 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002082 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2083 Py_CLEAR(keyfile_bytes);
2084 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002085 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002086 if (pw_info.error) {
2087 ERR_clear_error();
2088 /* the password callback has already set the error information */
2089 }
2090 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002091 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002092 PyErr_SetFromErrno(PyExc_IOError);
2093 }
2094 else {
2095 _setSSLError(NULL, 0, __FILE__, __LINE__);
2096 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002097 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002098 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002099 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002100 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002101 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002102 if (r != 1) {
2103 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002104 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002105 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002106 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2107 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2108 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002109 Py_RETURN_NONE;
2110
2111error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002112 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2113 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2114 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002115 Py_XDECREF(keyfile_bytes);
2116 Py_XDECREF(certfile_bytes);
2117 return NULL;
2118}
2119
2120static PyObject *
2121load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2122{
2123 char *kwlist[] = {"cafile", "capath", NULL};
2124 PyObject *cafile = NULL, *capath = NULL;
2125 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2126 const char *cafile_buf = NULL, *capath_buf = NULL;
2127 int r;
2128
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002129 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002130 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2131 "|OO:load_verify_locations", kwlist,
2132 &cafile, &capath))
2133 return NULL;
2134 if (cafile == Py_None)
2135 cafile = NULL;
2136 if (capath == Py_None)
2137 capath = NULL;
2138 if (cafile == NULL && capath == NULL) {
2139 PyErr_SetString(PyExc_TypeError,
2140 "cafile and capath cannot be both omitted");
2141 return NULL;
2142 }
2143 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2144 PyErr_SetString(PyExc_TypeError,
2145 "cafile should be a valid filesystem path");
2146 return NULL;
2147 }
2148 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002149 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002150 PyErr_SetString(PyExc_TypeError,
2151 "capath should be a valid filesystem path");
2152 return NULL;
2153 }
2154 if (cafile)
2155 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2156 if (capath)
2157 capath_buf = PyBytes_AS_STRING(capath_bytes);
2158 PySSL_BEGIN_ALLOW_THREADS
2159 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2160 PySSL_END_ALLOW_THREADS
2161 Py_XDECREF(cafile_bytes);
2162 Py_XDECREF(capath_bytes);
2163 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002164 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002165 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002166 PyErr_SetFromErrno(PyExc_IOError);
2167 }
2168 else {
2169 _setSSLError(NULL, 0, __FILE__, __LINE__);
2170 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002171 return NULL;
2172 }
2173 Py_RETURN_NONE;
2174}
2175
2176static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002177load_dh_params(PySSLContext *self, PyObject *filepath)
2178{
2179 FILE *f;
2180 DH *dh;
2181
2182 f = _Py_fopen(filepath, "rb");
2183 if (f == NULL) {
2184 if (!PyErr_Occurred())
2185 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2186 return NULL;
2187 }
2188 errno = 0;
2189 PySSL_BEGIN_ALLOW_THREADS
2190 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002191 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002192 PySSL_END_ALLOW_THREADS
2193 if (dh == NULL) {
2194 if (errno != 0) {
2195 ERR_clear_error();
2196 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2197 }
2198 else {
2199 _setSSLError(NULL, 0, __FILE__, __LINE__);
2200 }
2201 return NULL;
2202 }
2203 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2204 _setSSLError(NULL, 0, __FILE__, __LINE__);
2205 DH_free(dh);
2206 Py_RETURN_NONE;
2207}
2208
2209static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002210context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2211{
Antoine Pitroud5323212010-10-22 18:19:07 +00002212 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002213 PySocketSockObject *sock;
2214 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002215 char *hostname = NULL;
2216 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002217
Antoine Pitroud5323212010-10-22 18:19:07 +00002218 /* server_hostname is either None (or absent), or to be encoded
2219 using the idna encoding. */
2220 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002221 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002222 &sock, &server_side,
2223 Py_TYPE(Py_None), &hostname_obj)) {
2224 PyErr_Clear();
2225 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2226 PySocketModule.Sock_Type,
2227 &sock, &server_side,
2228 "idna", &hostname))
2229 return NULL;
2230#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
2231 PyMem_Free(hostname);
2232 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2233 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002234 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002235#endif
2236 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002237
Antoine Pitroud5323212010-10-22 18:19:07 +00002238 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
2239 hostname);
2240 if (hostname != NULL)
2241 PyMem_Free(hostname);
2242 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002243}
2244
Antoine Pitroub0182c82010-10-12 20:09:02 +00002245static PyObject *
2246session_stats(PySSLContext *self, PyObject *unused)
2247{
2248 int r;
2249 PyObject *value, *stats = PyDict_New();
2250 if (!stats)
2251 return NULL;
2252
2253#define ADD_STATS(SSL_NAME, KEY_NAME) \
2254 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2255 if (value == NULL) \
2256 goto error; \
2257 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2258 Py_DECREF(value); \
2259 if (r < 0) \
2260 goto error;
2261
2262 ADD_STATS(number, "number");
2263 ADD_STATS(connect, "connect");
2264 ADD_STATS(connect_good, "connect_good");
2265 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2266 ADD_STATS(accept, "accept");
2267 ADD_STATS(accept_good, "accept_good");
2268 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2269 ADD_STATS(accept, "accept");
2270 ADD_STATS(hits, "hits");
2271 ADD_STATS(misses, "misses");
2272 ADD_STATS(timeouts, "timeouts");
2273 ADD_STATS(cache_full, "cache_full");
2274
2275#undef ADD_STATS
2276
2277 return stats;
2278
2279error:
2280 Py_DECREF(stats);
2281 return NULL;
2282}
2283
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002284static PyObject *
2285set_default_verify_paths(PySSLContext *self, PyObject *unused)
2286{
2287 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2288 _setSSLError(NULL, 0, __FILE__, __LINE__);
2289 return NULL;
2290 }
2291 Py_RETURN_NONE;
2292}
2293
Antoine Pitrou501da612011-12-21 09:27:41 +01002294#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002295static PyObject *
2296set_ecdh_curve(PySSLContext *self, PyObject *name)
2297{
2298 PyObject *name_bytes;
2299 int nid;
2300 EC_KEY *key;
2301
2302 if (!PyUnicode_FSConverter(name, &name_bytes))
2303 return NULL;
2304 assert(PyBytes_Check(name_bytes));
2305 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2306 Py_DECREF(name_bytes);
2307 if (nid == 0) {
2308 PyErr_Format(PyExc_ValueError,
2309 "unknown elliptic curve name %R", name);
2310 return NULL;
2311 }
2312 key = EC_KEY_new_by_curve_name(nid);
2313 if (key == NULL) {
2314 _setSSLError(NULL, 0, __FILE__, __LINE__);
2315 return NULL;
2316 }
2317 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2318 EC_KEY_free(key);
2319 Py_RETURN_NONE;
2320}
Antoine Pitrou501da612011-12-21 09:27:41 +01002321#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002322
Antoine Pitrou152efa22010-05-16 18:19:27 +00002323static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002324 {"options", (getter) get_options,
2325 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002326 {"verify_mode", (getter) get_verify_mode,
2327 (setter) set_verify_mode, NULL},
2328 {NULL}, /* sentinel */
2329};
2330
2331static struct PyMethodDef context_methods[] = {
2332 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2333 METH_VARARGS | METH_KEYWORDS, NULL},
2334 {"set_ciphers", (PyCFunction) set_ciphers,
2335 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002336 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2337 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002338 {"load_cert_chain", (PyCFunction) load_cert_chain,
2339 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002340 {"load_dh_params", (PyCFunction) load_dh_params,
2341 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002342 {"load_verify_locations", (PyCFunction) load_verify_locations,
2343 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002344 {"session_stats", (PyCFunction) session_stats,
2345 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002346 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2347 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002348#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002349 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2350 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002351#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002352 {NULL, NULL} /* sentinel */
2353};
2354
2355static PyTypeObject PySSLContext_Type = {
2356 PyVarObject_HEAD_INIT(NULL, 0)
2357 "_ssl._SSLContext", /*tp_name*/
2358 sizeof(PySSLContext), /*tp_basicsize*/
2359 0, /*tp_itemsize*/
2360 (destructor)context_dealloc, /*tp_dealloc*/
2361 0, /*tp_print*/
2362 0, /*tp_getattr*/
2363 0, /*tp_setattr*/
2364 0, /*tp_reserved*/
2365 0, /*tp_repr*/
2366 0, /*tp_as_number*/
2367 0, /*tp_as_sequence*/
2368 0, /*tp_as_mapping*/
2369 0, /*tp_hash*/
2370 0, /*tp_call*/
2371 0, /*tp_str*/
2372 0, /*tp_getattro*/
2373 0, /*tp_setattro*/
2374 0, /*tp_as_buffer*/
2375 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2376 0, /*tp_doc*/
2377 0, /*tp_traverse*/
2378 0, /*tp_clear*/
2379 0, /*tp_richcompare*/
2380 0, /*tp_weaklistoffset*/
2381 0, /*tp_iter*/
2382 0, /*tp_iternext*/
2383 context_methods, /*tp_methods*/
2384 0, /*tp_members*/
2385 context_getsetlist, /*tp_getset*/
2386 0, /*tp_base*/
2387 0, /*tp_dict*/
2388 0, /*tp_descr_get*/
2389 0, /*tp_descr_set*/
2390 0, /*tp_dictoffset*/
2391 0, /*tp_init*/
2392 0, /*tp_alloc*/
2393 context_new, /*tp_new*/
2394};
2395
2396
2397
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002398#ifdef HAVE_OPENSSL_RAND
2399
2400/* helper routines for seeding the SSL PRNG */
2401static PyObject *
2402PySSL_RAND_add(PyObject *self, PyObject *args)
2403{
2404 char *buf;
2405 int len;
2406 double entropy;
2407
2408 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002409 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002410 RAND_add(buf, len, entropy);
2411 Py_INCREF(Py_None);
2412 return Py_None;
2413}
2414
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002415PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002416"RAND_add(string, entropy)\n\
2417\n\
2418Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002419bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002420
2421static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002422PySSL_RAND(int len, int pseudo)
2423{
2424 int ok;
2425 PyObject *bytes;
2426 unsigned long err;
2427 const char *errstr;
2428 PyObject *v;
2429
2430 bytes = PyBytes_FromStringAndSize(NULL, len);
2431 if (bytes == NULL)
2432 return NULL;
2433 if (pseudo) {
2434 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2435 if (ok == 0 || ok == 1)
2436 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2437 }
2438 else {
2439 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2440 if (ok == 1)
2441 return bytes;
2442 }
2443 Py_DECREF(bytes);
2444
2445 err = ERR_get_error();
2446 errstr = ERR_reason_error_string(err);
2447 v = Py_BuildValue("(ks)", err, errstr);
2448 if (v != NULL) {
2449 PyErr_SetObject(PySSLErrorObject, v);
2450 Py_DECREF(v);
2451 }
2452 return NULL;
2453}
2454
2455static PyObject *
2456PySSL_RAND_bytes(PyObject *self, PyObject *args)
2457{
2458 int len;
2459 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2460 return NULL;
2461 return PySSL_RAND(len, 0);
2462}
2463
2464PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2465"RAND_bytes(n) -> bytes\n\
2466\n\
2467Generate n cryptographically strong pseudo-random bytes.");
2468
2469static PyObject *
2470PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2471{
2472 int len;
2473 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2474 return NULL;
2475 return PySSL_RAND(len, 1);
2476}
2477
2478PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2479"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2480\n\
2481Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2482generated are cryptographically strong.");
2483
2484static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002485PySSL_RAND_status(PyObject *self)
2486{
Christian Heimes217cfd12007-12-02 14:31:20 +00002487 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002488}
2489
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002490PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002491"RAND_status() -> 0 or 1\n\
2492\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002493Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2494It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2495using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002496
2497static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002498PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002499{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002500 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002501 int bytes;
2502
Jesus Ceac8754a12012-09-11 02:00:58 +02002503 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002504 PyUnicode_FSConverter, &path))
2505 return NULL;
2506
2507 bytes = RAND_egd(PyBytes_AsString(path));
2508 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002509 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002510 PyErr_SetString(PySSLErrorObject,
2511 "EGD connection failed or EGD did not return "
2512 "enough data to seed the PRNG");
2513 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002514 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002515 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002516}
2517
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002518PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002519"RAND_egd(path) -> bytes\n\
2520\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002521Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2522Returns number of bytes read. Raises SSLError if connection to EGD\n\
2523fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002524
2525#endif
2526
Bill Janssen40a0f662008-08-12 16:56:25 +00002527
2528
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002529/* List of functions exported by this module. */
2530
2531static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002532 {"_test_decode_cert", PySSL_test_decode_certificate,
2533 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002534#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002535 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2536 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002537 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2538 PySSL_RAND_bytes_doc},
2539 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2540 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002541 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002542 PySSL_RAND_egd_doc},
2543 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2544 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002545#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002546 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002547};
2548
2549
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002550#ifdef WITH_THREAD
2551
2552/* an implementation of OpenSSL threading operations in terms
2553 of the Python C thread library */
2554
2555static PyThread_type_lock *_ssl_locks = NULL;
2556
2557static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002558 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002559}
2560
Bill Janssen6e027db2007-11-15 22:23:56 +00002561static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002562 (int mode, int n, const char *file, int line) {
2563 /* this function is needed to perform locking on shared data
2564 structures. (Note that OpenSSL uses a number of global data
2565 structures that will be implicitly shared whenever multiple
2566 threads use OpenSSL.) Multi-threaded applications will
2567 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002568
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002569 locking_function() must be able to handle up to
2570 CRYPTO_num_locks() different mutex locks. It sets the n-th
2571 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002572
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002573 file and line are the file number of the function setting the
2574 lock. They can be useful for debugging.
2575 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002576
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002577 if ((_ssl_locks == NULL) ||
2578 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2579 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002580
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002581 if (mode & CRYPTO_LOCK) {
2582 PyThread_acquire_lock(_ssl_locks[n], 1);
2583 } else {
2584 PyThread_release_lock(_ssl_locks[n]);
2585 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002586}
2587
2588static int _setup_ssl_threads(void) {
2589
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002590 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002591
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002592 if (_ssl_locks == NULL) {
2593 _ssl_locks_count = CRYPTO_num_locks();
2594 _ssl_locks = (PyThread_type_lock *)
2595 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2596 if (_ssl_locks == NULL)
2597 return 0;
2598 memset(_ssl_locks, 0,
2599 sizeof(PyThread_type_lock) * _ssl_locks_count);
2600 for (i = 0; i < _ssl_locks_count; i++) {
2601 _ssl_locks[i] = PyThread_allocate_lock();
2602 if (_ssl_locks[i] == NULL) {
2603 unsigned int j;
2604 for (j = 0; j < i; j++) {
2605 PyThread_free_lock(_ssl_locks[j]);
2606 }
2607 free(_ssl_locks);
2608 return 0;
2609 }
2610 }
2611 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2612 CRYPTO_set_id_callback(_ssl_thread_id_function);
2613 }
2614 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002615}
2616
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002617#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002618
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002619PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002620"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002621for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002622
Martin v. Löwis1a214512008-06-11 05:26:20 +00002623
2624static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002625 PyModuleDef_HEAD_INIT,
2626 "_ssl",
2627 module_doc,
2628 -1,
2629 PySSL_methods,
2630 NULL,
2631 NULL,
2632 NULL,
2633 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002634};
2635
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002636
2637static void
2638parse_openssl_version(unsigned long libver,
2639 unsigned int *major, unsigned int *minor,
2640 unsigned int *fix, unsigned int *patch,
2641 unsigned int *status)
2642{
2643 *status = libver & 0xF;
2644 libver >>= 4;
2645 *patch = libver & 0xFF;
2646 libver >>= 8;
2647 *fix = libver & 0xFF;
2648 libver >>= 8;
2649 *minor = libver & 0xFF;
2650 libver >>= 8;
2651 *major = libver & 0xFF;
2652}
2653
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002654PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002655PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002656{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002657 PyObject *m, *d, *r;
2658 unsigned long libver;
2659 unsigned int major, minor, fix, patch, status;
2660 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002661 struct py_ssl_error_code *errcode;
2662 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002663
Antoine Pitrou152efa22010-05-16 18:19:27 +00002664 if (PyType_Ready(&PySSLContext_Type) < 0)
2665 return NULL;
2666 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002667 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002668
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002669 m = PyModule_Create(&_sslmodule);
2670 if (m == NULL)
2671 return NULL;
2672 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002673
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002674 /* Load _socket module and its C API */
2675 socket_api = PySocketModule_ImportModuleAndAPI();
2676 if (!socket_api)
2677 return NULL;
2678 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002679
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002680 /* Init OpenSSL */
2681 SSL_load_error_strings();
2682 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002683#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002684 /* note that this will start threading if not already started */
2685 if (!_setup_ssl_threads()) {
2686 return NULL;
2687 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002688#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002689 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002690
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002691 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002692 sslerror_type_slots[0].pfunc = PyExc_OSError;
2693 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002694 if (PySSLErrorObject == NULL)
2695 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002696
Antoine Pitrou41032a62011-10-27 23:56:55 +02002697 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2698 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2699 PySSLErrorObject, NULL);
2700 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2701 "ssl.SSLWantReadError", SSLWantReadError_doc,
2702 PySSLErrorObject, NULL);
2703 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2704 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2705 PySSLErrorObject, NULL);
2706 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2707 "ssl.SSLSyscallError", SSLSyscallError_doc,
2708 PySSLErrorObject, NULL);
2709 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2710 "ssl.SSLEOFError", SSLEOFError_doc,
2711 PySSLErrorObject, NULL);
2712 if (PySSLZeroReturnErrorObject == NULL
2713 || PySSLWantReadErrorObject == NULL
2714 || PySSLWantWriteErrorObject == NULL
2715 || PySSLSyscallErrorObject == NULL
2716 || PySSLEOFErrorObject == NULL)
2717 return NULL;
2718 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2719 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2720 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2721 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2722 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2723 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002724 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002725 if (PyDict_SetItemString(d, "_SSLContext",
2726 (PyObject *)&PySSLContext_Type) != 0)
2727 return NULL;
2728 if (PyDict_SetItemString(d, "_SSLSocket",
2729 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002730 return NULL;
2731 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2732 PY_SSL_ERROR_ZERO_RETURN);
2733 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2734 PY_SSL_ERROR_WANT_READ);
2735 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2736 PY_SSL_ERROR_WANT_WRITE);
2737 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2738 PY_SSL_ERROR_WANT_X509_LOOKUP);
2739 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2740 PY_SSL_ERROR_SYSCALL);
2741 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2742 PY_SSL_ERROR_SSL);
2743 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2744 PY_SSL_ERROR_WANT_CONNECT);
2745 /* non ssl.h errorcodes */
2746 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2747 PY_SSL_ERROR_EOF);
2748 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2749 PY_SSL_ERROR_INVALID_ERROR_CODE);
2750 /* cert requirements */
2751 PyModule_AddIntConstant(m, "CERT_NONE",
2752 PY_SSL_CERT_NONE);
2753 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2754 PY_SSL_CERT_OPTIONAL);
2755 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2756 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002757
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002758 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002759#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002760 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2761 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002762#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002763 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2764 PY_SSL_VERSION_SSL3);
2765 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2766 PY_SSL_VERSION_SSL23);
2767 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2768 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002769
Antoine Pitroub5218772010-05-21 09:56:06 +00002770 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01002771 PyModule_AddIntConstant(m, "OP_ALL",
2772 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00002773 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2774 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2775 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou6db49442011-12-19 13:27:11 +01002776 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
2777 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002778 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002779#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002780 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002781#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002782#ifdef SSL_OP_NO_COMPRESSION
2783 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
2784 SSL_OP_NO_COMPRESSION);
2785#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00002786
Antoine Pitroud5323212010-10-22 18:19:07 +00002787#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2788 r = Py_True;
2789#else
2790 r = Py_False;
2791#endif
2792 Py_INCREF(r);
2793 PyModule_AddObject(m, "HAS_SNI", r);
2794
Antoine Pitroud6494802011-07-21 01:11:30 +02002795#if HAVE_OPENSSL_FINISHED
2796 r = Py_True;
2797#else
2798 r = Py_False;
2799#endif
2800 Py_INCREF(r);
2801 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2802
Antoine Pitrou501da612011-12-21 09:27:41 +01002803#ifdef OPENSSL_NO_ECDH
2804 r = Py_False;
2805#else
2806 r = Py_True;
2807#endif
2808 Py_INCREF(r);
2809 PyModule_AddObject(m, "HAS_ECDH", r);
2810
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002811#ifdef OPENSSL_NPN_NEGOTIATED
2812 r = Py_True;
2813#else
2814 r = Py_False;
2815#endif
2816 Py_INCREF(r);
2817 PyModule_AddObject(m, "HAS_NPN", r);
2818
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002819 /* Mappings for error codes */
2820 err_codes_to_names = PyDict_New();
2821 err_names_to_codes = PyDict_New();
2822 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
2823 return NULL;
2824 errcode = error_codes;
2825 while (errcode->mnemonic != NULL) {
2826 PyObject *mnemo, *key;
2827 mnemo = PyUnicode_FromString(errcode->mnemonic);
2828 key = Py_BuildValue("ii", errcode->library, errcode->reason);
2829 if (mnemo == NULL || key == NULL)
2830 return NULL;
2831 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
2832 return NULL;
2833 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
2834 return NULL;
2835 Py_DECREF(key);
2836 Py_DECREF(mnemo);
2837 errcode++;
2838 }
2839 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
2840 return NULL;
2841 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
2842 return NULL;
2843
2844 lib_codes_to_names = PyDict_New();
2845 if (lib_codes_to_names == NULL)
2846 return NULL;
2847 libcode = library_codes;
2848 while (libcode->library != NULL) {
2849 PyObject *mnemo, *key;
2850 key = PyLong_FromLong(libcode->code);
2851 mnemo = PyUnicode_FromString(libcode->library);
2852 if (key == NULL || mnemo == NULL)
2853 return NULL;
2854 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
2855 return NULL;
2856 Py_DECREF(key);
2857 Py_DECREF(mnemo);
2858 libcode++;
2859 }
2860 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
2861 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02002862
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002863 /* OpenSSL version */
2864 /* SSLeay() gives us the version of the library linked against,
2865 which could be different from the headers version.
2866 */
2867 libver = SSLeay();
2868 r = PyLong_FromUnsignedLong(libver);
2869 if (r == NULL)
2870 return NULL;
2871 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2872 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002873 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002874 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2875 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2876 return NULL;
2877 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2878 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2879 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002880
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002881 libver = OPENSSL_VERSION_NUMBER;
2882 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2883 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2884 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2885 return NULL;
2886
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002887 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002888}