blob: abb48b976afd2fde7e48e33a857086ae571a8abb [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
1139 SSL_get0_next_proto_negotiated(self->ssl,
1140 &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 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 PySSL_BEGIN_ALLOW_THREADS
1288 len = SSL_write(self->ssl, buf.buf, buf.len);
1289 err = SSL_get_error(self->ssl, len);
1290 PySSL_END_ALLOW_THREADS
1291 if (PyErr_CheckSignals()) {
1292 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001293 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001294 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001295 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001296 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001297 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001298 } else {
1299 sockstate = SOCKET_OPERATION_OK;
1300 }
1301 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001302 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001303 "The write operation timed out");
1304 goto error;
1305 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1306 PyErr_SetString(PySSLErrorObject,
1307 "Underlying socket has been closed.");
1308 goto error;
1309 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1310 break;
1311 }
1312 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001313
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001314 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001315 PyBuffer_Release(&buf);
1316 if (len > 0)
1317 return PyLong_FromLong(len);
1318 else
1319 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001320
1321error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001322 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001323 PyBuffer_Release(&buf);
1324 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001325}
1326
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001327PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001328"write(s) -> len\n\
1329\n\
1330Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001331of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001332
Antoine Pitrou152efa22010-05-16 18:19:27 +00001333static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001334{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001335 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001336
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001337 PySSL_BEGIN_ALLOW_THREADS
1338 count = SSL_pending(self->ssl);
1339 PySSL_END_ALLOW_THREADS
1340 if (count < 0)
1341 return PySSL_SetError(self, count, __FILE__, __LINE__);
1342 else
1343 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001344}
1345
1346PyDoc_STRVAR(PySSL_SSLpending_doc,
1347"pending() -> count\n\
1348\n\
1349Returns the number of already decrypted bytes available for read,\n\
1350pending on the connection.\n");
1351
Antoine Pitrou152efa22010-05-16 18:19:27 +00001352static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001353{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001354 PyObject *dest = NULL;
1355 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001356 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001357 int len, count;
1358 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 int sockstate;
1360 int err;
1361 int nonblocking;
1362 PySocketSockObject *sock
1363 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001364
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001365 if (((PyObject*)sock) == Py_None) {
1366 _setSSLError("Underlying socket connection gone",
1367 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1368 return NULL;
1369 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001370 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001371
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001372 buf.obj = NULL;
1373 buf.buf = NULL;
1374 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001375 goto error;
1376
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001377 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1378 dest = PyBytes_FromStringAndSize(NULL, len);
1379 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001380 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001381 mem = PyBytes_AS_STRING(dest);
1382 }
1383 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001384 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001385 mem = buf.buf;
1386 if (len <= 0 || len > buf.len) {
1387 len = (int) buf.len;
1388 if (buf.len != len) {
1389 PyErr_SetString(PyExc_OverflowError,
1390 "maximum length can't fit in a C 'int'");
1391 goto error;
1392 }
1393 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001394 }
1395
1396 /* just in case the blocking state of the socket has been changed */
1397 nonblocking = (sock->sock_timeout >= 0.0);
1398 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1399 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1400
1401 /* first check if there are bytes ready to be read */
1402 PySSL_BEGIN_ALLOW_THREADS
1403 count = SSL_pending(self->ssl);
1404 PySSL_END_ALLOW_THREADS
1405
1406 if (!count) {
1407 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1408 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001409 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001410 "The read operation timed out");
1411 goto error;
1412 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1413 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001414 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001415 goto error;
1416 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1417 count = 0;
1418 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001419 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001420 }
1421 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001422 PySSL_BEGIN_ALLOW_THREADS
1423 count = SSL_read(self->ssl, mem, len);
1424 err = SSL_get_error(self->ssl, count);
1425 PySSL_END_ALLOW_THREADS
1426 if (PyErr_CheckSignals())
1427 goto error;
1428 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001429 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001430 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001431 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001432 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1433 (SSL_get_shutdown(self->ssl) ==
1434 SSL_RECEIVED_SHUTDOWN))
1435 {
1436 count = 0;
1437 goto done;
1438 } else {
1439 sockstate = SOCKET_OPERATION_OK;
1440 }
1441 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001442 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001443 "The read operation timed out");
1444 goto error;
1445 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1446 break;
1447 }
1448 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1449 if (count <= 0) {
1450 PySSL_SetError(self, count, __FILE__, __LINE__);
1451 goto error;
1452 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001453
1454done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001455 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001456 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001457 _PyBytes_Resize(&dest, count);
1458 return dest;
1459 }
1460 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001461 PyBuffer_Release(&buf);
1462 return PyLong_FromLong(count);
1463 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001464
1465error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001466 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001467 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001468 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001469 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001470 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001471 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001472}
1473
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001474PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001475"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001476\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001477Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001478
Antoine Pitrou152efa22010-05-16 18:19:27 +00001479static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001480{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001481 int err, ssl_err, sockstate, nonblocking;
1482 int zeros = 0;
1483 PySocketSockObject *sock
1484 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001485
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001486 /* Guard against closed socket */
1487 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1488 _setSSLError("Underlying socket connection gone",
1489 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1490 return NULL;
1491 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001492 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001493
1494 /* Just in case the blocking state of the socket has been changed */
1495 nonblocking = (sock->sock_timeout >= 0.0);
1496 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1497 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1498
1499 while (1) {
1500 PySSL_BEGIN_ALLOW_THREADS
1501 /* Disable read-ahead so that unwrap can work correctly.
1502 * Otherwise OpenSSL might read in too much data,
1503 * eating clear text data that happens to be
1504 * transmitted after the SSL shutdown.
1505 * Should be safe to call repeatedly everytime this
1506 * function is used and the shutdown_seen_zero != 0
1507 * condition is met.
1508 */
1509 if (self->shutdown_seen_zero)
1510 SSL_set_read_ahead(self->ssl, 0);
1511 err = SSL_shutdown(self->ssl);
1512 PySSL_END_ALLOW_THREADS
1513 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1514 if (err > 0)
1515 break;
1516 if (err == 0) {
1517 /* Don't loop endlessly; instead preserve legacy
1518 behaviour of trying SSL_shutdown() only twice.
1519 This looks necessary for OpenSSL < 0.9.8m */
1520 if (++zeros > 1)
1521 break;
1522 /* Shutdown was sent, now try receiving */
1523 self->shutdown_seen_zero = 1;
1524 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001525 }
1526
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001527 /* Possibly retry shutdown until timeout or failure */
1528 ssl_err = SSL_get_error(self->ssl, err);
1529 if (ssl_err == SSL_ERROR_WANT_READ)
1530 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1531 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1532 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1533 else
1534 break;
1535 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1536 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001537 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001538 "The read operation timed out");
1539 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001540 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001541 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001542 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001543 }
1544 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1545 PyErr_SetString(PySSLErrorObject,
1546 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001547 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001548 }
1549 else if (sockstate != SOCKET_OPERATION_OK)
1550 /* Retain the SSL error code */
1551 break;
1552 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001553
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001554 if (err < 0) {
1555 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001556 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001557 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001558 else
1559 /* It's already INCREF'ed */
1560 return (PyObject *) sock;
1561
1562error:
1563 Py_DECREF(sock);
1564 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001565}
1566
1567PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1568"shutdown(s) -> socket\n\
1569\n\
1570Does the SSL shutdown handshake with the remote end, and returns\n\
1571the underlying socket object.");
1572
Antoine Pitroud6494802011-07-21 01:11:30 +02001573#if HAVE_OPENSSL_FINISHED
1574static PyObject *
1575PySSL_tls_unique_cb(PySSLSocket *self)
1576{
1577 PyObject *retval = NULL;
1578 char buf[PySSL_CB_MAXLEN];
1579 int len;
1580
1581 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1582 /* if session is resumed XOR we are the client */
1583 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1584 }
1585 else {
1586 /* if a new session XOR we are the server */
1587 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1588 }
1589
1590 /* It cannot be negative in current OpenSSL version as of July 2011 */
1591 assert(len >= 0);
1592 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
1766_advertiseNPN_cb(SSL *s,
1767 const unsigned char **data, unsigned int *len,
1768 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
1784_selectNPN_cb(SSL *s,
1785 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;
1918 Py_ssize_t size;
1919 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
1952 free(pw_info->password);
1953 pw_info->password = malloc(size);
1954 if (!pw_info->password) {
1955 PyErr_SetString(PyExc_MemoryError,
1956 "unable to allocate password buffer");
1957 goto error;
1958 }
1959 memcpy(pw_info->password, data, size);
1960 pw_info->size = size;
1961
1962 Py_XDECREF(password_bytes);
1963 return 1;
1964
1965error:
1966 Py_XDECREF(password_bytes);
1967 return 0;
1968}
1969
1970static int
1971_password_callback(char *buf, int size, int rwflag, void *userdata)
1972{
1973 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
1974 PyObject *fn_ret = NULL;
1975
1976 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
1977
1978 if (pw_info->callable) {
1979 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
1980 if (!fn_ret) {
1981 /* TODO: It would be nice to move _ctypes_add_traceback() into the
1982 core python API, so we could use it to add a frame here */
1983 goto error;
1984 }
1985
1986 if (!_pwinfo_set(pw_info, fn_ret,
1987 "password callback must return a string")) {
1988 goto error;
1989 }
1990 Py_CLEAR(fn_ret);
1991 }
1992
1993 if (pw_info->size > size) {
1994 PyErr_Format(PyExc_ValueError,
1995 "password cannot be longer than %d bytes", size);
1996 goto error;
1997 }
1998
1999 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2000 memcpy(buf, pw_info->password, pw_info->size);
2001 return pw_info->size;
2002
2003error:
2004 Py_XDECREF(fn_ret);
2005 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2006 pw_info->error = 1;
2007 return -1;
2008}
2009
Antoine Pitroub5218772010-05-21 09:56:06 +00002010static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002011load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2012{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002013 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2014 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002015 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002016 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2017 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2018 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002019 int r;
2020
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002021 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002022 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002023 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002024 "O|OO:load_cert_chain", kwlist,
2025 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002026 return NULL;
2027 if (keyfile == Py_None)
2028 keyfile = NULL;
2029 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2030 PyErr_SetString(PyExc_TypeError,
2031 "certfile should be a valid filesystem path");
2032 return NULL;
2033 }
2034 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2035 PyErr_SetString(PyExc_TypeError,
2036 "keyfile should be a valid filesystem path");
2037 goto error;
2038 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002039 if (password && password != Py_None) {
2040 if (PyCallable_Check(password)) {
2041 pw_info.callable = password;
2042 } else if (!_pwinfo_set(&pw_info, password,
2043 "password should be a string or callable")) {
2044 goto error;
2045 }
2046 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2047 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2048 }
2049 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002050 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2051 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002052 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002053 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002054 if (pw_info.error) {
2055 ERR_clear_error();
2056 /* the password callback has already set the error information */
2057 }
2058 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002059 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002060 PyErr_SetFromErrno(PyExc_IOError);
2061 }
2062 else {
2063 _setSSLError(NULL, 0, __FILE__, __LINE__);
2064 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002065 goto error;
2066 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002067 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002068 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002069 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2070 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002071 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2072 Py_CLEAR(keyfile_bytes);
2073 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002074 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002075 if (pw_info.error) {
2076 ERR_clear_error();
2077 /* the password callback has already set the error information */
2078 }
2079 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002080 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002081 PyErr_SetFromErrno(PyExc_IOError);
2082 }
2083 else {
2084 _setSSLError(NULL, 0, __FILE__, __LINE__);
2085 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002086 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002087 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002088 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002089 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002090 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002091 if (r != 1) {
2092 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002093 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002094 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002095 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2096 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2097 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002098 Py_RETURN_NONE;
2099
2100error:
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_XDECREF(keyfile_bytes);
2105 Py_XDECREF(certfile_bytes);
2106 return NULL;
2107}
2108
2109static PyObject *
2110load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2111{
2112 char *kwlist[] = {"cafile", "capath", NULL};
2113 PyObject *cafile = NULL, *capath = NULL;
2114 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2115 const char *cafile_buf = NULL, *capath_buf = NULL;
2116 int r;
2117
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002118 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002119 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2120 "|OO:load_verify_locations", kwlist,
2121 &cafile, &capath))
2122 return NULL;
2123 if (cafile == Py_None)
2124 cafile = NULL;
2125 if (capath == Py_None)
2126 capath = NULL;
2127 if (cafile == NULL && capath == NULL) {
2128 PyErr_SetString(PyExc_TypeError,
2129 "cafile and capath cannot be both omitted");
2130 return NULL;
2131 }
2132 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2133 PyErr_SetString(PyExc_TypeError,
2134 "cafile should be a valid filesystem path");
2135 return NULL;
2136 }
2137 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002138 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002139 PyErr_SetString(PyExc_TypeError,
2140 "capath should be a valid filesystem path");
2141 return NULL;
2142 }
2143 if (cafile)
2144 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2145 if (capath)
2146 capath_buf = PyBytes_AS_STRING(capath_bytes);
2147 PySSL_BEGIN_ALLOW_THREADS
2148 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2149 PySSL_END_ALLOW_THREADS
2150 Py_XDECREF(cafile_bytes);
2151 Py_XDECREF(capath_bytes);
2152 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002153 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002154 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002155 PyErr_SetFromErrno(PyExc_IOError);
2156 }
2157 else {
2158 _setSSLError(NULL, 0, __FILE__, __LINE__);
2159 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002160 return NULL;
2161 }
2162 Py_RETURN_NONE;
2163}
2164
2165static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002166load_dh_params(PySSLContext *self, PyObject *filepath)
2167{
2168 FILE *f;
2169 DH *dh;
2170
2171 f = _Py_fopen(filepath, "rb");
2172 if (f == NULL) {
2173 if (!PyErr_Occurred())
2174 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2175 return NULL;
2176 }
2177 errno = 0;
2178 PySSL_BEGIN_ALLOW_THREADS
2179 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002180 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002181 PySSL_END_ALLOW_THREADS
2182 if (dh == NULL) {
2183 if (errno != 0) {
2184 ERR_clear_error();
2185 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2186 }
2187 else {
2188 _setSSLError(NULL, 0, __FILE__, __LINE__);
2189 }
2190 return NULL;
2191 }
2192 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2193 _setSSLError(NULL, 0, __FILE__, __LINE__);
2194 DH_free(dh);
2195 Py_RETURN_NONE;
2196}
2197
2198static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002199context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2200{
Antoine Pitroud5323212010-10-22 18:19:07 +00002201 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002202 PySocketSockObject *sock;
2203 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002204 char *hostname = NULL;
2205 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002206
Antoine Pitroud5323212010-10-22 18:19:07 +00002207 /* server_hostname is either None (or absent), or to be encoded
2208 using the idna encoding. */
2209 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002210 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002211 &sock, &server_side,
2212 Py_TYPE(Py_None), &hostname_obj)) {
2213 PyErr_Clear();
2214 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2215 PySocketModule.Sock_Type,
2216 &sock, &server_side,
2217 "idna", &hostname))
2218 return NULL;
2219#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
2220 PyMem_Free(hostname);
2221 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2222 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002223 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002224#endif
2225 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002226
Antoine Pitroud5323212010-10-22 18:19:07 +00002227 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
2228 hostname);
2229 if (hostname != NULL)
2230 PyMem_Free(hostname);
2231 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002232}
2233
Antoine Pitroub0182c82010-10-12 20:09:02 +00002234static PyObject *
2235session_stats(PySSLContext *self, PyObject *unused)
2236{
2237 int r;
2238 PyObject *value, *stats = PyDict_New();
2239 if (!stats)
2240 return NULL;
2241
2242#define ADD_STATS(SSL_NAME, KEY_NAME) \
2243 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2244 if (value == NULL) \
2245 goto error; \
2246 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2247 Py_DECREF(value); \
2248 if (r < 0) \
2249 goto error;
2250
2251 ADD_STATS(number, "number");
2252 ADD_STATS(connect, "connect");
2253 ADD_STATS(connect_good, "connect_good");
2254 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2255 ADD_STATS(accept, "accept");
2256 ADD_STATS(accept_good, "accept_good");
2257 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2258 ADD_STATS(accept, "accept");
2259 ADD_STATS(hits, "hits");
2260 ADD_STATS(misses, "misses");
2261 ADD_STATS(timeouts, "timeouts");
2262 ADD_STATS(cache_full, "cache_full");
2263
2264#undef ADD_STATS
2265
2266 return stats;
2267
2268error:
2269 Py_DECREF(stats);
2270 return NULL;
2271}
2272
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002273static PyObject *
2274set_default_verify_paths(PySSLContext *self, PyObject *unused)
2275{
2276 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2277 _setSSLError(NULL, 0, __FILE__, __LINE__);
2278 return NULL;
2279 }
2280 Py_RETURN_NONE;
2281}
2282
Antoine Pitrou501da612011-12-21 09:27:41 +01002283#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002284static PyObject *
2285set_ecdh_curve(PySSLContext *self, PyObject *name)
2286{
2287 PyObject *name_bytes;
2288 int nid;
2289 EC_KEY *key;
2290
2291 if (!PyUnicode_FSConverter(name, &name_bytes))
2292 return NULL;
2293 assert(PyBytes_Check(name_bytes));
2294 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2295 Py_DECREF(name_bytes);
2296 if (nid == 0) {
2297 PyErr_Format(PyExc_ValueError,
2298 "unknown elliptic curve name %R", name);
2299 return NULL;
2300 }
2301 key = EC_KEY_new_by_curve_name(nid);
2302 if (key == NULL) {
2303 _setSSLError(NULL, 0, __FILE__, __LINE__);
2304 return NULL;
2305 }
2306 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2307 EC_KEY_free(key);
2308 Py_RETURN_NONE;
2309}
Antoine Pitrou501da612011-12-21 09:27:41 +01002310#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002311
Antoine Pitrou152efa22010-05-16 18:19:27 +00002312static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002313 {"options", (getter) get_options,
2314 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002315 {"verify_mode", (getter) get_verify_mode,
2316 (setter) set_verify_mode, NULL},
2317 {NULL}, /* sentinel */
2318};
2319
2320static struct PyMethodDef context_methods[] = {
2321 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2322 METH_VARARGS | METH_KEYWORDS, NULL},
2323 {"set_ciphers", (PyCFunction) set_ciphers,
2324 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002325 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2326 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002327 {"load_cert_chain", (PyCFunction) load_cert_chain,
2328 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002329 {"load_dh_params", (PyCFunction) load_dh_params,
2330 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002331 {"load_verify_locations", (PyCFunction) load_verify_locations,
2332 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002333 {"session_stats", (PyCFunction) session_stats,
2334 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002335 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2336 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002337#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002338 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2339 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002340#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002341 {NULL, NULL} /* sentinel */
2342};
2343
2344static PyTypeObject PySSLContext_Type = {
2345 PyVarObject_HEAD_INIT(NULL, 0)
2346 "_ssl._SSLContext", /*tp_name*/
2347 sizeof(PySSLContext), /*tp_basicsize*/
2348 0, /*tp_itemsize*/
2349 (destructor)context_dealloc, /*tp_dealloc*/
2350 0, /*tp_print*/
2351 0, /*tp_getattr*/
2352 0, /*tp_setattr*/
2353 0, /*tp_reserved*/
2354 0, /*tp_repr*/
2355 0, /*tp_as_number*/
2356 0, /*tp_as_sequence*/
2357 0, /*tp_as_mapping*/
2358 0, /*tp_hash*/
2359 0, /*tp_call*/
2360 0, /*tp_str*/
2361 0, /*tp_getattro*/
2362 0, /*tp_setattro*/
2363 0, /*tp_as_buffer*/
2364 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2365 0, /*tp_doc*/
2366 0, /*tp_traverse*/
2367 0, /*tp_clear*/
2368 0, /*tp_richcompare*/
2369 0, /*tp_weaklistoffset*/
2370 0, /*tp_iter*/
2371 0, /*tp_iternext*/
2372 context_methods, /*tp_methods*/
2373 0, /*tp_members*/
2374 context_getsetlist, /*tp_getset*/
2375 0, /*tp_base*/
2376 0, /*tp_dict*/
2377 0, /*tp_descr_get*/
2378 0, /*tp_descr_set*/
2379 0, /*tp_dictoffset*/
2380 0, /*tp_init*/
2381 0, /*tp_alloc*/
2382 context_new, /*tp_new*/
2383};
2384
2385
2386
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002387#ifdef HAVE_OPENSSL_RAND
2388
2389/* helper routines for seeding the SSL PRNG */
2390static PyObject *
2391PySSL_RAND_add(PyObject *self, PyObject *args)
2392{
2393 char *buf;
2394 int len;
2395 double entropy;
2396
2397 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002398 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002399 RAND_add(buf, len, entropy);
2400 Py_INCREF(Py_None);
2401 return Py_None;
2402}
2403
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002404PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002405"RAND_add(string, entropy)\n\
2406\n\
2407Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002408bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002409
2410static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002411PySSL_RAND(int len, int pseudo)
2412{
2413 int ok;
2414 PyObject *bytes;
2415 unsigned long err;
2416 const char *errstr;
2417 PyObject *v;
2418
2419 bytes = PyBytes_FromStringAndSize(NULL, len);
2420 if (bytes == NULL)
2421 return NULL;
2422 if (pseudo) {
2423 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2424 if (ok == 0 || ok == 1)
2425 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2426 }
2427 else {
2428 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2429 if (ok == 1)
2430 return bytes;
2431 }
2432 Py_DECREF(bytes);
2433
2434 err = ERR_get_error();
2435 errstr = ERR_reason_error_string(err);
2436 v = Py_BuildValue("(ks)", err, errstr);
2437 if (v != NULL) {
2438 PyErr_SetObject(PySSLErrorObject, v);
2439 Py_DECREF(v);
2440 }
2441 return NULL;
2442}
2443
2444static PyObject *
2445PySSL_RAND_bytes(PyObject *self, PyObject *args)
2446{
2447 int len;
2448 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2449 return NULL;
2450 return PySSL_RAND(len, 0);
2451}
2452
2453PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2454"RAND_bytes(n) -> bytes\n\
2455\n\
2456Generate n cryptographically strong pseudo-random bytes.");
2457
2458static PyObject *
2459PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2460{
2461 int len;
2462 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2463 return NULL;
2464 return PySSL_RAND(len, 1);
2465}
2466
2467PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2468"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2469\n\
2470Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2471generated are cryptographically strong.");
2472
2473static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002474PySSL_RAND_status(PyObject *self)
2475{
Christian Heimes217cfd12007-12-02 14:31:20 +00002476 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002477}
2478
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002479PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002480"RAND_status() -> 0 or 1\n\
2481\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002482Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2483It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2484using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002485
2486static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002487PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002488{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002489 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002490 int bytes;
2491
Jesus Ceac8754a12012-09-11 02:00:58 +02002492 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002493 PyUnicode_FSConverter, &path))
2494 return NULL;
2495
2496 bytes = RAND_egd(PyBytes_AsString(path));
2497 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002498 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002499 PyErr_SetString(PySSLErrorObject,
2500 "EGD connection failed or EGD did not return "
2501 "enough data to seed the PRNG");
2502 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002503 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002504 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002505}
2506
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002507PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002508"RAND_egd(path) -> bytes\n\
2509\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002510Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2511Returns number of bytes read. Raises SSLError if connection to EGD\n\
2512fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002513
2514#endif
2515
Bill Janssen40a0f662008-08-12 16:56:25 +00002516
2517
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002518/* List of functions exported by this module. */
2519
2520static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002521 {"_test_decode_cert", PySSL_test_decode_certificate,
2522 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002523#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002524 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2525 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002526 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2527 PySSL_RAND_bytes_doc},
2528 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2529 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002530 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002531 PySSL_RAND_egd_doc},
2532 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2533 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002534#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002535 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002536};
2537
2538
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002539#ifdef WITH_THREAD
2540
2541/* an implementation of OpenSSL threading operations in terms
2542 of the Python C thread library */
2543
2544static PyThread_type_lock *_ssl_locks = NULL;
2545
2546static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002547 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002548}
2549
Bill Janssen6e027db2007-11-15 22:23:56 +00002550static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002551 (int mode, int n, const char *file, int line) {
2552 /* this function is needed to perform locking on shared data
2553 structures. (Note that OpenSSL uses a number of global data
2554 structures that will be implicitly shared whenever multiple
2555 threads use OpenSSL.) Multi-threaded applications will
2556 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002557
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002558 locking_function() must be able to handle up to
2559 CRYPTO_num_locks() different mutex locks. It sets the n-th
2560 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002561
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002562 file and line are the file number of the function setting the
2563 lock. They can be useful for debugging.
2564 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002565
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002566 if ((_ssl_locks == NULL) ||
2567 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2568 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002569
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002570 if (mode & CRYPTO_LOCK) {
2571 PyThread_acquire_lock(_ssl_locks[n], 1);
2572 } else {
2573 PyThread_release_lock(_ssl_locks[n]);
2574 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002575}
2576
2577static int _setup_ssl_threads(void) {
2578
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002579 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002580
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002581 if (_ssl_locks == NULL) {
2582 _ssl_locks_count = CRYPTO_num_locks();
2583 _ssl_locks = (PyThread_type_lock *)
2584 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2585 if (_ssl_locks == NULL)
2586 return 0;
2587 memset(_ssl_locks, 0,
2588 sizeof(PyThread_type_lock) * _ssl_locks_count);
2589 for (i = 0; i < _ssl_locks_count; i++) {
2590 _ssl_locks[i] = PyThread_allocate_lock();
2591 if (_ssl_locks[i] == NULL) {
2592 unsigned int j;
2593 for (j = 0; j < i; j++) {
2594 PyThread_free_lock(_ssl_locks[j]);
2595 }
2596 free(_ssl_locks);
2597 return 0;
2598 }
2599 }
2600 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2601 CRYPTO_set_id_callback(_ssl_thread_id_function);
2602 }
2603 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002604}
2605
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002606#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002608PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002609"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002610for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002611
Martin v. Löwis1a214512008-06-11 05:26:20 +00002612
2613static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002614 PyModuleDef_HEAD_INIT,
2615 "_ssl",
2616 module_doc,
2617 -1,
2618 PySSL_methods,
2619 NULL,
2620 NULL,
2621 NULL,
2622 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002623};
2624
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002625
2626static void
2627parse_openssl_version(unsigned long libver,
2628 unsigned int *major, unsigned int *minor,
2629 unsigned int *fix, unsigned int *patch,
2630 unsigned int *status)
2631{
2632 *status = libver & 0xF;
2633 libver >>= 4;
2634 *patch = libver & 0xFF;
2635 libver >>= 8;
2636 *fix = libver & 0xFF;
2637 libver >>= 8;
2638 *minor = libver & 0xFF;
2639 libver >>= 8;
2640 *major = libver & 0xFF;
2641}
2642
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002643PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002644PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002645{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002646 PyObject *m, *d, *r;
2647 unsigned long libver;
2648 unsigned int major, minor, fix, patch, status;
2649 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002650 struct py_ssl_error_code *errcode;
2651 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002652
Antoine Pitrou152efa22010-05-16 18:19:27 +00002653 if (PyType_Ready(&PySSLContext_Type) < 0)
2654 return NULL;
2655 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002656 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002657
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002658 m = PyModule_Create(&_sslmodule);
2659 if (m == NULL)
2660 return NULL;
2661 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002662
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002663 /* Load _socket module and its C API */
2664 socket_api = PySocketModule_ImportModuleAndAPI();
2665 if (!socket_api)
2666 return NULL;
2667 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002668
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002669 /* Init OpenSSL */
2670 SSL_load_error_strings();
2671 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002672#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002673 /* note that this will start threading if not already started */
2674 if (!_setup_ssl_threads()) {
2675 return NULL;
2676 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002677#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002678 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002679
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002680 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002681 sslerror_type_slots[0].pfunc = PyExc_OSError;
2682 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002683 if (PySSLErrorObject == NULL)
2684 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002685
Antoine Pitrou41032a62011-10-27 23:56:55 +02002686 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2687 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2688 PySSLErrorObject, NULL);
2689 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2690 "ssl.SSLWantReadError", SSLWantReadError_doc,
2691 PySSLErrorObject, NULL);
2692 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2693 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2694 PySSLErrorObject, NULL);
2695 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2696 "ssl.SSLSyscallError", SSLSyscallError_doc,
2697 PySSLErrorObject, NULL);
2698 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2699 "ssl.SSLEOFError", SSLEOFError_doc,
2700 PySSLErrorObject, NULL);
2701 if (PySSLZeroReturnErrorObject == NULL
2702 || PySSLWantReadErrorObject == NULL
2703 || PySSLWantWriteErrorObject == NULL
2704 || PySSLSyscallErrorObject == NULL
2705 || PySSLEOFErrorObject == NULL)
2706 return NULL;
2707 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2708 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2709 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2710 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2711 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2712 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002713 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002714 if (PyDict_SetItemString(d, "_SSLContext",
2715 (PyObject *)&PySSLContext_Type) != 0)
2716 return NULL;
2717 if (PyDict_SetItemString(d, "_SSLSocket",
2718 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002719 return NULL;
2720 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2721 PY_SSL_ERROR_ZERO_RETURN);
2722 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2723 PY_SSL_ERROR_WANT_READ);
2724 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2725 PY_SSL_ERROR_WANT_WRITE);
2726 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2727 PY_SSL_ERROR_WANT_X509_LOOKUP);
2728 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2729 PY_SSL_ERROR_SYSCALL);
2730 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2731 PY_SSL_ERROR_SSL);
2732 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2733 PY_SSL_ERROR_WANT_CONNECT);
2734 /* non ssl.h errorcodes */
2735 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2736 PY_SSL_ERROR_EOF);
2737 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2738 PY_SSL_ERROR_INVALID_ERROR_CODE);
2739 /* cert requirements */
2740 PyModule_AddIntConstant(m, "CERT_NONE",
2741 PY_SSL_CERT_NONE);
2742 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2743 PY_SSL_CERT_OPTIONAL);
2744 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2745 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002746
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002747 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002748#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002749 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2750 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002751#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002752 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2753 PY_SSL_VERSION_SSL3);
2754 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2755 PY_SSL_VERSION_SSL23);
2756 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2757 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002758
Antoine Pitroub5218772010-05-21 09:56:06 +00002759 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01002760 PyModule_AddIntConstant(m, "OP_ALL",
2761 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00002762 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2763 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2764 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou6db49442011-12-19 13:27:11 +01002765 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
2766 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002767 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002768#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002769 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002770#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002771#ifdef SSL_OP_NO_COMPRESSION
2772 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
2773 SSL_OP_NO_COMPRESSION);
2774#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00002775
Antoine Pitroud5323212010-10-22 18:19:07 +00002776#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2777 r = Py_True;
2778#else
2779 r = Py_False;
2780#endif
2781 Py_INCREF(r);
2782 PyModule_AddObject(m, "HAS_SNI", r);
2783
Antoine Pitroud6494802011-07-21 01:11:30 +02002784#if HAVE_OPENSSL_FINISHED
2785 r = Py_True;
2786#else
2787 r = Py_False;
2788#endif
2789 Py_INCREF(r);
2790 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2791
Antoine Pitrou501da612011-12-21 09:27:41 +01002792#ifdef OPENSSL_NO_ECDH
2793 r = Py_False;
2794#else
2795 r = Py_True;
2796#endif
2797 Py_INCREF(r);
2798 PyModule_AddObject(m, "HAS_ECDH", r);
2799
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002800#ifdef OPENSSL_NPN_NEGOTIATED
2801 r = Py_True;
2802#else
2803 r = Py_False;
2804#endif
2805 Py_INCREF(r);
2806 PyModule_AddObject(m, "HAS_NPN", r);
2807
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002808 /* Mappings for error codes */
2809 err_codes_to_names = PyDict_New();
2810 err_names_to_codes = PyDict_New();
2811 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
2812 return NULL;
2813 errcode = error_codes;
2814 while (errcode->mnemonic != NULL) {
2815 PyObject *mnemo, *key;
2816 mnemo = PyUnicode_FromString(errcode->mnemonic);
2817 key = Py_BuildValue("ii", errcode->library, errcode->reason);
2818 if (mnemo == NULL || key == NULL)
2819 return NULL;
2820 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
2821 return NULL;
2822 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
2823 return NULL;
2824 Py_DECREF(key);
2825 Py_DECREF(mnemo);
2826 errcode++;
2827 }
2828 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
2829 return NULL;
2830 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
2831 return NULL;
2832
2833 lib_codes_to_names = PyDict_New();
2834 if (lib_codes_to_names == NULL)
2835 return NULL;
2836 libcode = library_codes;
2837 while (libcode->library != NULL) {
2838 PyObject *mnemo, *key;
2839 key = PyLong_FromLong(libcode->code);
2840 mnemo = PyUnicode_FromString(libcode->library);
2841 if (key == NULL || mnemo == NULL)
2842 return NULL;
2843 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
2844 return NULL;
2845 Py_DECREF(key);
2846 Py_DECREF(mnemo);
2847 libcode++;
2848 }
2849 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
2850 return NULL;
2851
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002852 /* OpenSSL version */
2853 /* SSLeay() gives us the version of the library linked against,
2854 which could be different from the headers version.
2855 */
2856 libver = SSLeay();
2857 r = PyLong_FromUnsignedLong(libver);
2858 if (r == NULL)
2859 return NULL;
2860 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2861 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002862 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002863 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2864 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2865 return NULL;
2866 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2867 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2868 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002869
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002870 libver = OPENSSL_VERSION_NUMBER;
2871 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2872 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2873 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2874 return NULL;
2875
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002876 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002877}