blob: b5d15306d6a6d7b569b812d50e7a79f057b5d9f2 [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;
1040 PyObject *binary_mode = Py_None;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001041
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001042 if (!PyArg_ParseTuple(args, "|O:peer_certificate", &binary_mode))
1043 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 Pitroucbb82eb2010-05-05 15:57:33 +00001048 if (PyObject_IsTrue(binary_mode)) {
1049 /* 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;
1716 /* Defaults */
1717 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001718 SSL_CTX_set_options(self->ctx,
1719 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001720
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001721#define SID_CTX "Python"
1722 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1723 sizeof(SID_CTX));
1724#undef SID_CTX
1725
Antoine Pitrou152efa22010-05-16 18:19:27 +00001726 return (PyObject *)self;
1727}
1728
1729static void
1730context_dealloc(PySSLContext *self)
1731{
1732 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001733#ifdef OPENSSL_NPN_NEGOTIATED
1734 PyMem_Free(self->npn_protocols);
1735#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001736 Py_TYPE(self)->tp_free(self);
1737}
1738
1739static PyObject *
1740set_ciphers(PySSLContext *self, PyObject *args)
1741{
1742 int ret;
1743 const char *cipherlist;
1744
1745 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1746 return NULL;
1747 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1748 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001749 /* Clearing the error queue is necessary on some OpenSSL versions,
1750 otherwise the error will be reported again when another SSL call
1751 is done. */
1752 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001753 PyErr_SetString(PySSLErrorObject,
1754 "No cipher can be selected.");
1755 return NULL;
1756 }
1757 Py_RETURN_NONE;
1758}
1759
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001760#ifdef OPENSSL_NPN_NEGOTIATED
1761/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1762static int
1763_advertiseNPN_cb(SSL *s,
1764 const unsigned char **data, unsigned int *len,
1765 void *args)
1766{
1767 PySSLContext *ssl_ctx = (PySSLContext *) args;
1768
1769 if (ssl_ctx->npn_protocols == NULL) {
1770 *data = (unsigned char *) "";
1771 *len = 0;
1772 } else {
1773 *data = (unsigned char *) ssl_ctx->npn_protocols;
1774 *len = ssl_ctx->npn_protocols_len;
1775 }
1776
1777 return SSL_TLSEXT_ERR_OK;
1778}
1779/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1780static int
1781_selectNPN_cb(SSL *s,
1782 unsigned char **out, unsigned char *outlen,
1783 const unsigned char *server, unsigned int server_len,
1784 void *args)
1785{
1786 PySSLContext *ssl_ctx = (PySSLContext *) args;
1787
1788 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1789 int client_len;
1790
1791 if (client == NULL) {
1792 client = (unsigned char *) "";
1793 client_len = 0;
1794 } else {
1795 client_len = ssl_ctx->npn_protocols_len;
1796 }
1797
1798 SSL_select_next_proto(out, outlen,
1799 server, server_len,
1800 client, client_len);
1801
1802 return SSL_TLSEXT_ERR_OK;
1803}
1804#endif
1805
1806static PyObject *
1807_set_npn_protocols(PySSLContext *self, PyObject *args)
1808{
1809#ifdef OPENSSL_NPN_NEGOTIATED
1810 Py_buffer protos;
1811
1812 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1813 return NULL;
1814
1815 self->npn_protocols = PyMem_Malloc(protos.len);
1816 if (self->npn_protocols == NULL) {
1817 PyBuffer_Release(&protos);
1818 return PyErr_NoMemory();
1819 }
1820 memcpy(self->npn_protocols, protos.buf, protos.len);
1821 self->npn_protocols_len = (int) protos.len;
1822
1823 /* set both server and client callbacks, because the context can
1824 * be used to create both types of sockets */
1825 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
1826 _advertiseNPN_cb,
1827 self);
1828 SSL_CTX_set_next_proto_select_cb(self->ctx,
1829 _selectNPN_cb,
1830 self);
1831
1832 PyBuffer_Release(&protos);
1833 Py_RETURN_NONE;
1834#else
1835 PyErr_SetString(PyExc_NotImplementedError,
1836 "The NPN extension requires OpenSSL 1.0.1 or later.");
1837 return NULL;
1838#endif
1839}
1840
Antoine Pitrou152efa22010-05-16 18:19:27 +00001841static PyObject *
1842get_verify_mode(PySSLContext *self, void *c)
1843{
1844 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1845 case SSL_VERIFY_NONE:
1846 return PyLong_FromLong(PY_SSL_CERT_NONE);
1847 case SSL_VERIFY_PEER:
1848 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1849 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1850 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1851 }
1852 PyErr_SetString(PySSLErrorObject,
1853 "invalid return value from SSL_CTX_get_verify_mode");
1854 return NULL;
1855}
1856
1857static int
1858set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1859{
1860 int n, mode;
1861 if (!PyArg_Parse(arg, "i", &n))
1862 return -1;
1863 if (n == PY_SSL_CERT_NONE)
1864 mode = SSL_VERIFY_NONE;
1865 else if (n == PY_SSL_CERT_OPTIONAL)
1866 mode = SSL_VERIFY_PEER;
1867 else if (n == PY_SSL_CERT_REQUIRED)
1868 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1869 else {
1870 PyErr_SetString(PyExc_ValueError,
1871 "invalid value for verify_mode");
1872 return -1;
1873 }
1874 SSL_CTX_set_verify(self->ctx, mode, NULL);
1875 return 0;
1876}
1877
1878static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001879get_options(PySSLContext *self, void *c)
1880{
1881 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1882}
1883
1884static int
1885set_options(PySSLContext *self, PyObject *arg, void *c)
1886{
1887 long new_opts, opts, set, clear;
1888 if (!PyArg_Parse(arg, "l", &new_opts))
1889 return -1;
1890 opts = SSL_CTX_get_options(self->ctx);
1891 clear = opts & ~new_opts;
1892 set = ~opts & new_opts;
1893 if (clear) {
1894#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1895 SSL_CTX_clear_options(self->ctx, clear);
1896#else
1897 PyErr_SetString(PyExc_ValueError,
1898 "can't clear options before OpenSSL 0.9.8m");
1899 return -1;
1900#endif
1901 }
1902 if (set)
1903 SSL_CTX_set_options(self->ctx, set);
1904 return 0;
1905}
1906
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001907typedef struct {
1908 PyThreadState *thread_state;
1909 PyObject *callable;
1910 char *password;
1911 Py_ssize_t size;
1912 int error;
1913} _PySSLPasswordInfo;
1914
1915static int
1916_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1917 const char *bad_type_error)
1918{
1919 /* Set the password and size fields of a _PySSLPasswordInfo struct
1920 from a unicode, bytes, or byte array object.
1921 The password field will be dynamically allocated and must be freed
1922 by the caller */
1923 PyObject *password_bytes = NULL;
1924 const char *data = NULL;
1925 Py_ssize_t size;
1926
1927 if (PyUnicode_Check(password)) {
1928 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
1929 if (!password_bytes) {
1930 goto error;
1931 }
1932 data = PyBytes_AS_STRING(password_bytes);
1933 size = PyBytes_GET_SIZE(password_bytes);
1934 } else if (PyBytes_Check(password)) {
1935 data = PyBytes_AS_STRING(password);
1936 size = PyBytes_GET_SIZE(password);
1937 } else if (PyByteArray_Check(password)) {
1938 data = PyByteArray_AS_STRING(password);
1939 size = PyByteArray_GET_SIZE(password);
1940 } else {
1941 PyErr_SetString(PyExc_TypeError, bad_type_error);
1942 goto error;
1943 }
1944
1945 free(pw_info->password);
1946 pw_info->password = malloc(size);
1947 if (!pw_info->password) {
1948 PyErr_SetString(PyExc_MemoryError,
1949 "unable to allocate password buffer");
1950 goto error;
1951 }
1952 memcpy(pw_info->password, data, size);
1953 pw_info->size = size;
1954
1955 Py_XDECREF(password_bytes);
1956 return 1;
1957
1958error:
1959 Py_XDECREF(password_bytes);
1960 return 0;
1961}
1962
1963static int
1964_password_callback(char *buf, int size, int rwflag, void *userdata)
1965{
1966 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
1967 PyObject *fn_ret = NULL;
1968
1969 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
1970
1971 if (pw_info->callable) {
1972 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
1973 if (!fn_ret) {
1974 /* TODO: It would be nice to move _ctypes_add_traceback() into the
1975 core python API, so we could use it to add a frame here */
1976 goto error;
1977 }
1978
1979 if (!_pwinfo_set(pw_info, fn_ret,
1980 "password callback must return a string")) {
1981 goto error;
1982 }
1983 Py_CLEAR(fn_ret);
1984 }
1985
1986 if (pw_info->size > size) {
1987 PyErr_Format(PyExc_ValueError,
1988 "password cannot be longer than %d bytes", size);
1989 goto error;
1990 }
1991
1992 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1993 memcpy(buf, pw_info->password, pw_info->size);
1994 return pw_info->size;
1995
1996error:
1997 Py_XDECREF(fn_ret);
1998 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
1999 pw_info->error = 1;
2000 return -1;
2001}
2002
Antoine Pitroub5218772010-05-21 09:56:06 +00002003static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002004load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2005{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002006 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2007 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002008 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002009 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2010 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2011 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002012 int r;
2013
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002014 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002015 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002016 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002017 "O|OO:load_cert_chain", kwlist,
2018 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002019 return NULL;
2020 if (keyfile == Py_None)
2021 keyfile = NULL;
2022 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2023 PyErr_SetString(PyExc_TypeError,
2024 "certfile should be a valid filesystem path");
2025 return NULL;
2026 }
2027 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2028 PyErr_SetString(PyExc_TypeError,
2029 "keyfile should be a valid filesystem path");
2030 goto error;
2031 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002032 if (password && password != Py_None) {
2033 if (PyCallable_Check(password)) {
2034 pw_info.callable = password;
2035 } else if (!_pwinfo_set(&pw_info, password,
2036 "password should be a string or callable")) {
2037 goto error;
2038 }
2039 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2040 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2041 }
2042 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002043 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2044 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002045 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002046 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002047 if (pw_info.error) {
2048 ERR_clear_error();
2049 /* the password callback has already set the error information */
2050 }
2051 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002052 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002053 PyErr_SetFromErrno(PyExc_IOError);
2054 }
2055 else {
2056 _setSSLError(NULL, 0, __FILE__, __LINE__);
2057 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002058 goto error;
2059 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002060 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002061 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002062 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2063 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002064 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2065 Py_CLEAR(keyfile_bytes);
2066 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002067 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002068 if (pw_info.error) {
2069 ERR_clear_error();
2070 /* the password callback has already set the error information */
2071 }
2072 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002073 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002074 PyErr_SetFromErrno(PyExc_IOError);
2075 }
2076 else {
2077 _setSSLError(NULL, 0, __FILE__, __LINE__);
2078 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002079 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002080 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002081 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002082 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002083 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002084 if (r != 1) {
2085 _setSSLError(NULL, 0, __FILE__, __LINE__);
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 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2089 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2090 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002091 Py_RETURN_NONE;
2092
2093error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002094 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2095 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2096 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002097 Py_XDECREF(keyfile_bytes);
2098 Py_XDECREF(certfile_bytes);
2099 return NULL;
2100}
2101
2102static PyObject *
2103load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2104{
2105 char *kwlist[] = {"cafile", "capath", NULL};
2106 PyObject *cafile = NULL, *capath = NULL;
2107 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2108 const char *cafile_buf = NULL, *capath_buf = NULL;
2109 int r;
2110
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002111 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002112 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2113 "|OO:load_verify_locations", kwlist,
2114 &cafile, &capath))
2115 return NULL;
2116 if (cafile == Py_None)
2117 cafile = NULL;
2118 if (capath == Py_None)
2119 capath = NULL;
2120 if (cafile == NULL && capath == NULL) {
2121 PyErr_SetString(PyExc_TypeError,
2122 "cafile and capath cannot be both omitted");
2123 return NULL;
2124 }
2125 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2126 PyErr_SetString(PyExc_TypeError,
2127 "cafile should be a valid filesystem path");
2128 return NULL;
2129 }
2130 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002131 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002132 PyErr_SetString(PyExc_TypeError,
2133 "capath should be a valid filesystem path");
2134 return NULL;
2135 }
2136 if (cafile)
2137 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2138 if (capath)
2139 capath_buf = PyBytes_AS_STRING(capath_bytes);
2140 PySSL_BEGIN_ALLOW_THREADS
2141 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2142 PySSL_END_ALLOW_THREADS
2143 Py_XDECREF(cafile_bytes);
2144 Py_XDECREF(capath_bytes);
2145 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002146 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002147 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002148 PyErr_SetFromErrno(PyExc_IOError);
2149 }
2150 else {
2151 _setSSLError(NULL, 0, __FILE__, __LINE__);
2152 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002153 return NULL;
2154 }
2155 Py_RETURN_NONE;
2156}
2157
2158static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002159load_dh_params(PySSLContext *self, PyObject *filepath)
2160{
2161 FILE *f;
2162 DH *dh;
2163
2164 f = _Py_fopen(filepath, "rb");
2165 if (f == NULL) {
2166 if (!PyErr_Occurred())
2167 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2168 return NULL;
2169 }
2170 errno = 0;
2171 PySSL_BEGIN_ALLOW_THREADS
2172 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
2173 PySSL_END_ALLOW_THREADS
2174 if (dh == NULL) {
2175 if (errno != 0) {
2176 ERR_clear_error();
2177 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2178 }
2179 else {
2180 _setSSLError(NULL, 0, __FILE__, __LINE__);
2181 }
2182 return NULL;
2183 }
2184 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2185 _setSSLError(NULL, 0, __FILE__, __LINE__);
2186 DH_free(dh);
2187 Py_RETURN_NONE;
2188}
2189
2190static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002191context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2192{
Antoine Pitroud5323212010-10-22 18:19:07 +00002193 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002194 PySocketSockObject *sock;
2195 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002196 char *hostname = NULL;
2197 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002198
Antoine Pitroud5323212010-10-22 18:19:07 +00002199 /* server_hostname is either None (or absent), or to be encoded
2200 using the idna encoding. */
2201 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002202 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002203 &sock, &server_side,
2204 Py_TYPE(Py_None), &hostname_obj)) {
2205 PyErr_Clear();
2206 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2207 PySocketModule.Sock_Type,
2208 &sock, &server_side,
2209 "idna", &hostname))
2210 return NULL;
2211#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
2212 PyMem_Free(hostname);
2213 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2214 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002215 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002216#endif
2217 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002218
Antoine Pitroud5323212010-10-22 18:19:07 +00002219 res = (PyObject *) newPySSLSocket(self->ctx, sock, server_side,
2220 hostname);
2221 if (hostname != NULL)
2222 PyMem_Free(hostname);
2223 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002224}
2225
Antoine Pitroub0182c82010-10-12 20:09:02 +00002226static PyObject *
2227session_stats(PySSLContext *self, PyObject *unused)
2228{
2229 int r;
2230 PyObject *value, *stats = PyDict_New();
2231 if (!stats)
2232 return NULL;
2233
2234#define ADD_STATS(SSL_NAME, KEY_NAME) \
2235 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2236 if (value == NULL) \
2237 goto error; \
2238 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2239 Py_DECREF(value); \
2240 if (r < 0) \
2241 goto error;
2242
2243 ADD_STATS(number, "number");
2244 ADD_STATS(connect, "connect");
2245 ADD_STATS(connect_good, "connect_good");
2246 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2247 ADD_STATS(accept, "accept");
2248 ADD_STATS(accept_good, "accept_good");
2249 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2250 ADD_STATS(accept, "accept");
2251 ADD_STATS(hits, "hits");
2252 ADD_STATS(misses, "misses");
2253 ADD_STATS(timeouts, "timeouts");
2254 ADD_STATS(cache_full, "cache_full");
2255
2256#undef ADD_STATS
2257
2258 return stats;
2259
2260error:
2261 Py_DECREF(stats);
2262 return NULL;
2263}
2264
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002265static PyObject *
2266set_default_verify_paths(PySSLContext *self, PyObject *unused)
2267{
2268 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2269 _setSSLError(NULL, 0, __FILE__, __LINE__);
2270 return NULL;
2271 }
2272 Py_RETURN_NONE;
2273}
2274
Antoine Pitrou501da612011-12-21 09:27:41 +01002275#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002276static PyObject *
2277set_ecdh_curve(PySSLContext *self, PyObject *name)
2278{
2279 PyObject *name_bytes;
2280 int nid;
2281 EC_KEY *key;
2282
2283 if (!PyUnicode_FSConverter(name, &name_bytes))
2284 return NULL;
2285 assert(PyBytes_Check(name_bytes));
2286 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2287 Py_DECREF(name_bytes);
2288 if (nid == 0) {
2289 PyErr_Format(PyExc_ValueError,
2290 "unknown elliptic curve name %R", name);
2291 return NULL;
2292 }
2293 key = EC_KEY_new_by_curve_name(nid);
2294 if (key == NULL) {
2295 _setSSLError(NULL, 0, __FILE__, __LINE__);
2296 return NULL;
2297 }
2298 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2299 EC_KEY_free(key);
2300 Py_RETURN_NONE;
2301}
Antoine Pitrou501da612011-12-21 09:27:41 +01002302#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002303
Antoine Pitrou152efa22010-05-16 18:19:27 +00002304static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002305 {"options", (getter) get_options,
2306 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002307 {"verify_mode", (getter) get_verify_mode,
2308 (setter) set_verify_mode, NULL},
2309 {NULL}, /* sentinel */
2310};
2311
2312static struct PyMethodDef context_methods[] = {
2313 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2314 METH_VARARGS | METH_KEYWORDS, NULL},
2315 {"set_ciphers", (PyCFunction) set_ciphers,
2316 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002317 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2318 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002319 {"load_cert_chain", (PyCFunction) load_cert_chain,
2320 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002321 {"load_dh_params", (PyCFunction) load_dh_params,
2322 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002323 {"load_verify_locations", (PyCFunction) load_verify_locations,
2324 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002325 {"session_stats", (PyCFunction) session_stats,
2326 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002327 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2328 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002329#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002330 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2331 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002332#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002333 {NULL, NULL} /* sentinel */
2334};
2335
2336static PyTypeObject PySSLContext_Type = {
2337 PyVarObject_HEAD_INIT(NULL, 0)
2338 "_ssl._SSLContext", /*tp_name*/
2339 sizeof(PySSLContext), /*tp_basicsize*/
2340 0, /*tp_itemsize*/
2341 (destructor)context_dealloc, /*tp_dealloc*/
2342 0, /*tp_print*/
2343 0, /*tp_getattr*/
2344 0, /*tp_setattr*/
2345 0, /*tp_reserved*/
2346 0, /*tp_repr*/
2347 0, /*tp_as_number*/
2348 0, /*tp_as_sequence*/
2349 0, /*tp_as_mapping*/
2350 0, /*tp_hash*/
2351 0, /*tp_call*/
2352 0, /*tp_str*/
2353 0, /*tp_getattro*/
2354 0, /*tp_setattro*/
2355 0, /*tp_as_buffer*/
2356 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
2357 0, /*tp_doc*/
2358 0, /*tp_traverse*/
2359 0, /*tp_clear*/
2360 0, /*tp_richcompare*/
2361 0, /*tp_weaklistoffset*/
2362 0, /*tp_iter*/
2363 0, /*tp_iternext*/
2364 context_methods, /*tp_methods*/
2365 0, /*tp_members*/
2366 context_getsetlist, /*tp_getset*/
2367 0, /*tp_base*/
2368 0, /*tp_dict*/
2369 0, /*tp_descr_get*/
2370 0, /*tp_descr_set*/
2371 0, /*tp_dictoffset*/
2372 0, /*tp_init*/
2373 0, /*tp_alloc*/
2374 context_new, /*tp_new*/
2375};
2376
2377
2378
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002379#ifdef HAVE_OPENSSL_RAND
2380
2381/* helper routines for seeding the SSL PRNG */
2382static PyObject *
2383PySSL_RAND_add(PyObject *self, PyObject *args)
2384{
2385 char *buf;
2386 int len;
2387 double entropy;
2388
2389 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002390 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002391 RAND_add(buf, len, entropy);
2392 Py_INCREF(Py_None);
2393 return Py_None;
2394}
2395
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002396PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002397"RAND_add(string, entropy)\n\
2398\n\
2399Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002400bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002401
2402static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002403PySSL_RAND(int len, int pseudo)
2404{
2405 int ok;
2406 PyObject *bytes;
2407 unsigned long err;
2408 const char *errstr;
2409 PyObject *v;
2410
2411 bytes = PyBytes_FromStringAndSize(NULL, len);
2412 if (bytes == NULL)
2413 return NULL;
2414 if (pseudo) {
2415 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2416 if (ok == 0 || ok == 1)
2417 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2418 }
2419 else {
2420 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2421 if (ok == 1)
2422 return bytes;
2423 }
2424 Py_DECREF(bytes);
2425
2426 err = ERR_get_error();
2427 errstr = ERR_reason_error_string(err);
2428 v = Py_BuildValue("(ks)", err, errstr);
2429 if (v != NULL) {
2430 PyErr_SetObject(PySSLErrorObject, v);
2431 Py_DECREF(v);
2432 }
2433 return NULL;
2434}
2435
2436static PyObject *
2437PySSL_RAND_bytes(PyObject *self, PyObject *args)
2438{
2439 int len;
2440 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2441 return NULL;
2442 return PySSL_RAND(len, 0);
2443}
2444
2445PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2446"RAND_bytes(n) -> bytes\n\
2447\n\
2448Generate n cryptographically strong pseudo-random bytes.");
2449
2450static PyObject *
2451PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2452{
2453 int len;
2454 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2455 return NULL;
2456 return PySSL_RAND(len, 1);
2457}
2458
2459PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2460"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2461\n\
2462Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2463generated are cryptographically strong.");
2464
2465static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002466PySSL_RAND_status(PyObject *self)
2467{
Christian Heimes217cfd12007-12-02 14:31:20 +00002468 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002469}
2470
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002471PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002472"RAND_status() -> 0 or 1\n\
2473\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002474Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2475It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2476using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002477
2478static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002479PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002480{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002481 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002482 int bytes;
2483
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002484 if (!PyArg_ParseTuple(args, "O&|i:RAND_egd",
2485 PyUnicode_FSConverter, &path))
2486 return NULL;
2487
2488 bytes = RAND_egd(PyBytes_AsString(path));
2489 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002490 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002491 PyErr_SetString(PySSLErrorObject,
2492 "EGD connection failed or EGD did not return "
2493 "enough data to seed the PRNG");
2494 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002495 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002496 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002497}
2498
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002499PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002500"RAND_egd(path) -> bytes\n\
2501\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002502Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2503Returns number of bytes read. Raises SSLError if connection to EGD\n\
2504fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002505
2506#endif
2507
Bill Janssen40a0f662008-08-12 16:56:25 +00002508
2509
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002510/* List of functions exported by this module. */
2511
2512static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002513 {"_test_decode_cert", PySSL_test_decode_certificate,
2514 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002515#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002516 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2517 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002518 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2519 PySSL_RAND_bytes_doc},
2520 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2521 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002522 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002523 PySSL_RAND_egd_doc},
2524 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2525 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002526#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002527 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002528};
2529
2530
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002531#ifdef WITH_THREAD
2532
2533/* an implementation of OpenSSL threading operations in terms
2534 of the Python C thread library */
2535
2536static PyThread_type_lock *_ssl_locks = NULL;
2537
2538static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002539 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002540}
2541
Bill Janssen6e027db2007-11-15 22:23:56 +00002542static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002543 (int mode, int n, const char *file, int line) {
2544 /* this function is needed to perform locking on shared data
2545 structures. (Note that OpenSSL uses a number of global data
2546 structures that will be implicitly shared whenever multiple
2547 threads use OpenSSL.) Multi-threaded applications will
2548 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002549
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002550 locking_function() must be able to handle up to
2551 CRYPTO_num_locks() different mutex locks. It sets the n-th
2552 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002553
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002554 file and line are the file number of the function setting the
2555 lock. They can be useful for debugging.
2556 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002557
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002558 if ((_ssl_locks == NULL) ||
2559 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2560 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002561
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002562 if (mode & CRYPTO_LOCK) {
2563 PyThread_acquire_lock(_ssl_locks[n], 1);
2564 } else {
2565 PyThread_release_lock(_ssl_locks[n]);
2566 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002567}
2568
2569static int _setup_ssl_threads(void) {
2570
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002571 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002572
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002573 if (_ssl_locks == NULL) {
2574 _ssl_locks_count = CRYPTO_num_locks();
2575 _ssl_locks = (PyThread_type_lock *)
2576 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2577 if (_ssl_locks == NULL)
2578 return 0;
2579 memset(_ssl_locks, 0,
2580 sizeof(PyThread_type_lock) * _ssl_locks_count);
2581 for (i = 0; i < _ssl_locks_count; i++) {
2582 _ssl_locks[i] = PyThread_allocate_lock();
2583 if (_ssl_locks[i] == NULL) {
2584 unsigned int j;
2585 for (j = 0; j < i; j++) {
2586 PyThread_free_lock(_ssl_locks[j]);
2587 }
2588 free(_ssl_locks);
2589 return 0;
2590 }
2591 }
2592 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2593 CRYPTO_set_id_callback(_ssl_thread_id_function);
2594 }
2595 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002596}
2597
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002598#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002599
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002600PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002601"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002602for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002603
Martin v. Löwis1a214512008-06-11 05:26:20 +00002604
2605static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002606 PyModuleDef_HEAD_INIT,
2607 "_ssl",
2608 module_doc,
2609 -1,
2610 PySSL_methods,
2611 NULL,
2612 NULL,
2613 NULL,
2614 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002615};
2616
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002617
2618static void
2619parse_openssl_version(unsigned long libver,
2620 unsigned int *major, unsigned int *minor,
2621 unsigned int *fix, unsigned int *patch,
2622 unsigned int *status)
2623{
2624 *status = libver & 0xF;
2625 libver >>= 4;
2626 *patch = libver & 0xFF;
2627 libver >>= 8;
2628 *fix = libver & 0xFF;
2629 libver >>= 8;
2630 *minor = libver & 0xFF;
2631 libver >>= 8;
2632 *major = libver & 0xFF;
2633}
2634
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002635PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002636PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002637{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002638 PyObject *m, *d, *r;
2639 unsigned long libver;
2640 unsigned int major, minor, fix, patch, status;
2641 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002642 struct py_ssl_error_code *errcode;
2643 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002644
Antoine Pitrou152efa22010-05-16 18:19:27 +00002645 if (PyType_Ready(&PySSLContext_Type) < 0)
2646 return NULL;
2647 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002648 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002649
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002650 m = PyModule_Create(&_sslmodule);
2651 if (m == NULL)
2652 return NULL;
2653 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002654
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002655 /* Load _socket module and its C API */
2656 socket_api = PySocketModule_ImportModuleAndAPI();
2657 if (!socket_api)
2658 return NULL;
2659 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002660
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002661 /* Init OpenSSL */
2662 SSL_load_error_strings();
2663 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002664#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002665 /* note that this will start threading if not already started */
2666 if (!_setup_ssl_threads()) {
2667 return NULL;
2668 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002669#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002670 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002671
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002672 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002673 sslerror_type_slots[0].pfunc = PyExc_OSError;
2674 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002675 if (PySSLErrorObject == NULL)
2676 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002677
Antoine Pitrou41032a62011-10-27 23:56:55 +02002678 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2679 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2680 PySSLErrorObject, NULL);
2681 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2682 "ssl.SSLWantReadError", SSLWantReadError_doc,
2683 PySSLErrorObject, NULL);
2684 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2685 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2686 PySSLErrorObject, NULL);
2687 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2688 "ssl.SSLSyscallError", SSLSyscallError_doc,
2689 PySSLErrorObject, NULL);
2690 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2691 "ssl.SSLEOFError", SSLEOFError_doc,
2692 PySSLErrorObject, NULL);
2693 if (PySSLZeroReturnErrorObject == NULL
2694 || PySSLWantReadErrorObject == NULL
2695 || PySSLWantWriteErrorObject == NULL
2696 || PySSLSyscallErrorObject == NULL
2697 || PySSLEOFErrorObject == NULL)
2698 return NULL;
2699 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2700 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2701 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2702 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2703 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2704 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002705 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002706 if (PyDict_SetItemString(d, "_SSLContext",
2707 (PyObject *)&PySSLContext_Type) != 0)
2708 return NULL;
2709 if (PyDict_SetItemString(d, "_SSLSocket",
2710 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002711 return NULL;
2712 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2713 PY_SSL_ERROR_ZERO_RETURN);
2714 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2715 PY_SSL_ERROR_WANT_READ);
2716 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2717 PY_SSL_ERROR_WANT_WRITE);
2718 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2719 PY_SSL_ERROR_WANT_X509_LOOKUP);
2720 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2721 PY_SSL_ERROR_SYSCALL);
2722 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2723 PY_SSL_ERROR_SSL);
2724 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2725 PY_SSL_ERROR_WANT_CONNECT);
2726 /* non ssl.h errorcodes */
2727 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2728 PY_SSL_ERROR_EOF);
2729 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2730 PY_SSL_ERROR_INVALID_ERROR_CODE);
2731 /* cert requirements */
2732 PyModule_AddIntConstant(m, "CERT_NONE",
2733 PY_SSL_CERT_NONE);
2734 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2735 PY_SSL_CERT_OPTIONAL);
2736 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2737 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002738
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002739 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002740#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002741 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2742 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002743#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002744 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2745 PY_SSL_VERSION_SSL3);
2746 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2747 PY_SSL_VERSION_SSL23);
2748 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
2749 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002750
Antoine Pitroub5218772010-05-21 09:56:06 +00002751 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01002752 PyModule_AddIntConstant(m, "OP_ALL",
2753 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00002754 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
2755 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
2756 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou6db49442011-12-19 13:27:11 +01002757 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
2758 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002759 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002760#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002761 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01002762#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002763#ifdef SSL_OP_NO_COMPRESSION
2764 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
2765 SSL_OP_NO_COMPRESSION);
2766#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00002767
Antoine Pitroud5323212010-10-22 18:19:07 +00002768#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
2769 r = Py_True;
2770#else
2771 r = Py_False;
2772#endif
2773 Py_INCREF(r);
2774 PyModule_AddObject(m, "HAS_SNI", r);
2775
Antoine Pitroud6494802011-07-21 01:11:30 +02002776#if HAVE_OPENSSL_FINISHED
2777 r = Py_True;
2778#else
2779 r = Py_False;
2780#endif
2781 Py_INCREF(r);
2782 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
2783
Antoine Pitrou501da612011-12-21 09:27:41 +01002784#ifdef OPENSSL_NO_ECDH
2785 r = Py_False;
2786#else
2787 r = Py_True;
2788#endif
2789 Py_INCREF(r);
2790 PyModule_AddObject(m, "HAS_ECDH", r);
2791
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002792#ifdef OPENSSL_NPN_NEGOTIATED
2793 r = Py_True;
2794#else
2795 r = Py_False;
2796#endif
2797 Py_INCREF(r);
2798 PyModule_AddObject(m, "HAS_NPN", r);
2799
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002800 /* Mappings for error codes */
2801 err_codes_to_names = PyDict_New();
2802 err_names_to_codes = PyDict_New();
2803 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
2804 return NULL;
2805 errcode = error_codes;
2806 while (errcode->mnemonic != NULL) {
2807 PyObject *mnemo, *key;
2808 mnemo = PyUnicode_FromString(errcode->mnemonic);
2809 key = Py_BuildValue("ii", errcode->library, errcode->reason);
2810 if (mnemo == NULL || key == NULL)
2811 return NULL;
2812 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
2813 return NULL;
2814 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
2815 return NULL;
2816 Py_DECREF(key);
2817 Py_DECREF(mnemo);
2818 errcode++;
2819 }
2820 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
2821 return NULL;
2822 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
2823 return NULL;
2824
2825 lib_codes_to_names = PyDict_New();
2826 if (lib_codes_to_names == NULL)
2827 return NULL;
2828 libcode = library_codes;
2829 while (libcode->library != NULL) {
2830 PyObject *mnemo, *key;
2831 key = PyLong_FromLong(libcode->code);
2832 mnemo = PyUnicode_FromString(libcode->library);
2833 if (key == NULL || mnemo == NULL)
2834 return NULL;
2835 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
2836 return NULL;
2837 Py_DECREF(key);
2838 Py_DECREF(mnemo);
2839 libcode++;
2840 }
2841 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
2842 return NULL;
2843
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002844 /* OpenSSL version */
2845 /* SSLeay() gives us the version of the library linked against,
2846 which could be different from the headers version.
2847 */
2848 libver = SSLeay();
2849 r = PyLong_FromUnsignedLong(libver);
2850 if (r == NULL)
2851 return NULL;
2852 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
2853 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002854 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002855 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2856 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
2857 return NULL;
2858 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
2859 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
2860 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00002861
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002862 libver = OPENSSL_VERSION_NUMBER;
2863 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
2864 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
2865 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
2866 return NULL;
2867
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002868 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002869}