blob: ebd84d51e12ff315fbad87d5604c189fe5bb352b [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
1267 /* just in case the blocking state of the socket has been changed */
1268 nonblocking = (sock->sock_timeout >= 0.0);
1269 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1270 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1271
1272 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1273 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001274 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001275 "The write operation timed out");
1276 goto error;
1277 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1278 PyErr_SetString(PySSLErrorObject,
1279 "Underlying socket has been closed.");
1280 goto error;
1281 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1282 PyErr_SetString(PySSLErrorObject,
1283 "Underlying socket too large for select().");
1284 goto error;
1285 }
1286 do {
Victor Stinner9ee02032013-06-23 15:08:23 +02001287 len = (int)Py_MIN(buf.len, INT_MAX);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner9ee02032013-06-23 15:08:23 +02001289 len = SSL_write(self->ssl, buf.buf, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 err = SSL_get_error(self->ssl, len);
1291 PySSL_END_ALLOW_THREADS
1292 if (PyErr_CheckSignals()) {
1293 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001294 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001296 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001297 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001298 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001299 } else {
1300 sockstate = SOCKET_OPERATION_OK;
1301 }
1302 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001303 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001304 "The write operation timed out");
1305 goto error;
1306 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1307 PyErr_SetString(PySSLErrorObject,
1308 "Underlying socket has been closed.");
1309 goto error;
1310 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1311 break;
1312 }
1313 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001314
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001315 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001316 PyBuffer_Release(&buf);
1317 if (len > 0)
1318 return PyLong_FromLong(len);
1319 else
1320 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001321
1322error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001323 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001324 PyBuffer_Release(&buf);
1325 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001326}
1327
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001328PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001329"write(s) -> len\n\
1330\n\
1331Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001332of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001333
Antoine Pitrou152efa22010-05-16 18:19:27 +00001334static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001335{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001336 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001337
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 PySSL_BEGIN_ALLOW_THREADS
1339 count = SSL_pending(self->ssl);
1340 PySSL_END_ALLOW_THREADS
1341 if (count < 0)
1342 return PySSL_SetError(self, count, __FILE__, __LINE__);
1343 else
1344 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001345}
1346
1347PyDoc_STRVAR(PySSL_SSLpending_doc,
1348"pending() -> count\n\
1349\n\
1350Returns the number of already decrypted bytes available for read,\n\
1351pending on the connection.\n");
1352
Antoine Pitrou152efa22010-05-16 18:19:27 +00001353static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001354{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001355 PyObject *dest = NULL;
1356 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001357 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001358 int len, count;
1359 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001360 int sockstate;
1361 int err;
1362 int nonblocking;
1363 PySocketSockObject *sock
1364 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001365
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 if (((PyObject*)sock) == Py_None) {
1367 _setSSLError("Underlying socket connection gone",
1368 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1369 return NULL;
1370 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001371 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001372
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001373 buf.obj = NULL;
1374 buf.buf = NULL;
1375 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001376 goto error;
1377
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001378 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1379 dest = PyBytes_FromStringAndSize(NULL, len);
1380 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001381 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001382 mem = PyBytes_AS_STRING(dest);
1383 }
1384 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001385 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001386 mem = buf.buf;
1387 if (len <= 0 || len > buf.len) {
1388 len = (int) buf.len;
1389 if (buf.len != len) {
1390 PyErr_SetString(PyExc_OverflowError,
1391 "maximum length can't fit in a C 'int'");
1392 goto error;
1393 }
1394 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001395 }
1396
1397 /* just in case the blocking state of the socket has been changed */
1398 nonblocking = (sock->sock_timeout >= 0.0);
1399 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1400 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1401
1402 /* first check if there are bytes ready to be read */
1403 PySSL_BEGIN_ALLOW_THREADS
1404 count = SSL_pending(self->ssl);
1405 PySSL_END_ALLOW_THREADS
1406
1407 if (!count) {
1408 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1409 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001410 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411 "The read operation timed out");
1412 goto error;
1413 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1414 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001415 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001416 goto error;
1417 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1418 count = 0;
1419 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001420 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001421 }
1422 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001423 PySSL_BEGIN_ALLOW_THREADS
1424 count = SSL_read(self->ssl, mem, len);
1425 err = SSL_get_error(self->ssl, count);
1426 PySSL_END_ALLOW_THREADS
1427 if (PyErr_CheckSignals())
1428 goto error;
1429 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001430 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001431 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001432 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001433 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1434 (SSL_get_shutdown(self->ssl) ==
1435 SSL_RECEIVED_SHUTDOWN))
1436 {
1437 count = 0;
1438 goto done;
1439 } else {
1440 sockstate = SOCKET_OPERATION_OK;
1441 }
1442 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001443 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001444 "The read operation timed out");
1445 goto error;
1446 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1447 break;
1448 }
1449 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1450 if (count <= 0) {
1451 PySSL_SetError(self, count, __FILE__, __LINE__);
1452 goto error;
1453 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001454
1455done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001456 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001457 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001458 _PyBytes_Resize(&dest, count);
1459 return dest;
1460 }
1461 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001462 PyBuffer_Release(&buf);
1463 return PyLong_FromLong(count);
1464 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001465
1466error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001467 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001468 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001469 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001470 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001471 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001472 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001473}
1474
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001475PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001476"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001477\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001478Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001479
Antoine Pitrou152efa22010-05-16 18:19:27 +00001480static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001481{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001482 int err, ssl_err, sockstate, nonblocking;
1483 int zeros = 0;
1484 PySocketSockObject *sock
1485 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001486
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001487 /* Guard against closed socket */
1488 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1489 _setSSLError("Underlying socket connection gone",
1490 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1491 return NULL;
1492 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001493 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001494
1495 /* Just in case the blocking state of the socket has been changed */
1496 nonblocking = (sock->sock_timeout >= 0.0);
1497 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1498 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1499
1500 while (1) {
1501 PySSL_BEGIN_ALLOW_THREADS
1502 /* Disable read-ahead so that unwrap can work correctly.
1503 * Otherwise OpenSSL might read in too much data,
1504 * eating clear text data that happens to be
1505 * transmitted after the SSL shutdown.
1506 * Should be safe to call repeatedly everytime this
1507 * function is used and the shutdown_seen_zero != 0
1508 * condition is met.
1509 */
1510 if (self->shutdown_seen_zero)
1511 SSL_set_read_ahead(self->ssl, 0);
1512 err = SSL_shutdown(self->ssl);
1513 PySSL_END_ALLOW_THREADS
1514 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1515 if (err > 0)
1516 break;
1517 if (err == 0) {
1518 /* Don't loop endlessly; instead preserve legacy
1519 behaviour of trying SSL_shutdown() only twice.
1520 This looks necessary for OpenSSL < 0.9.8m */
1521 if (++zeros > 1)
1522 break;
1523 /* Shutdown was sent, now try receiving */
1524 self->shutdown_seen_zero = 1;
1525 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001526 }
1527
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 /* Possibly retry shutdown until timeout or failure */
1529 ssl_err = SSL_get_error(self->ssl, err);
1530 if (ssl_err == SSL_ERROR_WANT_READ)
1531 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1532 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1533 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1534 else
1535 break;
1536 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1537 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001538 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001539 "The read operation timed out");
1540 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001541 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001542 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001543 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001544 }
1545 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1546 PyErr_SetString(PySSLErrorObject,
1547 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001548 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001549 }
1550 else if (sockstate != SOCKET_OPERATION_OK)
1551 /* Retain the SSL error code */
1552 break;
1553 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001554
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001555 if (err < 0) {
1556 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001557 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001559 else
1560 /* It's already INCREF'ed */
1561 return (PyObject *) sock;
1562
1563error:
1564 Py_DECREF(sock);
1565 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001566}
1567
1568PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1569"shutdown(s) -> socket\n\
1570\n\
1571Does the SSL shutdown handshake with the remote end, and returns\n\
1572the underlying socket object.");
1573
Antoine Pitroud6494802011-07-21 01:11:30 +02001574#if HAVE_OPENSSL_FINISHED
1575static PyObject *
1576PySSL_tls_unique_cb(PySSLSocket *self)
1577{
1578 PyObject *retval = NULL;
1579 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001580 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001581
1582 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1583 /* if session is resumed XOR we are the client */
1584 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1585 }
1586 else {
1587 /* if a new session XOR we are the server */
1588 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1589 }
1590
1591 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001592 if (len == 0)
1593 Py_RETURN_NONE;
1594
1595 retval = PyBytes_FromStringAndSize(buf, len);
1596
1597 return retval;
1598}
1599
1600PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1601"tls_unique_cb() -> bytes\n\
1602\n\
1603Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1604\n\
1605If the TLS handshake is not yet complete, None is returned");
1606
1607#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001608
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001609static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001610 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1611 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1612 PySSL_SSLwrite_doc},
1613 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1614 PySSL_SSLread_doc},
1615 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1616 PySSL_SSLpending_doc},
1617 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1618 PySSL_peercert_doc},
1619 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001620#ifdef OPENSSL_NPN_NEGOTIATED
1621 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1622#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001623 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001624 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1625 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001626#if HAVE_OPENSSL_FINISHED
1627 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1628 PySSL_tls_unique_cb_doc},
1629#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001630 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001631};
1632
Antoine Pitrou152efa22010-05-16 18:19:27 +00001633static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001634 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001635 "_ssl._SSLSocket", /*tp_name*/
1636 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001637 0, /*tp_itemsize*/
1638 /* methods */
1639 (destructor)PySSL_dealloc, /*tp_dealloc*/
1640 0, /*tp_print*/
1641 0, /*tp_getattr*/
1642 0, /*tp_setattr*/
1643 0, /*tp_reserved*/
1644 0, /*tp_repr*/
1645 0, /*tp_as_number*/
1646 0, /*tp_as_sequence*/
1647 0, /*tp_as_mapping*/
1648 0, /*tp_hash*/
1649 0, /*tp_call*/
1650 0, /*tp_str*/
1651 0, /*tp_getattro*/
1652 0, /*tp_setattro*/
1653 0, /*tp_as_buffer*/
1654 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1655 0, /*tp_doc*/
1656 0, /*tp_traverse*/
1657 0, /*tp_clear*/
1658 0, /*tp_richcompare*/
1659 0, /*tp_weaklistoffset*/
1660 0, /*tp_iter*/
1661 0, /*tp_iternext*/
1662 PySSLMethods, /*tp_methods*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001663};
1664
Antoine Pitrou152efa22010-05-16 18:19:27 +00001665
1666/*
1667 * _SSLContext objects
1668 */
1669
1670static PyObject *
1671context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1672{
1673 char *kwlist[] = {"protocol", NULL};
1674 PySSLContext *self;
1675 int proto_version = PY_SSL_VERSION_SSL23;
1676 SSL_CTX *ctx = NULL;
1677
1678 if (!PyArg_ParseTupleAndKeywords(
1679 args, kwds, "i:_SSLContext", kwlist,
1680 &proto_version))
1681 return NULL;
1682
1683 PySSL_BEGIN_ALLOW_THREADS
1684 if (proto_version == PY_SSL_VERSION_TLS1)
1685 ctx = SSL_CTX_new(TLSv1_method());
1686 else if (proto_version == PY_SSL_VERSION_SSL3)
1687 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001688#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001689 else if (proto_version == PY_SSL_VERSION_SSL2)
1690 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001691#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001692 else if (proto_version == PY_SSL_VERSION_SSL23)
1693 ctx = SSL_CTX_new(SSLv23_method());
1694 else
1695 proto_version = -1;
1696 PySSL_END_ALLOW_THREADS
1697
1698 if (proto_version == -1) {
1699 PyErr_SetString(PyExc_ValueError,
1700 "invalid protocol version");
1701 return NULL;
1702 }
1703 if (ctx == NULL) {
1704 PyErr_SetString(PySSLErrorObject,
1705 "failed to allocate SSL context");
1706 return NULL;
1707 }
1708
1709 assert(type != NULL && type->tp_alloc != NULL);
1710 self = (PySSLContext *) type->tp_alloc(type, 0);
1711 if (self == NULL) {
1712 SSL_CTX_free(ctx);
1713 return NULL;
1714 }
1715 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001716#ifdef OPENSSL_NPN_NEGOTIATED
1717 self->npn_protocols = NULL;
1718#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001719 /* Defaults */
1720 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001721 SSL_CTX_set_options(self->ctx,
1722 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001723
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001724#define SID_CTX "Python"
1725 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1726 sizeof(SID_CTX));
1727#undef SID_CTX
1728
Antoine Pitrou152efa22010-05-16 18:19:27 +00001729 return (PyObject *)self;
1730}
1731
1732static void
1733context_dealloc(PySSLContext *self)
1734{
1735 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001736#ifdef OPENSSL_NPN_NEGOTIATED
1737 PyMem_Free(self->npn_protocols);
1738#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001739 Py_TYPE(self)->tp_free(self);
1740}
1741
1742static PyObject *
1743set_ciphers(PySSLContext *self, PyObject *args)
1744{
1745 int ret;
1746 const char *cipherlist;
1747
1748 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1749 return NULL;
1750 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1751 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001752 /* Clearing the error queue is necessary on some OpenSSL versions,
1753 otherwise the error will be reported again when another SSL call
1754 is done. */
1755 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001756 PyErr_SetString(PySSLErrorObject,
1757 "No cipher can be selected.");
1758 return NULL;
1759 }
1760 Py_RETURN_NONE;
1761}
1762
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001763#ifdef OPENSSL_NPN_NEGOTIATED
1764/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1765static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001766_advertiseNPN_cb(SSL *s,
1767 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001768 void *args)
1769{
1770 PySSLContext *ssl_ctx = (PySSLContext *) args;
1771
1772 if (ssl_ctx->npn_protocols == NULL) {
1773 *data = (unsigned char *) "";
1774 *len = 0;
1775 } else {
1776 *data = (unsigned char *) ssl_ctx->npn_protocols;
1777 *len = ssl_ctx->npn_protocols_len;
1778 }
1779
1780 return SSL_TLSEXT_ERR_OK;
1781}
1782/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1783static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001784_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001785 unsigned char **out, unsigned char *outlen,
1786 const unsigned char *server, unsigned int server_len,
1787 void *args)
1788{
1789 PySSLContext *ssl_ctx = (PySSLContext *) args;
1790
1791 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1792 int client_len;
1793
1794 if (client == NULL) {
1795 client = (unsigned char *) "";
1796 client_len = 0;
1797 } else {
1798 client_len = ssl_ctx->npn_protocols_len;
1799 }
1800
1801 SSL_select_next_proto(out, outlen,
1802 server, server_len,
1803 client, client_len);
1804
1805 return SSL_TLSEXT_ERR_OK;
1806}
1807#endif
1808
1809static PyObject *
1810_set_npn_protocols(PySSLContext *self, PyObject *args)
1811{
1812#ifdef OPENSSL_NPN_NEGOTIATED
1813 Py_buffer protos;
1814
1815 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1816 return NULL;
1817
Christian Heimes5cb31c92012-09-20 12:42:54 +02001818 if (self->npn_protocols != NULL) {
1819 PyMem_Free(self->npn_protocols);
1820 }
1821
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001822 self->npn_protocols = PyMem_Malloc(protos.len);
1823 if (self->npn_protocols == NULL) {
1824 PyBuffer_Release(&protos);
1825 return PyErr_NoMemory();
1826 }
1827 memcpy(self->npn_protocols, protos.buf, protos.len);
1828 self->npn_protocols_len = (int) protos.len;
1829
1830 /* set both server and client callbacks, because the context can
1831 * be used to create both types of sockets */
1832 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
1833 _advertiseNPN_cb,
1834 self);
1835 SSL_CTX_set_next_proto_select_cb(self->ctx,
1836 _selectNPN_cb,
1837 self);
1838
1839 PyBuffer_Release(&protos);
1840 Py_RETURN_NONE;
1841#else
1842 PyErr_SetString(PyExc_NotImplementedError,
1843 "The NPN extension requires OpenSSL 1.0.1 or later.");
1844 return NULL;
1845#endif
1846}
1847
Antoine Pitrou152efa22010-05-16 18:19:27 +00001848static PyObject *
1849get_verify_mode(PySSLContext *self, void *c)
1850{
1851 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1852 case SSL_VERIFY_NONE:
1853 return PyLong_FromLong(PY_SSL_CERT_NONE);
1854 case SSL_VERIFY_PEER:
1855 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1856 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1857 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1858 }
1859 PyErr_SetString(PySSLErrorObject,
1860 "invalid return value from SSL_CTX_get_verify_mode");
1861 return NULL;
1862}
1863
1864static int
1865set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1866{
1867 int n, mode;
1868 if (!PyArg_Parse(arg, "i", &n))
1869 return -1;
1870 if (n == PY_SSL_CERT_NONE)
1871 mode = SSL_VERIFY_NONE;
1872 else if (n == PY_SSL_CERT_OPTIONAL)
1873 mode = SSL_VERIFY_PEER;
1874 else if (n == PY_SSL_CERT_REQUIRED)
1875 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1876 else {
1877 PyErr_SetString(PyExc_ValueError,
1878 "invalid value for verify_mode");
1879 return -1;
1880 }
1881 SSL_CTX_set_verify(self->ctx, mode, NULL);
1882 return 0;
1883}
1884
1885static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001886get_options(PySSLContext *self, void *c)
1887{
1888 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1889}
1890
1891static int
1892set_options(PySSLContext *self, PyObject *arg, void *c)
1893{
1894 long new_opts, opts, set, clear;
1895 if (!PyArg_Parse(arg, "l", &new_opts))
1896 return -1;
1897 opts = SSL_CTX_get_options(self->ctx);
1898 clear = opts & ~new_opts;
1899 set = ~opts & new_opts;
1900 if (clear) {
1901#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1902 SSL_CTX_clear_options(self->ctx, clear);
1903#else
1904 PyErr_SetString(PyExc_ValueError,
1905 "can't clear options before OpenSSL 0.9.8m");
1906 return -1;
1907#endif
1908 }
1909 if (set)
1910 SSL_CTX_set_options(self->ctx, set);
1911 return 0;
1912}
1913
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001914typedef struct {
1915 PyThreadState *thread_state;
1916 PyObject *callable;
1917 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02001918 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001919 int error;
1920} _PySSLPasswordInfo;
1921
1922static int
1923_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1924 const char *bad_type_error)
1925{
1926 /* Set the password and size fields of a _PySSLPasswordInfo struct
1927 from a unicode, bytes, or byte array object.
1928 The password field will be dynamically allocated and must be freed
1929 by the caller */
1930 PyObject *password_bytes = NULL;
1931 const char *data = NULL;
1932 Py_ssize_t size;
1933
1934 if (PyUnicode_Check(password)) {
1935 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
1936 if (!password_bytes) {
1937 goto error;
1938 }
1939 data = PyBytes_AS_STRING(password_bytes);
1940 size = PyBytes_GET_SIZE(password_bytes);
1941 } else if (PyBytes_Check(password)) {
1942 data = PyBytes_AS_STRING(password);
1943 size = PyBytes_GET_SIZE(password);
1944 } else if (PyByteArray_Check(password)) {
1945 data = PyByteArray_AS_STRING(password);
1946 size = PyByteArray_GET_SIZE(password);
1947 } else {
1948 PyErr_SetString(PyExc_TypeError, bad_type_error);
1949 goto error;
1950 }
1951
Victor Stinner9ee02032013-06-23 15:08:23 +02001952 if (size > (Py_ssize_t)INT_MAX) {
1953 PyErr_Format(PyExc_ValueError,
1954 "password cannot be longer than %d bytes", INT_MAX);
1955 goto error;
1956 }
1957
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001958 free(pw_info->password);
1959 pw_info->password = malloc(size);
1960 if (!pw_info->password) {
1961 PyErr_SetString(PyExc_MemoryError,
1962 "unable to allocate password buffer");
1963 goto error;
1964 }
1965 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02001966 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001967
1968 Py_XDECREF(password_bytes);
1969 return 1;
1970
1971error:
1972 Py_XDECREF(password_bytes);
1973 return 0;
1974}
1975
1976static int
1977_password_callback(char *buf, int size, int rwflag, void *userdata)
1978{
1979 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
1980 PyObject *fn_ret = NULL;
1981
1982 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
1983
1984 if (pw_info->callable) {
1985 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
1986 if (!fn_ret) {
1987 /* TODO: It would be nice to move _ctypes_add_traceback() into the
1988 core python API, so we could use it to add a frame here */
1989 goto error;
1990 }
1991
1992 if (!_pwinfo_set(pw_info, fn_ret,
1993 "password callback must return a string")) {
1994 goto error;
1995 }
1996 Py_CLEAR(fn_ret);
1997 }
1998
1999 if (pw_info->size > size) {
2000 PyErr_Format(PyExc_ValueError,
2001 "password cannot be longer than %d bytes", size);
2002 goto error;
2003 }
2004
2005 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2006 memcpy(buf, pw_info->password, pw_info->size);
2007 return pw_info->size;
2008
2009error:
2010 Py_XDECREF(fn_ret);
2011 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2012 pw_info->error = 1;
2013 return -1;
2014}
2015
Antoine Pitroub5218772010-05-21 09:56:06 +00002016static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002017load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2018{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002019 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2020 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002021 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002022 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2023 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2024 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002025 int r;
2026
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002027 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002028 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002029 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002030 "O|OO:load_cert_chain", kwlist,
2031 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002032 return NULL;
2033 if (keyfile == Py_None)
2034 keyfile = NULL;
2035 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2036 PyErr_SetString(PyExc_TypeError,
2037 "certfile should be a valid filesystem path");
2038 return NULL;
2039 }
2040 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2041 PyErr_SetString(PyExc_TypeError,
2042 "keyfile should be a valid filesystem path");
2043 goto error;
2044 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002045 if (password && password != Py_None) {
2046 if (PyCallable_Check(password)) {
2047 pw_info.callable = password;
2048 } else if (!_pwinfo_set(&pw_info, password,
2049 "password should be a string or callable")) {
2050 goto error;
2051 }
2052 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2053 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2054 }
2055 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002056 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2057 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002058 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002059 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002060 if (pw_info.error) {
2061 ERR_clear_error();
2062 /* the password callback has already set the error information */
2063 }
2064 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002065 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002066 PyErr_SetFromErrno(PyExc_IOError);
2067 }
2068 else {
2069 _setSSLError(NULL, 0, __FILE__, __LINE__);
2070 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002071 goto error;
2072 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002073 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002074 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002075 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2076 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002077 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2078 Py_CLEAR(keyfile_bytes);
2079 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002080 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002081 if (pw_info.error) {
2082 ERR_clear_error();
2083 /* the password callback has already set the error information */
2084 }
2085 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002086 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002087 PyErr_SetFromErrno(PyExc_IOError);
2088 }
2089 else {
2090 _setSSLError(NULL, 0, __FILE__, __LINE__);
2091 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002092 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002093 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002094 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002095 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002096 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002097 if (r != 1) {
2098 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002099 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002100 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002101 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2102 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2103 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002104 Py_RETURN_NONE;
2105
2106error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002107 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2108 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2109 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002110 Py_XDECREF(keyfile_bytes);
2111 Py_XDECREF(certfile_bytes);
2112 return NULL;
2113}
2114
2115static PyObject *
2116load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2117{
2118 char *kwlist[] = {"cafile", "capath", NULL};
2119 PyObject *cafile = NULL, *capath = NULL;
2120 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2121 const char *cafile_buf = NULL, *capath_buf = NULL;
2122 int r;
2123
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002124 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002125 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2126 "|OO:load_verify_locations", kwlist,
2127 &cafile, &capath))
2128 return NULL;
2129 if (cafile == Py_None)
2130 cafile = NULL;
2131 if (capath == Py_None)
2132 capath = NULL;
2133 if (cafile == NULL && capath == NULL) {
2134 PyErr_SetString(PyExc_TypeError,
2135 "cafile and capath cannot be both omitted");
2136 return NULL;
2137 }
2138 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2139 PyErr_SetString(PyExc_TypeError,
2140 "cafile should be a valid filesystem path");
2141 return NULL;
2142 }
2143 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002144 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002145 PyErr_SetString(PyExc_TypeError,
2146 "capath should be a valid filesystem path");
2147 return NULL;
2148 }
2149 if (cafile)
2150 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2151 if (capath)
2152 capath_buf = PyBytes_AS_STRING(capath_bytes);
2153 PySSL_BEGIN_ALLOW_THREADS
2154 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2155 PySSL_END_ALLOW_THREADS
2156 Py_XDECREF(cafile_bytes);
2157 Py_XDECREF(capath_bytes);
2158 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002159 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002160 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002161 PyErr_SetFromErrno(PyExc_IOError);
2162 }
2163 else {
2164 _setSSLError(NULL, 0, __FILE__, __LINE__);
2165 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002166 return NULL;
2167 }
2168 Py_RETURN_NONE;
2169}
2170
2171static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002172load_dh_params(PySSLContext *self, PyObject *filepath)
2173{
2174 FILE *f;
2175 DH *dh;
2176
2177 f = _Py_fopen(filepath, "rb");
2178 if (f == NULL) {
2179 if (!PyErr_Occurred())
2180 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2181 return NULL;
2182 }
2183 errno = 0;
2184 PySSL_BEGIN_ALLOW_THREADS
2185 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002186 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002187 PySSL_END_ALLOW_THREADS
2188 if (dh == NULL) {
2189 if (errno != 0) {
2190 ERR_clear_error();
2191 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2192 }
2193 else {
2194 _setSSLError(NULL, 0, __FILE__, __LINE__);
2195 }
2196 return NULL;
2197 }
2198 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2199 _setSSLError(NULL, 0, __FILE__, __LINE__);
2200 DH_free(dh);
2201 Py_RETURN_NONE;
2202}
2203
2204static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002205context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2206{
Antoine Pitroud5323212010-10-22 18:19:07 +00002207 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002208 PySocketSockObject *sock;
2209 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002210 char *hostname = NULL;
2211 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002212
Antoine Pitroud5323212010-10-22 18:19:07 +00002213 /* server_hostname is either None (or absent), or to be encoded
2214 using the idna encoding. */
2215 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002216 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002217 &sock, &server_side,
2218 Py_TYPE(Py_None), &hostname_obj)) {
2219 PyErr_Clear();
2220 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2221 PySocketModule.Sock_Type,
2222 &sock, &server_side,
2223 "idna", &hostname))
2224 return NULL;
2225#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
2226 PyMem_Free(hostname);
2227 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2228 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002229 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002230#endif
2231 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002232
Antoine Pitroud5323212010-10-22 18:19:07 +00002233 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
2234 hostname);
2235 if (hostname != NULL)
2236 PyMem_Free(hostname);
2237 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002238}
2239
Antoine Pitroub0182c82010-10-12 20:09:02 +00002240static PyObject *
2241session_stats(PySSLContext *self, PyObject *unused)
2242{
2243 int r;
2244 PyObject *value, *stats = PyDict_New();
2245 if (!stats)
2246 return NULL;
2247
2248#define ADD_STATS(SSL_NAME, KEY_NAME) \
2249 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2250 if (value == NULL) \
2251 goto error; \
2252 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2253 Py_DECREF(value); \
2254 if (r < 0) \
2255 goto error;
2256
2257 ADD_STATS(number, "number");
2258 ADD_STATS(connect, "connect");
2259 ADD_STATS(connect_good, "connect_good");
2260 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2261 ADD_STATS(accept, "accept");
2262 ADD_STATS(accept_good, "accept_good");
2263 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2264 ADD_STATS(accept, "accept");
2265 ADD_STATS(hits, "hits");
2266 ADD_STATS(misses, "misses");
2267 ADD_STATS(timeouts, "timeouts");
2268 ADD_STATS(cache_full, "cache_full");
2269
2270#undef ADD_STATS
2271
2272 return stats;
2273
2274error:
2275 Py_DECREF(stats);
2276 return NULL;
2277}
2278
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002279static PyObject *
2280set_default_verify_paths(PySSLContext *self, PyObject *unused)
2281{
2282 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2283 _setSSLError(NULL, 0, __FILE__, __LINE__);
2284 return NULL;
2285 }
2286 Py_RETURN_NONE;
2287}
2288
Antoine Pitrou501da612011-12-21 09:27:41 +01002289#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002290static PyObject *
2291set_ecdh_curve(PySSLContext *self, PyObject *name)
2292{
2293 PyObject *name_bytes;
2294 int nid;
2295 EC_KEY *key;
2296
2297 if (!PyUnicode_FSConverter(name, &name_bytes))
2298 return NULL;
2299 assert(PyBytes_Check(name_bytes));
2300 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2301 Py_DECREF(name_bytes);
2302 if (nid == 0) {
2303 PyErr_Format(PyExc_ValueError,
2304 "unknown elliptic curve name %R", name);
2305 return NULL;
2306 }
2307 key = EC_KEY_new_by_curve_name(nid);
2308 if (key == NULL) {
2309 _setSSLError(NULL, 0, __FILE__, __LINE__);
2310 return NULL;
2311 }
2312 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2313 EC_KEY_free(key);
2314 Py_RETURN_NONE;
2315}
Antoine Pitrou501da612011-12-21 09:27:41 +01002316#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002317
Antoine Pitrou152efa22010-05-16 18:19:27 +00002318static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002319 {"options", (getter) get_options,
2320 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002321 {"verify_mode", (getter) get_verify_mode,
2322 (setter) set_verify_mode, NULL},
2323 {NULL}, /* sentinel */
2324};
2325
2326static struct PyMethodDef context_methods[] = {
2327 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2328 METH_VARARGS | METH_KEYWORDS, NULL},
2329 {"set_ciphers", (PyCFunction) set_ciphers,
2330 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002331 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2332 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002333 {"load_cert_chain", (PyCFunction) load_cert_chain,
2334 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002335 {"load_dh_params", (PyCFunction) load_dh_params,
2336 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002337 {"load_verify_locations", (PyCFunction) load_verify_locations,
2338 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002339 {"session_stats", (PyCFunction) session_stats,
2340 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002341 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2342 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002343#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002344 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2345 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002346#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002347 {NULL, NULL} /* sentinel */
2348};
2349
2350static PyTypeObject PySSLContext_Type = {
2351 PyVarObject_HEAD_INIT(NULL, 0)
2352 "_ssl._SSLContext", /*tp_name*/
2353 sizeof(PySSLContext), /*tp_basicsize*/
2354 0, /*tp_itemsize*/
2355 (destructor)context_dealloc, /*tp_dealloc*/
2356 0, /*tp_print*/
2357 0, /*tp_getattr*/
2358 0, /*tp_setattr*/
2359 0, /*tp_reserved*/
2360 0, /*tp_repr*/
2361 0, /*tp_as_number*/
2362 0, /*tp_as_sequence*/
2363 0, /*tp_as_mapping*/
2364 0, /*tp_hash*/
2365 0, /*tp_call*/
2366 0, /*tp_str*/
2367 0, /*tp_getattro*/
2368 0, /*tp_setattro*/
2369 0, /*tp_as_buffer*/
2370 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2371 0, /*tp_doc*/
2372 0, /*tp_traverse*/
2373 0, /*tp_clear*/
2374 0, /*tp_richcompare*/
2375 0, /*tp_weaklistoffset*/
2376 0, /*tp_iter*/
2377 0, /*tp_iternext*/
2378 context_methods, /*tp_methods*/
2379 0, /*tp_members*/
2380 context_getsetlist, /*tp_getset*/
2381 0, /*tp_base*/
2382 0, /*tp_dict*/
2383 0, /*tp_descr_get*/
2384 0, /*tp_descr_set*/
2385 0, /*tp_dictoffset*/
2386 0, /*tp_init*/
2387 0, /*tp_alloc*/
2388 context_new, /*tp_new*/
2389};
2390
2391
2392
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002393#ifdef HAVE_OPENSSL_RAND
2394
2395/* helper routines for seeding the SSL PRNG */
2396static PyObject *
2397PySSL_RAND_add(PyObject *self, PyObject *args)
2398{
2399 char *buf;
2400 int len;
2401 double entropy;
2402
2403 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002404 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002405 RAND_add(buf, len, entropy);
2406 Py_INCREF(Py_None);
2407 return Py_None;
2408}
2409
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002410PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002411"RAND_add(string, entropy)\n\
2412\n\
2413Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002414bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002415
2416static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002417PySSL_RAND(int len, int pseudo)
2418{
2419 int ok;
2420 PyObject *bytes;
2421 unsigned long err;
2422 const char *errstr;
2423 PyObject *v;
2424
2425 bytes = PyBytes_FromStringAndSize(NULL, len);
2426 if (bytes == NULL)
2427 return NULL;
2428 if (pseudo) {
2429 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2430 if (ok == 0 || ok == 1)
2431 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2432 }
2433 else {
2434 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2435 if (ok == 1)
2436 return bytes;
2437 }
2438 Py_DECREF(bytes);
2439
2440 err = ERR_get_error();
2441 errstr = ERR_reason_error_string(err);
2442 v = Py_BuildValue("(ks)", err, errstr);
2443 if (v != NULL) {
2444 PyErr_SetObject(PySSLErrorObject, v);
2445 Py_DECREF(v);
2446 }
2447 return NULL;
2448}
2449
2450static PyObject *
2451PySSL_RAND_bytes(PyObject *self, PyObject *args)
2452{
2453 int len;
2454 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2455 return NULL;
2456 return PySSL_RAND(len, 0);
2457}
2458
2459PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2460"RAND_bytes(n) -> bytes\n\
2461\n\
2462Generate n cryptographically strong pseudo-random bytes.");
2463
2464static PyObject *
2465PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2466{
2467 int len;
2468 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2469 return NULL;
2470 return PySSL_RAND(len, 1);
2471}
2472
2473PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2474"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2475\n\
2476Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2477generated are cryptographically strong.");
2478
2479static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002480PySSL_RAND_status(PyObject *self)
2481{
Christian Heimes217cfd12007-12-02 14:31:20 +00002482 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002483}
2484
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002485PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002486"RAND_status() -> 0 or 1\n\
2487\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002488Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2489It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2490using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002491
2492static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002493PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002494{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002495 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002496 int bytes;
2497
Jesus Ceac8754a12012-09-11 02:00:58 +02002498 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002499 PyUnicode_FSConverter, &path))
2500 return NULL;
2501
2502 bytes = RAND_egd(PyBytes_AsString(path));
2503 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002504 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002505 PyErr_SetString(PySSLErrorObject,
2506 "EGD connection failed or EGD did not return "
2507 "enough data to seed the PRNG");
2508 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002509 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002510 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002511}
2512
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002513PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002514"RAND_egd(path) -> bytes\n\
2515\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002516Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2517Returns number of bytes read. Raises SSLError if connection to EGD\n\
2518fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002519
2520#endif
2521
Bill Janssen40a0f662008-08-12 16:56:25 +00002522
2523
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002524/* List of functions exported by this module. */
2525
2526static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002527 {"_test_decode_cert", PySSL_test_decode_certificate,
2528 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002529#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002530 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2531 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002532 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2533 PySSL_RAND_bytes_doc},
2534 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2535 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002536 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002537 PySSL_RAND_egd_doc},
2538 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2539 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002540#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002541 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002542};
2543
2544
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002545#ifdef WITH_THREAD
2546
2547/* an implementation of OpenSSL threading operations in terms
2548 of the Python C thread library */
2549
2550static PyThread_type_lock *_ssl_locks = NULL;
2551
2552static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002553 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002554}
2555
Bill Janssen6e027db2007-11-15 22:23:56 +00002556static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002557 (int mode, int n, const char *file, int line) {
2558 /* this function is needed to perform locking on shared data
2559 structures. (Note that OpenSSL uses a number of global data
2560 structures that will be implicitly shared whenever multiple
2561 threads use OpenSSL.) Multi-threaded applications will
2562 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002563
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002564 locking_function() must be able to handle up to
2565 CRYPTO_num_locks() different mutex locks. It sets the n-th
2566 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002568 file and line are the file number of the function setting the
2569 lock. They can be useful for debugging.
2570 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002571
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002572 if ((_ssl_locks == NULL) ||
2573 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2574 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002575
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002576 if (mode & CRYPTO_LOCK) {
2577 PyThread_acquire_lock(_ssl_locks[n], 1);
2578 } else {
2579 PyThread_release_lock(_ssl_locks[n]);
2580 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002581}
2582
2583static int _setup_ssl_threads(void) {
2584
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002585 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002586
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002587 if (_ssl_locks == NULL) {
2588 _ssl_locks_count = CRYPTO_num_locks();
2589 _ssl_locks = (PyThread_type_lock *)
2590 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2591 if (_ssl_locks == NULL)
2592 return 0;
2593 memset(_ssl_locks, 0,
2594 sizeof(PyThread_type_lock) * _ssl_locks_count);
2595 for (i = 0; i < _ssl_locks_count; i++) {
2596 _ssl_locks[i] = PyThread_allocate_lock();
2597 if (_ssl_locks[i] == NULL) {
2598 unsigned int j;
2599 for (j = 0; j < i; j++) {
2600 PyThread_free_lock(_ssl_locks[j]);
2601 }
2602 free(_ssl_locks);
2603 return 0;
2604 }
2605 }
2606 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2607 CRYPTO_set_id_callback(_ssl_thread_id_function);
2608 }
2609 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002610}
2611
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002612#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002613
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002614PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002615"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002616for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002617
Martin v. Löwis1a214512008-06-11 05:26:20 +00002618
2619static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002620 PyModuleDef_HEAD_INIT,
2621 "_ssl",
2622 module_doc,
2623 -1,
2624 PySSL_methods,
2625 NULL,
2626 NULL,
2627 NULL,
2628 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002629};
2630
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002631
2632static void
2633parse_openssl_version(unsigned long libver,
2634 unsigned int *major, unsigned int *minor,
2635 unsigned int *fix, unsigned int *patch,
2636 unsigned int *status)
2637{
2638 *status = libver & 0xF;
2639 libver >>= 4;
2640 *patch = libver & 0xFF;
2641 libver >>= 8;
2642 *fix = libver & 0xFF;
2643 libver >>= 8;
2644 *minor = libver & 0xFF;
2645 libver >>= 8;
2646 *major = libver & 0xFF;
2647}
2648
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002649PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002650PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002651{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002652 PyObject *m, *d, *r;
2653 unsigned long libver;
2654 unsigned int major, minor, fix, patch, status;
2655 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002656 struct py_ssl_error_code *errcode;
2657 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002658
Antoine Pitrou152efa22010-05-16 18:19:27 +00002659 if (PyType_Ready(&PySSLContext_Type) < 0)
2660 return NULL;
2661 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002662 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002663
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002664 m = PyModule_Create(&_sslmodule);
2665 if (m == NULL)
2666 return NULL;
2667 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002668
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002669 /* Load _socket module and its C API */
2670 socket_api = PySocketModule_ImportModuleAndAPI();
2671 if (!socket_api)
2672 return NULL;
2673 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002674
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002675 /* Init OpenSSL */
2676 SSL_load_error_strings();
2677 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002678#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002679 /* note that this will start threading if not already started */
2680 if (!_setup_ssl_threads()) {
2681 return NULL;
2682 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002683#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002684 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002685
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002686 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002687 sslerror_type_slots[0].pfunc = PyExc_OSError;
2688 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002689 if (PySSLErrorObject == NULL)
2690 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002691
Antoine Pitrou41032a62011-10-27 23:56:55 +02002692 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2693 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2694 PySSLErrorObject, NULL);
2695 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2696 "ssl.SSLWantReadError", SSLWantReadError_doc,
2697 PySSLErrorObject, NULL);
2698 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2699 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2700 PySSLErrorObject, NULL);
2701 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2702 "ssl.SSLSyscallError", SSLSyscallError_doc,
2703 PySSLErrorObject, NULL);
2704 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2705 "ssl.SSLEOFError", SSLEOFError_doc,
2706 PySSLErrorObject, NULL);
2707 if (PySSLZeroReturnErrorObject == NULL
2708 || PySSLWantReadErrorObject == NULL
2709 || PySSLWantWriteErrorObject == NULL
2710 || PySSLSyscallErrorObject == NULL
2711 || PySSLEOFErrorObject == NULL)
2712 return NULL;
2713 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2714 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2715 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2716 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2717 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2718 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002719 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002720 if (PyDict_SetItemString(d, "_SSLContext",
2721 (PyObject *)&PySSLContext_Type) != 0)
2722 return NULL;
2723 if (PyDict_SetItemString(d, "_SSLSocket",
2724 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002725 return NULL;
2726 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2727 PY_SSL_ERROR_ZERO_RETURN);
2728 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2729 PY_SSL_ERROR_WANT_READ);
2730 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2731 PY_SSL_ERROR_WANT_WRITE);
2732 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2733 PY_SSL_ERROR_WANT_X509_LOOKUP);
2734 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2735 PY_SSL_ERROR_SYSCALL);
2736 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2737 PY_SSL_ERROR_SSL);
2738 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2739 PY_SSL_ERROR_WANT_CONNECT);
2740 /* non ssl.h errorcodes */
2741 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2742 PY_SSL_ERROR_EOF);
2743 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2744 PY_SSL_ERROR_INVALID_ERROR_CODE);
2745 /* cert requirements */
2746 PyModule_AddIntConstant(m, "CERT_NONE",
2747 PY_SSL_CERT_NONE);
2748 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2749 PY_SSL_CERT_OPTIONAL);
2750 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2751 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002752
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002753 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002754#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002755 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2756 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002757#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002758 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2759 PY_SSL_VERSION_SSL3);
2760 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2761 PY_SSL_VERSION_SSL23);
2762 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2763 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002764
Antoine Pitroub5218772010-05-21 09:56:06 +00002765 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01002766 PyModule_AddIntConstant(m, "OP_ALL",
2767 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00002768 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2769 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2770 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou6db49442011-12-19 13:27:11 +01002771 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
2772 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002773 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002774#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002775 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002776#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002777#ifdef SSL_OP_NO_COMPRESSION
2778 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
2779 SSL_OP_NO_COMPRESSION);
2780#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00002781
Antoine Pitroud5323212010-10-22 18:19:07 +00002782#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2783 r = Py_True;
2784#else
2785 r = Py_False;
2786#endif
2787 Py_INCREF(r);
2788 PyModule_AddObject(m, "HAS_SNI", r);
2789
Antoine Pitroud6494802011-07-21 01:11:30 +02002790#if HAVE_OPENSSL_FINISHED
2791 r = Py_True;
2792#else
2793 r = Py_False;
2794#endif
2795 Py_INCREF(r);
2796 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2797
Antoine Pitrou501da612011-12-21 09:27:41 +01002798#ifdef OPENSSL_NO_ECDH
2799 r = Py_False;
2800#else
2801 r = Py_True;
2802#endif
2803 Py_INCREF(r);
2804 PyModule_AddObject(m, "HAS_ECDH", r);
2805
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002806#ifdef OPENSSL_NPN_NEGOTIATED
2807 r = Py_True;
2808#else
2809 r = Py_False;
2810#endif
2811 Py_INCREF(r);
2812 PyModule_AddObject(m, "HAS_NPN", r);
2813
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002814 /* Mappings for error codes */
2815 err_codes_to_names = PyDict_New();
2816 err_names_to_codes = PyDict_New();
2817 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
2818 return NULL;
2819 errcode = error_codes;
2820 while (errcode->mnemonic != NULL) {
2821 PyObject *mnemo, *key;
2822 mnemo = PyUnicode_FromString(errcode->mnemonic);
2823 key = Py_BuildValue("ii", errcode->library, errcode->reason);
2824 if (mnemo == NULL || key == NULL)
2825 return NULL;
2826 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
2827 return NULL;
2828 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
2829 return NULL;
2830 Py_DECREF(key);
2831 Py_DECREF(mnemo);
2832 errcode++;
2833 }
2834 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
2835 return NULL;
2836 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
2837 return NULL;
2838
2839 lib_codes_to_names = PyDict_New();
2840 if (lib_codes_to_names == NULL)
2841 return NULL;
2842 libcode = library_codes;
2843 while (libcode->library != NULL) {
2844 PyObject *mnemo, *key;
2845 key = PyLong_FromLong(libcode->code);
2846 mnemo = PyUnicode_FromString(libcode->library);
2847 if (key == NULL || mnemo == NULL)
2848 return NULL;
2849 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
2850 return NULL;
2851 Py_DECREF(key);
2852 Py_DECREF(mnemo);
2853 libcode++;
2854 }
2855 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
2856 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02002857
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002858 /* OpenSSL version */
2859 /* SSLeay() gives us the version of the library linked against,
2860 which could be different from the headers version.
2861 */
2862 libver = SSLeay();
2863 r = PyLong_FromUnsignedLong(libver);
2864 if (r == NULL)
2865 return NULL;
2866 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2867 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002868 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002869 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2870 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2871 return NULL;
2872 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2873 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2874 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002875
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002876 libver = OPENSSL_VERSION_NUMBER;
2877 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2878 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2879 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2880 return NULL;
2881
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002882 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002883}