blob: dce84c00851fbd9ef7fa3781a2c38b91eecd8510 [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
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010043/* Include symbols from _socket module */
44#include "socketmodule.h"
45
46static PySocketModule_APIObject PySocketModule;
47
48#if defined(HAVE_POLL_H)
49#include <poll.h>
50#elif defined(HAVE_SYS_POLL_H)
51#include <sys/poll.h>
52#endif
53
54/* Include OpenSSL header files */
55#include "openssl/rsa.h"
56#include "openssl/crypto.h"
57#include "openssl/x509.h"
58#include "openssl/x509v3.h"
59#include "openssl/pem.h"
60#include "openssl/ssl.h"
61#include "openssl/err.h"
62#include "openssl/rand.h"
63
64/* SSL error object */
65static PyObject *PySSLErrorObject;
66static PyObject *PySSLZeroReturnErrorObject;
67static PyObject *PySSLWantReadErrorObject;
68static PyObject *PySSLWantWriteErrorObject;
69static PyObject *PySSLSyscallErrorObject;
70static PyObject *PySSLEOFErrorObject;
71
72/* Error mappings */
73static PyObject *err_codes_to_names;
74static PyObject *err_names_to_codes;
75static PyObject *lib_codes_to_names;
76
77struct py_ssl_error_code {
78 const char *mnemonic;
79 int library, reason;
80};
81struct py_ssl_library_code {
82 const char *library;
83 int code;
84};
85
86/* Include generated data (error codes) */
87#include "_ssl_data.h"
88
89/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
90 http://www.openssl.org/news/changelog.html
91 */
92#if OPENSSL_VERSION_NUMBER >= 0x10001000L
93# define HAVE_TLSv1_2 1
94#else
95# define HAVE_TLSv1_2 0
96#endif
97
Antoine Pitrouce852cb2013-03-30 16:45:04 +010098/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0.
Antoine Pitrou912fbff2013-03-30 16:29:32 +010099 * This includes the SSL_set_SSL_CTX() function.
100 */
101#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
102# define HAVE_SNI 1
103#else
104# define HAVE_SNI 0
105#endif
106
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000107enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000108 /* these mirror ssl.h */
109 PY_SSL_ERROR_NONE,
110 PY_SSL_ERROR_SSL,
111 PY_SSL_ERROR_WANT_READ,
112 PY_SSL_ERROR_WANT_WRITE,
113 PY_SSL_ERROR_WANT_X509_LOOKUP,
114 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
115 PY_SSL_ERROR_ZERO_RETURN,
116 PY_SSL_ERROR_WANT_CONNECT,
117 /* start of non ssl.h errorcodes */
118 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
119 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
120 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000121};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000122
Thomas Woutersed03b412007-08-28 21:37:11 +0000123enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000124 PY_SSL_CLIENT,
125 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000126};
127
128enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000129 PY_SSL_CERT_NONE,
130 PY_SSL_CERT_OPTIONAL,
131 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000132};
133
134enum py_ssl_version {
Victor Stinner3de49192011-05-09 00:42:58 +0200135#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000136 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200137#endif
138 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000139 PY_SSL_VERSION_SSL23,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100140#if HAVE_TLSv1_2
141 PY_SSL_VERSION_TLS1,
142 PY_SSL_VERSION_TLS1_1,
143 PY_SSL_VERSION_TLS1_2
144#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000145 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000146#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100147};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200148
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000149#ifdef WITH_THREAD
150
151/* serves as a flag to see whether we've initialized the SSL thread support. */
152/* 0 means no, greater than 0 means yes */
153
154static unsigned int _ssl_locks_count = 0;
155
156#endif /* def WITH_THREAD */
157
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000158/* SSL socket object */
159
160#define X509_NAME_MAXLEN 256
161
162/* RAND_* APIs got added to OpenSSL in 0.9.5 */
163#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
164# define HAVE_OPENSSL_RAND 1
165#else
166# undef HAVE_OPENSSL_RAND
167#endif
168
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000169/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
170 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
171 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
172#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000173# define HAVE_SSL_CTX_CLEAR_OPTIONS
174#else
175# undef HAVE_SSL_CTX_CLEAR_OPTIONS
176#endif
177
Antoine Pitroud6494802011-07-21 01:11:30 +0200178/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
179 * older SSL, but let's be safe */
180#define PySSL_CB_MAXLEN 128
181
182/* SSL_get_finished got added to OpenSSL in 0.9.5 */
183#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
184# define HAVE_OPENSSL_FINISHED 1
185#else
186# define HAVE_OPENSSL_FINISHED 0
187#endif
188
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100189/* ECDH support got added to OpenSSL in 0.9.8 */
190#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
191# define OPENSSL_NO_ECDH
192#endif
193
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100194/* compression support got added to OpenSSL in 0.9.8 */
195#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
196# define OPENSSL_NO_COMP
197#endif
198
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100199
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000200typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000201 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000202 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100203#ifdef OPENSSL_NPN_NEGOTIATED
204 char *npn_protocols;
205 int npn_protocols_len;
206#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100207#ifndef OPENSSL_NO_TLSEXT
208 PyObject *set_hostname;
209#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000210} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000211
Antoine Pitrou152efa22010-05-16 18:19:27 +0000212typedef struct {
213 PyObject_HEAD
214 PyObject *Socket; /* weakref to socket on which we're layered */
215 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100216 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000217 X509 *peer_cert;
218 int shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200219 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000220} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000221
Antoine Pitrou152efa22010-05-16 18:19:27 +0000222static PyTypeObject PySSLContext_Type;
223static PyTypeObject PySSLSocket_Type;
224
225static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
226static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000227static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000228 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000229static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
230static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000231
Antoine Pitrou152efa22010-05-16 18:19:27 +0000232#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
233#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000234
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000235typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000236 SOCKET_IS_NONBLOCKING,
237 SOCKET_IS_BLOCKING,
238 SOCKET_HAS_TIMED_OUT,
239 SOCKET_HAS_BEEN_CLOSED,
240 SOCKET_TOO_LARGE_FOR_SELECT,
241 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000242} timeout_state;
243
Thomas Woutersed03b412007-08-28 21:37:11 +0000244/* Wrap error strings with filename and line # */
245#define STRINGIFY1(x) #x
246#define STRINGIFY2(x) STRINGIFY1(x)
247#define ERRSTR1(x,y,z) (x ":" y ": " z)
248#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
249
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200250
251/*
252 * SSL errors.
253 */
254
255PyDoc_STRVAR(SSLError_doc,
256"An error occurred in the SSL implementation.");
257
258PyDoc_STRVAR(SSLZeroReturnError_doc,
259"SSL/TLS session closed cleanly.");
260
261PyDoc_STRVAR(SSLWantReadError_doc,
262"Non-blocking SSL socket needs to read more data\n"
263"before the requested operation can be completed.");
264
265PyDoc_STRVAR(SSLWantWriteError_doc,
266"Non-blocking SSL socket needs to write more data\n"
267"before the requested operation can be completed.");
268
269PyDoc_STRVAR(SSLSyscallError_doc,
270"System error when attempting SSL operation.");
271
272PyDoc_STRVAR(SSLEOFError_doc,
273"SSL/TLS connection terminated abruptly.");
274
275static PyObject *
276SSLError_str(PyOSErrorObject *self)
277{
278 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
279 Py_INCREF(self->strerror);
280 return self->strerror;
281 }
282 else
283 return PyObject_Str(self->args);
284}
285
286static PyType_Slot sslerror_type_slots[] = {
287 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
288 {Py_tp_doc, SSLError_doc},
289 {Py_tp_str, SSLError_str},
290 {0, 0},
291};
292
293static PyType_Spec sslerror_type_spec = {
294 "ssl.SSLError",
295 sizeof(PyOSErrorObject),
296 0,
297 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
298 sslerror_type_slots
299};
300
301static void
302fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
303 int lineno, unsigned long errcode)
304{
305 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
306 PyObject *init_value, *msg, *key;
307 _Py_IDENTIFIER(reason);
308 _Py_IDENTIFIER(library);
309
310 if (errcode != 0) {
311 int lib, reason;
312
313 lib = ERR_GET_LIB(errcode);
314 reason = ERR_GET_REASON(errcode);
315 key = Py_BuildValue("ii", lib, reason);
316 if (key == NULL)
317 goto fail;
318 reason_obj = PyDict_GetItem(err_codes_to_names, key);
319 Py_DECREF(key);
320 if (reason_obj == NULL) {
321 /* XXX if reason < 100, it might reflect a library number (!!) */
322 PyErr_Clear();
323 }
324 key = PyLong_FromLong(lib);
325 if (key == NULL)
326 goto fail;
327 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
328 Py_DECREF(key);
329 if (lib_obj == NULL) {
330 PyErr_Clear();
331 }
332 if (errstr == NULL)
333 errstr = ERR_reason_error_string(errcode);
334 }
335 if (errstr == NULL)
336 errstr = "unknown error";
337
338 if (reason_obj && lib_obj)
339 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
340 lib_obj, reason_obj, errstr, lineno);
341 else if (lib_obj)
342 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
343 lib_obj, errstr, lineno);
344 else
345 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
346
347 if (msg == NULL)
348 goto fail;
349 init_value = Py_BuildValue("iN", ssl_errno, msg);
350 err_value = PyObject_CallObject(type, init_value);
351 Py_DECREF(init_value);
352 if (err_value == NULL)
353 goto fail;
354 if (reason_obj == NULL)
355 reason_obj = Py_None;
356 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
357 goto fail;
358 if (lib_obj == NULL)
359 lib_obj = Py_None;
360 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
361 goto fail;
362 PyErr_SetObject(type, err_value);
363fail:
364 Py_XDECREF(err_value);
365}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000366
367static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000368PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000369{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200370 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200371 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000372 int err;
373 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200374 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000375
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000376 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200377 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000378
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000379 if (obj->ssl != NULL) {
380 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000381
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000382 switch (err) {
383 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200384 errstr = "TLS/SSL connection has been closed (EOF)";
385 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000386 p = PY_SSL_ERROR_ZERO_RETURN;
387 break;
388 case SSL_ERROR_WANT_READ:
389 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200390 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000391 p = PY_SSL_ERROR_WANT_READ;
392 break;
393 case SSL_ERROR_WANT_WRITE:
394 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200395 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000396 errstr = "The operation did not complete (write)";
397 break;
398 case SSL_ERROR_WANT_X509_LOOKUP:
399 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000400 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000401 break;
402 case SSL_ERROR_WANT_CONNECT:
403 p = PY_SSL_ERROR_WANT_CONNECT;
404 errstr = "The operation did not complete (connect)";
405 break;
406 case SSL_ERROR_SYSCALL:
407 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000408 if (e == 0) {
409 PySocketSockObject *s
410 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
411 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000412 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200413 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000414 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000415 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000416 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000417 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000418 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200419 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000420 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200421 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000422 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000423 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200424 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000425 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000426 }
427 } else {
428 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000429 }
430 break;
431 }
432 case SSL_ERROR_SSL:
433 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000434 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200435 if (e == 0)
436 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000437 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000438 break;
439 }
440 default:
441 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
442 errstr = "Invalid error code";
443 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000444 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200445 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000446 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000447 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000448}
449
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000450static PyObject *
451_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
452
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200453 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000454 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200455 else
456 errcode = 0;
457 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000458 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000459 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000460}
461
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200462/*
463 * SSL objects
464 */
465
Antoine Pitrou152efa22010-05-16 18:19:27 +0000466static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100467newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000468 enum py_ssl_server_or_client socket_type,
469 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000470{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000471 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100472 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200473 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000474
Antoine Pitrou152efa22010-05-16 18:19:27 +0000475 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000476 if (self == NULL)
477 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000478
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000479 self->peer_cert = NULL;
480 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000481 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100482 self->ctx = sslctx;
483 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000484
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000485 /* Make sure the SSL error state is initialized */
486 (void) ERR_get_state();
487 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000488
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000489 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000490 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000491 PySSL_END_ALLOW_THREADS
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100492 SSL_set_app_data(self->ssl,self);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000493 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou19fef692013-05-25 13:23:03 +0200494 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000495#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200496 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000497#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200498 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000499
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100500#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000501 if (server_hostname != NULL)
502 SSL_set_tlsext_host_name(self->ssl, server_hostname);
503#endif
504
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000505 /* If the socket is in non-blocking mode or timeout mode, set the BIO
506 * to non-blocking mode (blocking is the default)
507 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000508 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000509 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
510 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
511 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000512
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000513 PySSL_BEGIN_ALLOW_THREADS
514 if (socket_type == PY_SSL_CLIENT)
515 SSL_set_connect_state(self->ssl);
516 else
517 SSL_set_accept_state(self->ssl);
518 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000519
Antoine Pitroud6494802011-07-21 01:11:30 +0200520 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000521 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000522 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000523}
524
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000525/* SSL object methods */
526
Antoine Pitrou152efa22010-05-16 18:19:27 +0000527static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000528{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000529 int ret;
530 int err;
531 int sockstate, nonblocking;
532 PySocketSockObject *sock
533 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000534
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000535 if (((PyObject*)sock) == Py_None) {
536 _setSSLError("Underlying socket connection gone",
537 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
538 return NULL;
539 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000540 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000541
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000542 /* just in case the blocking state of the socket has been changed */
543 nonblocking = (sock->sock_timeout >= 0.0);
544 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
545 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000546
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000547 /* Actually negotiate SSL connection */
548 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000549 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000550 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000551 ret = SSL_do_handshake(self->ssl);
552 err = SSL_get_error(self->ssl, ret);
553 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000554 if (PyErr_CheckSignals())
555 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000556 if (err == SSL_ERROR_WANT_READ) {
557 sockstate = check_socket_and_wait_for_timeout(sock, 0);
558 } else if (err == SSL_ERROR_WANT_WRITE) {
559 sockstate = check_socket_and_wait_for_timeout(sock, 1);
560 } else {
561 sockstate = SOCKET_OPERATION_OK;
562 }
563 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000564 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000565 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000566 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000567 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
568 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000569 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000570 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000571 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
572 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000573 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000574 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000575 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
576 break;
577 }
578 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000579 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000580 if (ret < 1)
581 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000582
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000583 if (self->peer_cert)
584 X509_free (self->peer_cert);
585 PySSL_BEGIN_ALLOW_THREADS
586 self->peer_cert = SSL_get_peer_certificate(self->ssl);
587 PySSL_END_ALLOW_THREADS
588
589 Py_INCREF(Py_None);
590 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000591
592error:
593 Py_DECREF(sock);
594 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000595}
596
Thomas Woutersed03b412007-08-28 21:37:11 +0000597static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000598_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000599
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000600 char namebuf[X509_NAME_MAXLEN];
601 int buflen;
602 PyObject *name_obj;
603 PyObject *value_obj;
604 PyObject *attr;
605 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000606
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000607 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
608 if (buflen < 0) {
609 _setSSLError(NULL, 0, __FILE__, __LINE__);
610 goto fail;
611 }
612 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
613 if (name_obj == NULL)
614 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000615
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000616 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
617 if (buflen < 0) {
618 _setSSLError(NULL, 0, __FILE__, __LINE__);
619 Py_DECREF(name_obj);
620 goto fail;
621 }
622 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000623 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000624 OPENSSL_free(valuebuf);
625 if (value_obj == NULL) {
626 Py_DECREF(name_obj);
627 goto fail;
628 }
629 attr = PyTuple_New(2);
630 if (attr == NULL) {
631 Py_DECREF(name_obj);
632 Py_DECREF(value_obj);
633 goto fail;
634 }
635 PyTuple_SET_ITEM(attr, 0, name_obj);
636 PyTuple_SET_ITEM(attr, 1, value_obj);
637 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000638
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000639 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000640 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000641}
642
643static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000644_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000645{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000646 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
647 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
648 PyObject *rdnt;
649 PyObject *attr = NULL; /* tuple to hold an attribute */
650 int entry_count = X509_NAME_entry_count(xname);
651 X509_NAME_ENTRY *entry;
652 ASN1_OBJECT *name;
653 ASN1_STRING *value;
654 int index_counter;
655 int rdn_level = -1;
656 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000657
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000658 dn = PyList_New(0);
659 if (dn == NULL)
660 return NULL;
661 /* now create another tuple to hold the top-level RDN */
662 rdn = PyList_New(0);
663 if (rdn == NULL)
664 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000665
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 for (index_counter = 0;
667 index_counter < entry_count;
668 index_counter++)
669 {
670 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000671
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000672 /* check to see if we've gotten to a new RDN */
673 if (rdn_level >= 0) {
674 if (rdn_level != entry->set) {
675 /* yes, new RDN */
676 /* add old RDN to DN */
677 rdnt = PyList_AsTuple(rdn);
678 Py_DECREF(rdn);
679 if (rdnt == NULL)
680 goto fail0;
681 retcode = PyList_Append(dn, rdnt);
682 Py_DECREF(rdnt);
683 if (retcode < 0)
684 goto fail0;
685 /* create new RDN */
686 rdn = PyList_New(0);
687 if (rdn == NULL)
688 goto fail0;
689 }
690 }
691 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000692
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000693 /* now add this attribute to the current RDN */
694 name = X509_NAME_ENTRY_get_object(entry);
695 value = X509_NAME_ENTRY_get_data(entry);
696 attr = _create_tuple_for_attribute(name, value);
697 /*
698 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
699 entry->set,
700 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
701 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
702 */
703 if (attr == NULL)
704 goto fail1;
705 retcode = PyList_Append(rdn, attr);
706 Py_DECREF(attr);
707 if (retcode < 0)
708 goto fail1;
709 }
710 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100711 if (rdn != NULL) {
712 if (PyList_GET_SIZE(rdn) > 0) {
713 rdnt = PyList_AsTuple(rdn);
714 Py_DECREF(rdn);
715 if (rdnt == NULL)
716 goto fail0;
717 retcode = PyList_Append(dn, rdnt);
718 Py_DECREF(rdnt);
719 if (retcode < 0)
720 goto fail0;
721 }
722 else {
723 Py_DECREF(rdn);
724 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000725 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000726
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000727 /* convert list to tuple */
728 rdnt = PyList_AsTuple(dn);
729 Py_DECREF(dn);
730 if (rdnt == NULL)
731 return NULL;
732 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000733
734 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000736
737 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000738 Py_XDECREF(dn);
739 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000740}
741
742static PyObject *
743_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000744
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 /* this code follows the procedure outlined in
746 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
747 function to extract the STACK_OF(GENERAL_NAME),
748 then iterates through the stack to add the
749 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000750
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000751 int i, j;
752 PyObject *peer_alt_names = Py_None;
753 PyObject *v, *t;
754 X509_EXTENSION *ext = NULL;
755 GENERAL_NAMES *names = NULL;
756 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000757 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000758 BIO *biobuf = NULL;
759 char buf[2048];
760 char *vptr;
761 int len;
762 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000763#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000764 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000765#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000766 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000767#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000768
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 if (certificate == NULL)
770 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000771
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000772 /* get a memory buffer */
773 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000774
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200775 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000776 while ((i = X509_get_ext_by_NID(
777 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000778
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 if (peer_alt_names == Py_None) {
780 peer_alt_names = PyList_New(0);
781 if (peer_alt_names == NULL)
782 goto fail;
783 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000784
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 /* now decode the altName */
786 ext = X509_get_ext(certificate, i);
787 if(!(method = X509V3_EXT_get(ext))) {
788 PyErr_SetString
789 (PySSLErrorObject,
790 ERRSTR("No method for internalizing subjectAltName!"));
791 goto fail;
792 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000793
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 p = ext->value->data;
795 if (method->it)
796 names = (GENERAL_NAMES*)
797 (ASN1_item_d2i(NULL,
798 &p,
799 ext->value->length,
800 ASN1_ITEM_ptr(method->it)));
801 else
802 names = (GENERAL_NAMES*)
803 (method->d2i(NULL,
804 &p,
805 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000806
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000807 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000808
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000809 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000811 name = sk_GENERAL_NAME_value(names, j);
812 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000813
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000814 /* we special-case DirName as a tuple of
815 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000816
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000817 t = PyTuple_New(2);
818 if (t == NULL) {
819 goto fail;
820 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000821
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000822 v = PyUnicode_FromString("DirName");
823 if (v == NULL) {
824 Py_DECREF(t);
825 goto fail;
826 }
827 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000829 v = _create_tuple_for_X509_NAME (name->d.dirn);
830 if (v == NULL) {
831 Py_DECREF(t);
832 goto fail;
833 }
834 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000835
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000836 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000837
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000839
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 (void) BIO_reset(biobuf);
841 GENERAL_NAME_print(biobuf, name);
842 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
843 if (len < 0) {
844 _setSSLError(NULL, 0, __FILE__, __LINE__);
845 goto fail;
846 }
847 vptr = strchr(buf, ':');
848 if (vptr == NULL)
849 goto fail;
850 t = PyTuple_New(2);
851 if (t == NULL)
852 goto fail;
853 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
854 if (v == NULL) {
855 Py_DECREF(t);
856 goto fail;
857 }
858 PyTuple_SET_ITEM(t, 0, v);
859 v = PyUnicode_FromStringAndSize((vptr + 1),
860 (len - (vptr - buf + 1)));
861 if (v == NULL) {
862 Py_DECREF(t);
863 goto fail;
864 }
865 PyTuple_SET_ITEM(t, 1, v);
866 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000867
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000868 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000869
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000870 if (PyList_Append(peer_alt_names, t) < 0) {
871 Py_DECREF(t);
872 goto fail;
873 }
874 Py_DECREF(t);
875 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100876 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000877 }
878 BIO_free(biobuf);
879 if (peer_alt_names != Py_None) {
880 v = PyList_AsTuple(peer_alt_names);
881 Py_DECREF(peer_alt_names);
882 return v;
883 } else {
884 return peer_alt_names;
885 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000886
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000887
888 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000889 if (biobuf != NULL)
890 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000891
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000892 if (peer_alt_names != Py_None) {
893 Py_XDECREF(peer_alt_names);
894 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000895
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000897}
898
899static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000900_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000901
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000902 PyObject *retval = NULL;
903 BIO *biobuf = NULL;
904 PyObject *peer;
905 PyObject *peer_alt_names = NULL;
906 PyObject *issuer;
907 PyObject *version;
908 PyObject *sn_obj;
909 ASN1_INTEGER *serialNumber;
910 char buf[2048];
911 int len;
912 ASN1_TIME *notBefore, *notAfter;
913 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000914
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000915 retval = PyDict_New();
916 if (retval == NULL)
917 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000918
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000919 peer = _create_tuple_for_X509_NAME(
920 X509_get_subject_name(certificate));
921 if (peer == NULL)
922 goto fail0;
923 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
924 Py_DECREF(peer);
925 goto fail0;
926 }
927 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000928
Antoine Pitroufb046912010-11-09 20:21:19 +0000929 issuer = _create_tuple_for_X509_NAME(
930 X509_get_issuer_name(certificate));
931 if (issuer == NULL)
932 goto fail0;
933 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000935 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000937 Py_DECREF(issuer);
938
939 version = PyLong_FromLong(X509_get_version(certificate) + 1);
940 if (PyDict_SetItemString(retval, "version", version) < 0) {
941 Py_DECREF(version);
942 goto fail0;
943 }
944 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000945
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 /* get a memory buffer */
947 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000948
Antoine Pitroufb046912010-11-09 20:21:19 +0000949 (void) BIO_reset(biobuf);
950 serialNumber = X509_get_serialNumber(certificate);
951 /* should not exceed 20 octets, 160 bits, so buf is big enough */
952 i2a_ASN1_INTEGER(biobuf, serialNumber);
953 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
954 if (len < 0) {
955 _setSSLError(NULL, 0, __FILE__, __LINE__);
956 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000958 sn_obj = PyUnicode_FromStringAndSize(buf, len);
959 if (sn_obj == NULL)
960 goto fail1;
961 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
962 Py_DECREF(sn_obj);
963 goto fail1;
964 }
965 Py_DECREF(sn_obj);
966
967 (void) BIO_reset(biobuf);
968 notBefore = X509_get_notBefore(certificate);
969 ASN1_TIME_print(biobuf, notBefore);
970 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
971 if (len < 0) {
972 _setSSLError(NULL, 0, __FILE__, __LINE__);
973 goto fail1;
974 }
975 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
976 if (pnotBefore == NULL)
977 goto fail1;
978 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
979 Py_DECREF(pnotBefore);
980 goto fail1;
981 }
982 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000983
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000984 (void) BIO_reset(biobuf);
985 notAfter = X509_get_notAfter(certificate);
986 ASN1_TIME_print(biobuf, notAfter);
987 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
988 if (len < 0) {
989 _setSSLError(NULL, 0, __FILE__, __LINE__);
990 goto fail1;
991 }
992 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
993 if (pnotAfter == NULL)
994 goto fail1;
995 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
996 Py_DECREF(pnotAfter);
997 goto fail1;
998 }
999 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001000
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001001 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001002
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001003 peer_alt_names = _get_peer_alt_names(certificate);
1004 if (peer_alt_names == NULL)
1005 goto fail1;
1006 else if (peer_alt_names != Py_None) {
1007 if (PyDict_SetItemString(retval, "subjectAltName",
1008 peer_alt_names) < 0) {
1009 Py_DECREF(peer_alt_names);
1010 goto fail1;
1011 }
1012 Py_DECREF(peer_alt_names);
1013 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001014
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001015 BIO_free(biobuf);
1016 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001017
1018 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001019 if (biobuf != NULL)
1020 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001021 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001022 Py_XDECREF(retval);
1023 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001024}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001025
Christian Heimes9a5395a2013-06-17 15:44:12 +02001026static PyObject *
1027_certificate_to_der(X509 *certificate)
1028{
1029 unsigned char *bytes_buf = NULL;
1030 int len;
1031 PyObject *retval;
1032
1033 bytes_buf = NULL;
1034 len = i2d_X509(certificate, &bytes_buf);
1035 if (len < 0) {
1036 _setSSLError(NULL, 0, __FILE__, __LINE__);
1037 return NULL;
1038 }
1039 /* this is actually an immutable bytes sequence */
1040 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1041 OPENSSL_free(bytes_buf);
1042 return retval;
1043}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001044
1045static PyObject *
1046PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1047
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001048 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001049 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 X509 *x=NULL;
1051 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001052
Antoine Pitroufb046912010-11-09 20:21:19 +00001053 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1054 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001055 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001056
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1058 PyErr_SetString(PySSLErrorObject,
1059 "Can't malloc memory to read file");
1060 goto fail0;
1061 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001062
Victor Stinner3800e1e2010-05-16 21:23:48 +00001063 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001064 PyErr_SetString(PySSLErrorObject,
1065 "Can't open file");
1066 goto fail0;
1067 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001068
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1070 if (x == NULL) {
1071 PyErr_SetString(PySSLErrorObject,
1072 "Error decoding PEM-encoded file");
1073 goto fail0;
1074 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001075
Antoine Pitroufb046912010-11-09 20:21:19 +00001076 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001077 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001078
1079 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001080 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081 if (cert != NULL) BIO_free(cert);
1082 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001083}
1084
1085
1086static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001087PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001088{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001089 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001090 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001091
Antoine Pitrou721738f2012-08-15 23:20:39 +02001092 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001093 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001094
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001095 if (!self->peer_cert)
1096 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001097
Antoine Pitrou721738f2012-08-15 23:20:39 +02001098 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001100 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001102 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 if ((verification & SSL_VERIFY_PEER) == 0)
1104 return PyDict_New();
1105 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001106 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001108}
1109
1110PyDoc_STRVAR(PySSL_peercert_doc,
1111"peer_certificate([der=False]) -> certificate\n\
1112\n\
1113Returns the certificate for the peer. If no certificate was provided,\n\
1114returns None. If a certificate was provided, but not validated, returns\n\
1115an empty dictionary. Otherwise returns a dict containing information\n\
1116about the peer certificate.\n\
1117\n\
1118If the optional argument is True, returns a DER-encoded copy of the\n\
1119peer certificate, or None if no certificate was provided. This will\n\
1120return the certificate even if it wasn't validated.");
1121
Antoine Pitrou152efa22010-05-16 18:19:27 +00001122static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001123
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001124 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001125 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001126 char *cipher_name;
1127 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001128
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001130 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131 current = SSL_get_current_cipher(self->ssl);
1132 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001133 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001134
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001135 retval = PyTuple_New(3);
1136 if (retval == NULL)
1137 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001138
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001139 cipher_name = (char *) SSL_CIPHER_get_name(current);
1140 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001141 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001142 PyTuple_SET_ITEM(retval, 0, Py_None);
1143 } else {
1144 v = PyUnicode_FromString(cipher_name);
1145 if (v == NULL)
1146 goto fail0;
1147 PyTuple_SET_ITEM(retval, 0, v);
1148 }
1149 cipher_protocol = SSL_CIPHER_get_version(current);
1150 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001151 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001152 PyTuple_SET_ITEM(retval, 1, Py_None);
1153 } else {
1154 v = PyUnicode_FromString(cipher_protocol);
1155 if (v == NULL)
1156 goto fail0;
1157 PyTuple_SET_ITEM(retval, 1, v);
1158 }
1159 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1160 if (v == NULL)
1161 goto fail0;
1162 PyTuple_SET_ITEM(retval, 2, v);
1163 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001164
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001165 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001166 Py_DECREF(retval);
1167 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001168}
1169
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001170#ifdef OPENSSL_NPN_NEGOTIATED
1171static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1172 const unsigned char *out;
1173 unsigned int outlen;
1174
Victor Stinner4569cd52013-06-23 14:58:43 +02001175 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001176 &out, &outlen);
1177
1178 if (out == NULL)
1179 Py_RETURN_NONE;
1180 return PyUnicode_FromStringAndSize((char *) out, outlen);
1181}
1182#endif
1183
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001184static PyObject *PySSL_compression(PySSLSocket *self) {
1185#ifdef OPENSSL_NO_COMP
1186 Py_RETURN_NONE;
1187#else
1188 const COMP_METHOD *comp_method;
1189 const char *short_name;
1190
1191 if (self->ssl == NULL)
1192 Py_RETURN_NONE;
1193 comp_method = SSL_get_current_compression(self->ssl);
1194 if (comp_method == NULL || comp_method->type == NID_undef)
1195 Py_RETURN_NONE;
1196 short_name = OBJ_nid2sn(comp_method->type);
1197 if (short_name == NULL)
1198 Py_RETURN_NONE;
1199 return PyUnicode_DecodeFSDefault(short_name);
1200#endif
1201}
1202
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001203static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1204 Py_INCREF(self->ctx);
1205 return self->ctx;
1206}
1207
1208static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1209 void *closure) {
1210
1211 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001212#if !HAVE_SNI
1213 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1214 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001215 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001216#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001217 Py_INCREF(value);
1218 Py_DECREF(self->ctx);
1219 self->ctx = (PySSLContext *) value;
1220 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001221#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001222 } else {
1223 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1224 return -1;
1225 }
1226
1227 return 0;
1228}
1229
1230PyDoc_STRVAR(PySSL_set_context_doc,
1231"_setter_context(ctx)\n\
1232\
1233This changes the context associated with the SSLSocket. This is typically\n\
1234used from within a callback function set by the set_servername_callback\n\
1235on the SSLContext to change the certificate information associated with the\n\
1236SSLSocket before the cryptographic exchange handshake messages\n");
1237
1238
1239
Antoine Pitrou152efa22010-05-16 18:19:27 +00001240static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001241{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001242 if (self->peer_cert) /* Possible not to have one? */
1243 X509_free (self->peer_cert);
1244 if (self->ssl)
1245 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001246 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001247 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001248 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001249}
1250
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001251/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001252 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001253 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001254 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001255
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001256static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001257check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001258{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001259 fd_set fds;
1260 struct timeval tv;
1261 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1264 if (s->sock_timeout < 0.0)
1265 return SOCKET_IS_BLOCKING;
1266 else if (s->sock_timeout == 0.0)
1267 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001268
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001269 /* Guard against closed socket */
1270 if (s->sock_fd < 0)
1271 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001272
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001273 /* Prefer poll, if available, since you can poll() any fd
1274 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001275#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 {
1277 struct pollfd pollfd;
1278 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001279
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 pollfd.fd = s->sock_fd;
1281 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001282
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001283 /* s->sock_timeout is in seconds, timeout in ms */
1284 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1285 PySSL_BEGIN_ALLOW_THREADS
1286 rc = poll(&pollfd, 1, timeout);
1287 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001288
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001289 goto normal_return;
1290 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001291#endif
1292
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001293 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001294 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001296
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001297 /* Construct the arguments to select */
1298 tv.tv_sec = (int)s->sock_timeout;
1299 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1300 FD_ZERO(&fds);
1301 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001302
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001303 /* See if the socket is ready */
1304 PySSL_BEGIN_ALLOW_THREADS
1305 if (writing)
1306 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1307 else
1308 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1309 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001310
Bill Janssen6e027db2007-11-15 22:23:56 +00001311#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001312normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001313#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001314 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1315 (when we are able to write or when there's something to read) */
1316 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001317}
1318
Antoine Pitrou152efa22010-05-16 18:19:27 +00001319static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001320{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001321 Py_buffer buf;
1322 int len;
1323 int sockstate;
1324 int err;
1325 int nonblocking;
1326 PySocketSockObject *sock
1327 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001328
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 if (((PyObject*)sock) == Py_None) {
1330 _setSSLError("Underlying socket connection gone",
1331 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1332 return NULL;
1333 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001334 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001335
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001336 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1337 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001339 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340
1341 /* just in case the blocking state of the socket has been changed */
1342 nonblocking = (sock->sock_timeout >= 0.0);
1343 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1344 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1345
1346 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1347 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001348 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001349 "The write operation timed out");
1350 goto error;
1351 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1352 PyErr_SetString(PySSLErrorObject,
1353 "Underlying socket has been closed.");
1354 goto error;
1355 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1356 PyErr_SetString(PySSLErrorObject,
1357 "Underlying socket too large for select().");
1358 goto error;
1359 }
1360 do {
Victor Stinner9ee02032013-06-23 15:08:23 +02001361 len = (int)Py_MIN(buf.len, INT_MAX);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001362 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner9ee02032013-06-23 15:08:23 +02001363 len = SSL_write(self->ssl, buf.buf, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 err = SSL_get_error(self->ssl, len);
1365 PySSL_END_ALLOW_THREADS
1366 if (PyErr_CheckSignals()) {
1367 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001368 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001369 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001370 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001371 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001372 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001373 } else {
1374 sockstate = SOCKET_OPERATION_OK;
1375 }
1376 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001377 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 "The write operation timed out");
1379 goto error;
1380 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1381 PyErr_SetString(PySSLErrorObject,
1382 "Underlying socket has been closed.");
1383 goto error;
1384 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1385 break;
1386 }
1387 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001388
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001389 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001390 PyBuffer_Release(&buf);
1391 if (len > 0)
1392 return PyLong_FromLong(len);
1393 else
1394 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001395
1396error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001397 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001398 PyBuffer_Release(&buf);
1399 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001400}
1401
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001402PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001403"write(s) -> len\n\
1404\n\
1405Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001406of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001407
Antoine Pitrou152efa22010-05-16 18:19:27 +00001408static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001409{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001410 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001411
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001412 PySSL_BEGIN_ALLOW_THREADS
1413 count = SSL_pending(self->ssl);
1414 PySSL_END_ALLOW_THREADS
1415 if (count < 0)
1416 return PySSL_SetError(self, count, __FILE__, __LINE__);
1417 else
1418 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001419}
1420
1421PyDoc_STRVAR(PySSL_SSLpending_doc,
1422"pending() -> count\n\
1423\n\
1424Returns the number of already decrypted bytes available for read,\n\
1425pending on the connection.\n");
1426
Antoine Pitrou152efa22010-05-16 18:19:27 +00001427static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001428{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001429 PyObject *dest = NULL;
1430 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001431 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001432 int len, count;
1433 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001434 int sockstate;
1435 int err;
1436 int nonblocking;
1437 PySocketSockObject *sock
1438 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001439
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001440 if (((PyObject*)sock) == Py_None) {
1441 _setSSLError("Underlying socket connection gone",
1442 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1443 return NULL;
1444 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001445 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001446
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001447 buf.obj = NULL;
1448 buf.buf = NULL;
1449 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001450 goto error;
1451
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001452 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1453 dest = PyBytes_FromStringAndSize(NULL, len);
1454 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001455 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001456 mem = PyBytes_AS_STRING(dest);
1457 }
1458 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001459 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001460 mem = buf.buf;
1461 if (len <= 0 || len > buf.len) {
1462 len = (int) buf.len;
1463 if (buf.len != len) {
1464 PyErr_SetString(PyExc_OverflowError,
1465 "maximum length can't fit in a C 'int'");
1466 goto error;
1467 }
1468 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001469 }
1470
1471 /* just in case the blocking state of the socket has been changed */
1472 nonblocking = (sock->sock_timeout >= 0.0);
1473 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1474 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1475
1476 /* first check if there are bytes ready to be read */
1477 PySSL_BEGIN_ALLOW_THREADS
1478 count = SSL_pending(self->ssl);
1479 PySSL_END_ALLOW_THREADS
1480
1481 if (!count) {
1482 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1483 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001484 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001485 "The read operation timed out");
1486 goto error;
1487 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1488 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001489 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001490 goto error;
1491 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1492 count = 0;
1493 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001494 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001495 }
1496 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001497 PySSL_BEGIN_ALLOW_THREADS
1498 count = SSL_read(self->ssl, mem, len);
1499 err = SSL_get_error(self->ssl, count);
1500 PySSL_END_ALLOW_THREADS
1501 if (PyErr_CheckSignals())
1502 goto error;
1503 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001504 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001505 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001506 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001507 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1508 (SSL_get_shutdown(self->ssl) ==
1509 SSL_RECEIVED_SHUTDOWN))
1510 {
1511 count = 0;
1512 goto done;
1513 } else {
1514 sockstate = SOCKET_OPERATION_OK;
1515 }
1516 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001517 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001518 "The read operation timed out");
1519 goto error;
1520 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1521 break;
1522 }
1523 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1524 if (count <= 0) {
1525 PySSL_SetError(self, count, __FILE__, __LINE__);
1526 goto error;
1527 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001528
1529done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001530 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001531 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001532 _PyBytes_Resize(&dest, count);
1533 return dest;
1534 }
1535 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001536 PyBuffer_Release(&buf);
1537 return PyLong_FromLong(count);
1538 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001539
1540error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001541 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001542 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001543 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001544 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001545 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001546 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001547}
1548
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001549PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001550"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001551\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001552Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001553
Antoine Pitrou152efa22010-05-16 18:19:27 +00001554static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001555{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001556 int err, ssl_err, sockstate, nonblocking;
1557 int zeros = 0;
1558 PySocketSockObject *sock
1559 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001560
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001561 /* Guard against closed socket */
1562 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1563 _setSSLError("Underlying socket connection gone",
1564 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1565 return NULL;
1566 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001567 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568
1569 /* Just in case the blocking state of the socket has been changed */
1570 nonblocking = (sock->sock_timeout >= 0.0);
1571 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1572 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1573
1574 while (1) {
1575 PySSL_BEGIN_ALLOW_THREADS
1576 /* Disable read-ahead so that unwrap can work correctly.
1577 * Otherwise OpenSSL might read in too much data,
1578 * eating clear text data that happens to be
1579 * transmitted after the SSL shutdown.
1580 * Should be safe to call repeatedly everytime this
1581 * function is used and the shutdown_seen_zero != 0
1582 * condition is met.
1583 */
1584 if (self->shutdown_seen_zero)
1585 SSL_set_read_ahead(self->ssl, 0);
1586 err = SSL_shutdown(self->ssl);
1587 PySSL_END_ALLOW_THREADS
1588 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1589 if (err > 0)
1590 break;
1591 if (err == 0) {
1592 /* Don't loop endlessly; instead preserve legacy
1593 behaviour of trying SSL_shutdown() only twice.
1594 This looks necessary for OpenSSL < 0.9.8m */
1595 if (++zeros > 1)
1596 break;
1597 /* Shutdown was sent, now try receiving */
1598 self->shutdown_seen_zero = 1;
1599 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001600 }
1601
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001602 /* Possibly retry shutdown until timeout or failure */
1603 ssl_err = SSL_get_error(self->ssl, err);
1604 if (ssl_err == SSL_ERROR_WANT_READ)
1605 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1606 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1607 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1608 else
1609 break;
1610 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1611 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001612 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001613 "The read operation timed out");
1614 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001615 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001616 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001617 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001618 }
1619 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1620 PyErr_SetString(PySSLErrorObject,
1621 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001622 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001623 }
1624 else if (sockstate != SOCKET_OPERATION_OK)
1625 /* Retain the SSL error code */
1626 break;
1627 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001628
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001629 if (err < 0) {
1630 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001631 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001632 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001633 else
1634 /* It's already INCREF'ed */
1635 return (PyObject *) sock;
1636
1637error:
1638 Py_DECREF(sock);
1639 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001640}
1641
1642PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1643"shutdown(s) -> socket\n\
1644\n\
1645Does the SSL shutdown handshake with the remote end, and returns\n\
1646the underlying socket object.");
1647
Antoine Pitroud6494802011-07-21 01:11:30 +02001648#if HAVE_OPENSSL_FINISHED
1649static PyObject *
1650PySSL_tls_unique_cb(PySSLSocket *self)
1651{
1652 PyObject *retval = NULL;
1653 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001654 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001655
1656 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1657 /* if session is resumed XOR we are the client */
1658 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1659 }
1660 else {
1661 /* if a new session XOR we are the server */
1662 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1663 }
1664
1665 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001666 if (len == 0)
1667 Py_RETURN_NONE;
1668
1669 retval = PyBytes_FromStringAndSize(buf, len);
1670
1671 return retval;
1672}
1673
1674PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1675"tls_unique_cb() -> bytes\n\
1676\n\
1677Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1678\n\
1679If the TLS handshake is not yet complete, None is returned");
1680
1681#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001682
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001683static PyGetSetDef ssl_getsetlist[] = {
1684 {"context", (getter) PySSL_get_context,
1685 (setter) PySSL_set_context, PySSL_set_context_doc},
1686 {NULL}, /* sentinel */
1687};
1688
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001689static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001690 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1691 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1692 PySSL_SSLwrite_doc},
1693 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1694 PySSL_SSLread_doc},
1695 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1696 PySSL_SSLpending_doc},
1697 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1698 PySSL_peercert_doc},
1699 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001700#ifdef OPENSSL_NPN_NEGOTIATED
1701 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1702#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001703 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001704 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1705 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001706#if HAVE_OPENSSL_FINISHED
1707 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1708 PySSL_tls_unique_cb_doc},
1709#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001710 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001711};
1712
Antoine Pitrou152efa22010-05-16 18:19:27 +00001713static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001714 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001715 "_ssl._SSLSocket", /*tp_name*/
1716 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001717 0, /*tp_itemsize*/
1718 /* methods */
1719 (destructor)PySSL_dealloc, /*tp_dealloc*/
1720 0, /*tp_print*/
1721 0, /*tp_getattr*/
1722 0, /*tp_setattr*/
1723 0, /*tp_reserved*/
1724 0, /*tp_repr*/
1725 0, /*tp_as_number*/
1726 0, /*tp_as_sequence*/
1727 0, /*tp_as_mapping*/
1728 0, /*tp_hash*/
1729 0, /*tp_call*/
1730 0, /*tp_str*/
1731 0, /*tp_getattro*/
1732 0, /*tp_setattro*/
1733 0, /*tp_as_buffer*/
1734 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1735 0, /*tp_doc*/
1736 0, /*tp_traverse*/
1737 0, /*tp_clear*/
1738 0, /*tp_richcompare*/
1739 0, /*tp_weaklistoffset*/
1740 0, /*tp_iter*/
1741 0, /*tp_iternext*/
1742 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001743 0, /*tp_members*/
1744 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001745};
1746
Antoine Pitrou152efa22010-05-16 18:19:27 +00001747
1748/*
1749 * _SSLContext objects
1750 */
1751
1752static PyObject *
1753context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1754{
1755 char *kwlist[] = {"protocol", NULL};
1756 PySSLContext *self;
1757 int proto_version = PY_SSL_VERSION_SSL23;
1758 SSL_CTX *ctx = NULL;
1759
1760 if (!PyArg_ParseTupleAndKeywords(
1761 args, kwds, "i:_SSLContext", kwlist,
1762 &proto_version))
1763 return NULL;
1764
1765 PySSL_BEGIN_ALLOW_THREADS
1766 if (proto_version == PY_SSL_VERSION_TLS1)
1767 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01001768#if HAVE_TLSv1_2
1769 else if (proto_version == PY_SSL_VERSION_TLS1_1)
1770 ctx = SSL_CTX_new(TLSv1_1_method());
1771 else if (proto_version == PY_SSL_VERSION_TLS1_2)
1772 ctx = SSL_CTX_new(TLSv1_2_method());
1773#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001774 else if (proto_version == PY_SSL_VERSION_SSL3)
1775 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001776#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001777 else if (proto_version == PY_SSL_VERSION_SSL2)
1778 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001779#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001780 else if (proto_version == PY_SSL_VERSION_SSL23)
1781 ctx = SSL_CTX_new(SSLv23_method());
1782 else
1783 proto_version = -1;
1784 PySSL_END_ALLOW_THREADS
1785
1786 if (proto_version == -1) {
1787 PyErr_SetString(PyExc_ValueError,
1788 "invalid protocol version");
1789 return NULL;
1790 }
1791 if (ctx == NULL) {
1792 PyErr_SetString(PySSLErrorObject,
1793 "failed to allocate SSL context");
1794 return NULL;
1795 }
1796
1797 assert(type != NULL && type->tp_alloc != NULL);
1798 self = (PySSLContext *) type->tp_alloc(type, 0);
1799 if (self == NULL) {
1800 SSL_CTX_free(ctx);
1801 return NULL;
1802 }
1803 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001804#ifdef OPENSSL_NPN_NEGOTIATED
1805 self->npn_protocols = NULL;
1806#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001807#ifndef OPENSSL_NO_TLSEXT
1808 self->set_hostname = NULL;
1809#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001810 /* Defaults */
1811 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001812 SSL_CTX_set_options(self->ctx,
1813 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001814
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001815#define SID_CTX "Python"
1816 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1817 sizeof(SID_CTX));
1818#undef SID_CTX
1819
Antoine Pitrou152efa22010-05-16 18:19:27 +00001820 return (PyObject *)self;
1821}
1822
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001823static int
1824context_traverse(PySSLContext *self, visitproc visit, void *arg)
1825{
1826#ifndef OPENSSL_NO_TLSEXT
1827 Py_VISIT(self->set_hostname);
1828#endif
1829 return 0;
1830}
1831
1832static int
1833context_clear(PySSLContext *self)
1834{
1835#ifndef OPENSSL_NO_TLSEXT
1836 Py_CLEAR(self->set_hostname);
1837#endif
1838 return 0;
1839}
1840
Antoine Pitrou152efa22010-05-16 18:19:27 +00001841static void
1842context_dealloc(PySSLContext *self)
1843{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001844 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001845 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001846#ifdef OPENSSL_NPN_NEGOTIATED
1847 PyMem_Free(self->npn_protocols);
1848#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001849 Py_TYPE(self)->tp_free(self);
1850}
1851
1852static PyObject *
1853set_ciphers(PySSLContext *self, PyObject *args)
1854{
1855 int ret;
1856 const char *cipherlist;
1857
1858 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1859 return NULL;
1860 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1861 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001862 /* Clearing the error queue is necessary on some OpenSSL versions,
1863 otherwise the error will be reported again when another SSL call
1864 is done. */
1865 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001866 PyErr_SetString(PySSLErrorObject,
1867 "No cipher can be selected.");
1868 return NULL;
1869 }
1870 Py_RETURN_NONE;
1871}
1872
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001873#ifdef OPENSSL_NPN_NEGOTIATED
1874/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1875static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001876_advertiseNPN_cb(SSL *s,
1877 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001878 void *args)
1879{
1880 PySSLContext *ssl_ctx = (PySSLContext *) args;
1881
1882 if (ssl_ctx->npn_protocols == NULL) {
1883 *data = (unsigned char *) "";
1884 *len = 0;
1885 } else {
1886 *data = (unsigned char *) ssl_ctx->npn_protocols;
1887 *len = ssl_ctx->npn_protocols_len;
1888 }
1889
1890 return SSL_TLSEXT_ERR_OK;
1891}
1892/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1893static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001894_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001895 unsigned char **out, unsigned char *outlen,
1896 const unsigned char *server, unsigned int server_len,
1897 void *args)
1898{
1899 PySSLContext *ssl_ctx = (PySSLContext *) args;
1900
1901 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1902 int client_len;
1903
1904 if (client == NULL) {
1905 client = (unsigned char *) "";
1906 client_len = 0;
1907 } else {
1908 client_len = ssl_ctx->npn_protocols_len;
1909 }
1910
1911 SSL_select_next_proto(out, outlen,
1912 server, server_len,
1913 client, client_len);
1914
1915 return SSL_TLSEXT_ERR_OK;
1916}
1917#endif
1918
1919static PyObject *
1920_set_npn_protocols(PySSLContext *self, PyObject *args)
1921{
1922#ifdef OPENSSL_NPN_NEGOTIATED
1923 Py_buffer protos;
1924
1925 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1926 return NULL;
1927
Christian Heimes5cb31c92012-09-20 12:42:54 +02001928 if (self->npn_protocols != NULL) {
1929 PyMem_Free(self->npn_protocols);
1930 }
1931
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001932 self->npn_protocols = PyMem_Malloc(protos.len);
1933 if (self->npn_protocols == NULL) {
1934 PyBuffer_Release(&protos);
1935 return PyErr_NoMemory();
1936 }
1937 memcpy(self->npn_protocols, protos.buf, protos.len);
1938 self->npn_protocols_len = (int) protos.len;
1939
1940 /* set both server and client callbacks, because the context can
1941 * be used to create both types of sockets */
1942 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
1943 _advertiseNPN_cb,
1944 self);
1945 SSL_CTX_set_next_proto_select_cb(self->ctx,
1946 _selectNPN_cb,
1947 self);
1948
1949 PyBuffer_Release(&protos);
1950 Py_RETURN_NONE;
1951#else
1952 PyErr_SetString(PyExc_NotImplementedError,
1953 "The NPN extension requires OpenSSL 1.0.1 or later.");
1954 return NULL;
1955#endif
1956}
1957
Antoine Pitrou152efa22010-05-16 18:19:27 +00001958static PyObject *
1959get_verify_mode(PySSLContext *self, void *c)
1960{
1961 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1962 case SSL_VERIFY_NONE:
1963 return PyLong_FromLong(PY_SSL_CERT_NONE);
1964 case SSL_VERIFY_PEER:
1965 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1966 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1967 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1968 }
1969 PyErr_SetString(PySSLErrorObject,
1970 "invalid return value from SSL_CTX_get_verify_mode");
1971 return NULL;
1972}
1973
1974static int
1975set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1976{
1977 int n, mode;
1978 if (!PyArg_Parse(arg, "i", &n))
1979 return -1;
1980 if (n == PY_SSL_CERT_NONE)
1981 mode = SSL_VERIFY_NONE;
1982 else if (n == PY_SSL_CERT_OPTIONAL)
1983 mode = SSL_VERIFY_PEER;
1984 else if (n == PY_SSL_CERT_REQUIRED)
1985 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1986 else {
1987 PyErr_SetString(PyExc_ValueError,
1988 "invalid value for verify_mode");
1989 return -1;
1990 }
1991 SSL_CTX_set_verify(self->ctx, mode, NULL);
1992 return 0;
1993}
1994
1995static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001996get_options(PySSLContext *self, void *c)
1997{
1998 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1999}
2000
2001static int
2002set_options(PySSLContext *self, PyObject *arg, void *c)
2003{
2004 long new_opts, opts, set, clear;
2005 if (!PyArg_Parse(arg, "l", &new_opts))
2006 return -1;
2007 opts = SSL_CTX_get_options(self->ctx);
2008 clear = opts & ~new_opts;
2009 set = ~opts & new_opts;
2010 if (clear) {
2011#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2012 SSL_CTX_clear_options(self->ctx, clear);
2013#else
2014 PyErr_SetString(PyExc_ValueError,
2015 "can't clear options before OpenSSL 0.9.8m");
2016 return -1;
2017#endif
2018 }
2019 if (set)
2020 SSL_CTX_set_options(self->ctx, set);
2021 return 0;
2022}
2023
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002024typedef struct {
2025 PyThreadState *thread_state;
2026 PyObject *callable;
2027 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002028 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002029 int error;
2030} _PySSLPasswordInfo;
2031
2032static int
2033_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2034 const char *bad_type_error)
2035{
2036 /* Set the password and size fields of a _PySSLPasswordInfo struct
2037 from a unicode, bytes, or byte array object.
2038 The password field will be dynamically allocated and must be freed
2039 by the caller */
2040 PyObject *password_bytes = NULL;
2041 const char *data = NULL;
2042 Py_ssize_t size;
2043
2044 if (PyUnicode_Check(password)) {
2045 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2046 if (!password_bytes) {
2047 goto error;
2048 }
2049 data = PyBytes_AS_STRING(password_bytes);
2050 size = PyBytes_GET_SIZE(password_bytes);
2051 } else if (PyBytes_Check(password)) {
2052 data = PyBytes_AS_STRING(password);
2053 size = PyBytes_GET_SIZE(password);
2054 } else if (PyByteArray_Check(password)) {
2055 data = PyByteArray_AS_STRING(password);
2056 size = PyByteArray_GET_SIZE(password);
2057 } else {
2058 PyErr_SetString(PyExc_TypeError, bad_type_error);
2059 goto error;
2060 }
2061
Victor Stinner9ee02032013-06-23 15:08:23 +02002062 if (size > (Py_ssize_t)INT_MAX) {
2063 PyErr_Format(PyExc_ValueError,
2064 "password cannot be longer than %d bytes", INT_MAX);
2065 goto error;
2066 }
2067
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002068 free(pw_info->password);
2069 pw_info->password = malloc(size);
2070 if (!pw_info->password) {
2071 PyErr_SetString(PyExc_MemoryError,
2072 "unable to allocate password buffer");
2073 goto error;
2074 }
2075 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002076 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002077
2078 Py_XDECREF(password_bytes);
2079 return 1;
2080
2081error:
2082 Py_XDECREF(password_bytes);
2083 return 0;
2084}
2085
2086static int
2087_password_callback(char *buf, int size, int rwflag, void *userdata)
2088{
2089 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2090 PyObject *fn_ret = NULL;
2091
2092 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2093
2094 if (pw_info->callable) {
2095 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2096 if (!fn_ret) {
2097 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2098 core python API, so we could use it to add a frame here */
2099 goto error;
2100 }
2101
2102 if (!_pwinfo_set(pw_info, fn_ret,
2103 "password callback must return a string")) {
2104 goto error;
2105 }
2106 Py_CLEAR(fn_ret);
2107 }
2108
2109 if (pw_info->size > size) {
2110 PyErr_Format(PyExc_ValueError,
2111 "password cannot be longer than %d bytes", size);
2112 goto error;
2113 }
2114
2115 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2116 memcpy(buf, pw_info->password, pw_info->size);
2117 return pw_info->size;
2118
2119error:
2120 Py_XDECREF(fn_ret);
2121 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2122 pw_info->error = 1;
2123 return -1;
2124}
2125
Antoine Pitroub5218772010-05-21 09:56:06 +00002126static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002127load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2128{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002129 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2130 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002131 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002132 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2133 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2134 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002135 int r;
2136
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002137 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002138 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002139 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002140 "O|OO:load_cert_chain", kwlist,
2141 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002142 return NULL;
2143 if (keyfile == Py_None)
2144 keyfile = NULL;
2145 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2146 PyErr_SetString(PyExc_TypeError,
2147 "certfile should be a valid filesystem path");
2148 return NULL;
2149 }
2150 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2151 PyErr_SetString(PyExc_TypeError,
2152 "keyfile should be a valid filesystem path");
2153 goto error;
2154 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002155 if (password && password != Py_None) {
2156 if (PyCallable_Check(password)) {
2157 pw_info.callable = password;
2158 } else if (!_pwinfo_set(&pw_info, password,
2159 "password should be a string or callable")) {
2160 goto error;
2161 }
2162 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2163 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2164 }
2165 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002166 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2167 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002168 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002169 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002170 if (pw_info.error) {
2171 ERR_clear_error();
2172 /* the password callback has already set the error information */
2173 }
2174 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002175 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002176 PyErr_SetFromErrno(PyExc_IOError);
2177 }
2178 else {
2179 _setSSLError(NULL, 0, __FILE__, __LINE__);
2180 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002181 goto error;
2182 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002183 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002184 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002185 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2186 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002187 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2188 Py_CLEAR(keyfile_bytes);
2189 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002190 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002191 if (pw_info.error) {
2192 ERR_clear_error();
2193 /* the password callback has already set the error information */
2194 }
2195 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002196 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002197 PyErr_SetFromErrno(PyExc_IOError);
2198 }
2199 else {
2200 _setSSLError(NULL, 0, __FILE__, __LINE__);
2201 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002202 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002203 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002204 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002205 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002206 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002207 if (r != 1) {
2208 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002209 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002210 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002211 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2212 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2213 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002214 Py_RETURN_NONE;
2215
2216error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002217 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2218 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2219 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002220 Py_XDECREF(keyfile_bytes);
2221 Py_XDECREF(certfile_bytes);
2222 return NULL;
2223}
2224
2225static PyObject *
2226load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2227{
2228 char *kwlist[] = {"cafile", "capath", NULL};
2229 PyObject *cafile = NULL, *capath = NULL;
2230 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2231 const char *cafile_buf = NULL, *capath_buf = NULL;
2232 int r;
2233
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002234 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002235 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2236 "|OO:load_verify_locations", kwlist,
2237 &cafile, &capath))
2238 return NULL;
2239 if (cafile == Py_None)
2240 cafile = NULL;
2241 if (capath == Py_None)
2242 capath = NULL;
2243 if (cafile == NULL && capath == NULL) {
2244 PyErr_SetString(PyExc_TypeError,
2245 "cafile and capath cannot be both omitted");
2246 return NULL;
2247 }
2248 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2249 PyErr_SetString(PyExc_TypeError,
2250 "cafile should be a valid filesystem path");
2251 return NULL;
2252 }
2253 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002254 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002255 PyErr_SetString(PyExc_TypeError,
2256 "capath should be a valid filesystem path");
2257 return NULL;
2258 }
2259 if (cafile)
2260 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2261 if (capath)
2262 capath_buf = PyBytes_AS_STRING(capath_bytes);
2263 PySSL_BEGIN_ALLOW_THREADS
2264 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2265 PySSL_END_ALLOW_THREADS
2266 Py_XDECREF(cafile_bytes);
2267 Py_XDECREF(capath_bytes);
2268 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002269 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002270 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002271 PyErr_SetFromErrno(PyExc_IOError);
2272 }
2273 else {
2274 _setSSLError(NULL, 0, __FILE__, __LINE__);
2275 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002276 return NULL;
2277 }
2278 Py_RETURN_NONE;
2279}
2280
2281static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002282load_dh_params(PySSLContext *self, PyObject *filepath)
2283{
2284 FILE *f;
2285 DH *dh;
2286
2287 f = _Py_fopen(filepath, "rb");
2288 if (f == NULL) {
2289 if (!PyErr_Occurred())
2290 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2291 return NULL;
2292 }
2293 errno = 0;
2294 PySSL_BEGIN_ALLOW_THREADS
2295 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002296 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002297 PySSL_END_ALLOW_THREADS
2298 if (dh == NULL) {
2299 if (errno != 0) {
2300 ERR_clear_error();
2301 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2302 }
2303 else {
2304 _setSSLError(NULL, 0, __FILE__, __LINE__);
2305 }
2306 return NULL;
2307 }
2308 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2309 _setSSLError(NULL, 0, __FILE__, __LINE__);
2310 DH_free(dh);
2311 Py_RETURN_NONE;
2312}
2313
2314static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002315context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2316{
Antoine Pitroud5323212010-10-22 18:19:07 +00002317 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002318 PySocketSockObject *sock;
2319 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002320 char *hostname = NULL;
2321 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002322
Antoine Pitroud5323212010-10-22 18:19:07 +00002323 /* server_hostname is either None (or absent), or to be encoded
2324 using the idna encoding. */
2325 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002326 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002327 &sock, &server_side,
2328 Py_TYPE(Py_None), &hostname_obj)) {
2329 PyErr_Clear();
2330 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2331 PySocketModule.Sock_Type,
2332 &sock, &server_side,
2333 "idna", &hostname))
2334 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002335#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002336 PyMem_Free(hostname);
2337 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2338 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002339 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002340#endif
2341 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002342
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002343 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002344 hostname);
2345 if (hostname != NULL)
2346 PyMem_Free(hostname);
2347 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002348}
2349
Antoine Pitroub0182c82010-10-12 20:09:02 +00002350static PyObject *
2351session_stats(PySSLContext *self, PyObject *unused)
2352{
2353 int r;
2354 PyObject *value, *stats = PyDict_New();
2355 if (!stats)
2356 return NULL;
2357
2358#define ADD_STATS(SSL_NAME, KEY_NAME) \
2359 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2360 if (value == NULL) \
2361 goto error; \
2362 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2363 Py_DECREF(value); \
2364 if (r < 0) \
2365 goto error;
2366
2367 ADD_STATS(number, "number");
2368 ADD_STATS(connect, "connect");
2369 ADD_STATS(connect_good, "connect_good");
2370 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2371 ADD_STATS(accept, "accept");
2372 ADD_STATS(accept_good, "accept_good");
2373 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2374 ADD_STATS(accept, "accept");
2375 ADD_STATS(hits, "hits");
2376 ADD_STATS(misses, "misses");
2377 ADD_STATS(timeouts, "timeouts");
2378 ADD_STATS(cache_full, "cache_full");
2379
2380#undef ADD_STATS
2381
2382 return stats;
2383
2384error:
2385 Py_DECREF(stats);
2386 return NULL;
2387}
2388
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002389static PyObject *
2390set_default_verify_paths(PySSLContext *self, PyObject *unused)
2391{
2392 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2393 _setSSLError(NULL, 0, __FILE__, __LINE__);
2394 return NULL;
2395 }
2396 Py_RETURN_NONE;
2397}
2398
Antoine Pitrou501da612011-12-21 09:27:41 +01002399#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002400static PyObject *
2401set_ecdh_curve(PySSLContext *self, PyObject *name)
2402{
2403 PyObject *name_bytes;
2404 int nid;
2405 EC_KEY *key;
2406
2407 if (!PyUnicode_FSConverter(name, &name_bytes))
2408 return NULL;
2409 assert(PyBytes_Check(name_bytes));
2410 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2411 Py_DECREF(name_bytes);
2412 if (nid == 0) {
2413 PyErr_Format(PyExc_ValueError,
2414 "unknown elliptic curve name %R", name);
2415 return NULL;
2416 }
2417 key = EC_KEY_new_by_curve_name(nid);
2418 if (key == NULL) {
2419 _setSSLError(NULL, 0, __FILE__, __LINE__);
2420 return NULL;
2421 }
2422 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2423 EC_KEY_free(key);
2424 Py_RETURN_NONE;
2425}
Antoine Pitrou501da612011-12-21 09:27:41 +01002426#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002427
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002428#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002429static int
2430_servername_callback(SSL *s, int *al, void *args)
2431{
2432 int ret;
2433 PySSLContext *ssl_ctx = (PySSLContext *) args;
2434 PySSLSocket *ssl;
2435 PyObject *servername_o;
2436 PyObject *servername_idna;
2437 PyObject *result;
2438 /* The high-level ssl.SSLSocket object */
2439 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002440 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002441#ifdef WITH_THREAD
2442 PyGILState_STATE gstate = PyGILState_Ensure();
2443#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002444
2445 if (ssl_ctx->set_hostname == NULL) {
2446 /* remove race condition in this the call back while if removing the
2447 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002448#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002449 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002450#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002451 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002452 }
2453
2454 ssl = SSL_get_app_data(s);
2455 assert(PySSLSocket_Check(ssl));
2456 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2457 Py_INCREF(ssl_socket);
2458 if (ssl_socket == Py_None) {
2459 goto error;
2460 }
2461
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002462 if (servername == NULL) {
2463 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2464 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002465 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002466 else {
2467 servername_o = PyBytes_FromString(servername);
2468 if (servername_o == NULL) {
2469 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2470 goto error;
2471 }
2472 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2473 if (servername_idna == NULL) {
2474 PyErr_WriteUnraisable(servername_o);
2475 Py_DECREF(servername_o);
2476 goto error;
2477 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002478 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002479 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2480 servername_idna, ssl_ctx, NULL);
2481 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002482 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002483 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002484
2485 if (result == NULL) {
2486 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2487 *al = SSL_AD_HANDSHAKE_FAILURE;
2488 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2489 }
2490 else {
2491 if (result != Py_None) {
2492 *al = (int) PyLong_AsLong(result);
2493 if (PyErr_Occurred()) {
2494 PyErr_WriteUnraisable(result);
2495 *al = SSL_AD_INTERNAL_ERROR;
2496 }
2497 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2498 }
2499 else {
2500 ret = SSL_TLSEXT_ERR_OK;
2501 }
2502 Py_DECREF(result);
2503 }
2504
Stefan Krah20d60802013-01-17 17:07:17 +01002505#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002506 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002507#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002508 return ret;
2509
2510error:
2511 Py_DECREF(ssl_socket);
2512 *al = SSL_AD_INTERNAL_ERROR;
2513 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002514#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002515 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002516#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002517 return ret;
2518}
Antoine Pitroua5963382013-03-30 16:39:00 +01002519#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002520
2521PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2522"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002523\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002524This sets a callback that will be called when a server name is provided by\n\
2525the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002526\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002527If the argument is None then the callback is disabled. The method is called\n\
2528with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002529See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002530
2531static PyObject *
2532set_servername_callback(PySSLContext *self, PyObject *args)
2533{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002534#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002535 PyObject *cb;
2536
2537 if (!PyArg_ParseTuple(args, "O", &cb))
2538 return NULL;
2539
2540 Py_CLEAR(self->set_hostname);
2541 if (cb == Py_None) {
2542 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2543 }
2544 else {
2545 if (!PyCallable_Check(cb)) {
2546 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2547 PyErr_SetString(PyExc_TypeError,
2548 "not a callable object");
2549 return NULL;
2550 }
2551 Py_INCREF(cb);
2552 self->set_hostname = cb;
2553 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
2554 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
2555 }
2556 Py_RETURN_NONE;
2557#else
2558 PyErr_SetString(PyExc_NotImplementedError,
2559 "The TLS extension servername callback, "
2560 "SSL_CTX_set_tlsext_servername_callback, "
2561 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002562 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002563#endif
2564}
2565
Christian Heimes9a5395a2013-06-17 15:44:12 +02002566PyDoc_STRVAR(PySSL_get_stats_doc,
2567"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
2568\n\
2569Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
2570CA extension and certificate revocation lists inside the context's cert\n\
2571store.\n\
2572NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2573been used at least once.");
2574
2575static PyObject *
2576cert_store_stats(PySSLContext *self)
2577{
2578 X509_STORE *store;
2579 X509_OBJECT *obj;
2580 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
2581
2582 store = SSL_CTX_get_cert_store(self->ctx);
2583 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2584 obj = sk_X509_OBJECT_value(store->objs, i);
2585 switch (obj->type) {
2586 case X509_LU_X509:
2587 x509++;
2588 if (X509_check_ca(obj->data.x509)) {
2589 ca++;
2590 }
2591 break;
2592 case X509_LU_CRL:
2593 crl++;
2594 break;
2595 case X509_LU_PKEY:
2596 pkey++;
2597 break;
2598 default:
2599 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
2600 * As far as I can tell they are internal states and never
2601 * stored in a cert store */
2602 break;
2603 }
2604 }
2605 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
2606 "x509_ca", ca);
2607}
2608
2609PyDoc_STRVAR(PySSL_get_ca_certs_doc,
2610"get_ca_certs([der=False]) -> list of loaded certificate\n\
2611\n\
2612Returns a list of dicts with information of loaded CA certs. If the\n\
2613optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
2614NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2615been used at least once.");
2616
2617static PyObject *
2618get_ca_certs(PySSLContext *self, PyObject *args)
2619{
2620 X509_STORE *store;
2621 PyObject *ci = NULL, *rlist = NULL;
2622 int i;
2623 int binary_mode = 0;
2624
2625 if (!PyArg_ParseTuple(args, "|p:get_ca_certs", &binary_mode)) {
2626 return NULL;
2627 }
2628
2629 if ((rlist = PyList_New(0)) == NULL) {
2630 return NULL;
2631 }
2632
2633 store = SSL_CTX_get_cert_store(self->ctx);
2634 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2635 X509_OBJECT *obj;
2636 X509 *cert;
2637
2638 obj = sk_X509_OBJECT_value(store->objs, i);
2639 if (obj->type != X509_LU_X509) {
2640 /* not a x509 cert */
2641 continue;
2642 }
2643 /* CA for any purpose */
2644 cert = obj->data.x509;
2645 if (!X509_check_ca(cert)) {
2646 continue;
2647 }
2648 if (binary_mode) {
2649 ci = _certificate_to_der(cert);
2650 } else {
2651 ci = _decode_certificate(cert);
2652 }
2653 if (ci == NULL) {
2654 goto error;
2655 }
2656 if (PyList_Append(rlist, ci) == -1) {
2657 goto error;
2658 }
2659 Py_CLEAR(ci);
2660 }
2661 return rlist;
2662
2663 error:
2664 Py_XDECREF(ci);
2665 Py_XDECREF(rlist);
2666 return NULL;
2667}
2668
2669
Antoine Pitrou152efa22010-05-16 18:19:27 +00002670static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002671 {"options", (getter) get_options,
2672 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002673 {"verify_mode", (getter) get_verify_mode,
2674 (setter) set_verify_mode, NULL},
2675 {NULL}, /* sentinel */
2676};
2677
2678static struct PyMethodDef context_methods[] = {
2679 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2680 METH_VARARGS | METH_KEYWORDS, NULL},
2681 {"set_ciphers", (PyCFunction) set_ciphers,
2682 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002683 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2684 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002685 {"load_cert_chain", (PyCFunction) load_cert_chain,
2686 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002687 {"load_dh_params", (PyCFunction) load_dh_params,
2688 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002689 {"load_verify_locations", (PyCFunction) load_verify_locations,
2690 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002691 {"session_stats", (PyCFunction) session_stats,
2692 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002693 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2694 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002695#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002696 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2697 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002698#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002699 {"set_servername_callback", (PyCFunction) set_servername_callback,
2700 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02002701 {"cert_store_stats", (PyCFunction) cert_store_stats,
2702 METH_NOARGS, PySSL_get_stats_doc},
2703 {"get_ca_certs", (PyCFunction) get_ca_certs,
2704 METH_VARARGS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002705 {NULL, NULL} /* sentinel */
2706};
2707
2708static PyTypeObject PySSLContext_Type = {
2709 PyVarObject_HEAD_INIT(NULL, 0)
2710 "_ssl._SSLContext", /*tp_name*/
2711 sizeof(PySSLContext), /*tp_basicsize*/
2712 0, /*tp_itemsize*/
2713 (destructor)context_dealloc, /*tp_dealloc*/
2714 0, /*tp_print*/
2715 0, /*tp_getattr*/
2716 0, /*tp_setattr*/
2717 0, /*tp_reserved*/
2718 0, /*tp_repr*/
2719 0, /*tp_as_number*/
2720 0, /*tp_as_sequence*/
2721 0, /*tp_as_mapping*/
2722 0, /*tp_hash*/
2723 0, /*tp_call*/
2724 0, /*tp_str*/
2725 0, /*tp_getattro*/
2726 0, /*tp_setattro*/
2727 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002728 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002729 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002730 (traverseproc) context_traverse, /*tp_traverse*/
2731 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002732 0, /*tp_richcompare*/
2733 0, /*tp_weaklistoffset*/
2734 0, /*tp_iter*/
2735 0, /*tp_iternext*/
2736 context_methods, /*tp_methods*/
2737 0, /*tp_members*/
2738 context_getsetlist, /*tp_getset*/
2739 0, /*tp_base*/
2740 0, /*tp_dict*/
2741 0, /*tp_descr_get*/
2742 0, /*tp_descr_set*/
2743 0, /*tp_dictoffset*/
2744 0, /*tp_init*/
2745 0, /*tp_alloc*/
2746 context_new, /*tp_new*/
2747};
2748
2749
2750
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002751#ifdef HAVE_OPENSSL_RAND
2752
2753/* helper routines for seeding the SSL PRNG */
2754static PyObject *
2755PySSL_RAND_add(PyObject *self, PyObject *args)
2756{
2757 char *buf;
2758 int len;
2759 double entropy;
2760
2761 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002762 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002763 RAND_add(buf, len, entropy);
2764 Py_INCREF(Py_None);
2765 return Py_None;
2766}
2767
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002768PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002769"RAND_add(string, entropy)\n\
2770\n\
2771Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002772bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002773
2774static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002775PySSL_RAND(int len, int pseudo)
2776{
2777 int ok;
2778 PyObject *bytes;
2779 unsigned long err;
2780 const char *errstr;
2781 PyObject *v;
2782
2783 bytes = PyBytes_FromStringAndSize(NULL, len);
2784 if (bytes == NULL)
2785 return NULL;
2786 if (pseudo) {
2787 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2788 if (ok == 0 || ok == 1)
2789 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2790 }
2791 else {
2792 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2793 if (ok == 1)
2794 return bytes;
2795 }
2796 Py_DECREF(bytes);
2797
2798 err = ERR_get_error();
2799 errstr = ERR_reason_error_string(err);
2800 v = Py_BuildValue("(ks)", err, errstr);
2801 if (v != NULL) {
2802 PyErr_SetObject(PySSLErrorObject, v);
2803 Py_DECREF(v);
2804 }
2805 return NULL;
2806}
2807
2808static PyObject *
2809PySSL_RAND_bytes(PyObject *self, PyObject *args)
2810{
2811 int len;
2812 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2813 return NULL;
2814 return PySSL_RAND(len, 0);
2815}
2816
2817PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2818"RAND_bytes(n) -> bytes\n\
2819\n\
2820Generate n cryptographically strong pseudo-random bytes.");
2821
2822static PyObject *
2823PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2824{
2825 int len;
2826 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2827 return NULL;
2828 return PySSL_RAND(len, 1);
2829}
2830
2831PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2832"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2833\n\
2834Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2835generated are cryptographically strong.");
2836
2837static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002838PySSL_RAND_status(PyObject *self)
2839{
Christian Heimes217cfd12007-12-02 14:31:20 +00002840 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002841}
2842
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002843PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002844"RAND_status() -> 0 or 1\n\
2845\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002846Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2847It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2848using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002849
2850static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002851PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002852{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002853 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002854 int bytes;
2855
Jesus Ceac8754a12012-09-11 02:00:58 +02002856 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002857 PyUnicode_FSConverter, &path))
2858 return NULL;
2859
2860 bytes = RAND_egd(PyBytes_AsString(path));
2861 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002862 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002863 PyErr_SetString(PySSLErrorObject,
2864 "EGD connection failed or EGD did not return "
2865 "enough data to seed the PRNG");
2866 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002867 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002868 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002869}
2870
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002871PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002872"RAND_egd(path) -> bytes\n\
2873\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002874Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2875Returns number of bytes read. Raises SSLError if connection to EGD\n\
2876fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002877
2878#endif
2879
Christian Heimes6d7ad132013-06-09 18:02:55 +02002880PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
2881"get_default_verify_paths() -> tuple\n\
2882\n\
2883Return search paths and environment vars that are used by SSLContext's\n\
2884set_default_verify_paths() to load default CAs. The values are\n\
2885'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
2886
2887static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02002888PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02002889{
2890 PyObject *ofile_env = NULL;
2891 PyObject *ofile = NULL;
2892 PyObject *odir_env = NULL;
2893 PyObject *odir = NULL;
2894
2895#define convert(info, target) { \
2896 const char *tmp = (info); \
2897 target = NULL; \
2898 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
2899 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
2900 target = PyBytes_FromString(tmp); } \
2901 if (!target) goto error; \
2902 } while(0)
2903
2904 convert(X509_get_default_cert_file_env(), ofile_env);
2905 convert(X509_get_default_cert_file(), ofile);
2906 convert(X509_get_default_cert_dir_env(), odir_env);
2907 convert(X509_get_default_cert_dir(), odir);
2908#undef convert
2909
Christian Heimes200bb1b2013-06-14 15:14:29 +02002910 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02002911
2912 error:
2913 Py_XDECREF(ofile_env);
2914 Py_XDECREF(ofile);
2915 Py_XDECREF(odir_env);
2916 Py_XDECREF(odir);
2917 return NULL;
2918}
2919
Christian Heimes46bebee2013-06-09 19:03:31 +02002920#ifdef _MSC_VER
2921PyDoc_STRVAR(PySSL_enum_cert_store_doc,
2922"enum_cert_store(store_name, cert_type='certificate') -> []\n\
2923\n\
2924Retrieve certificates from Windows' cert store. store_name may be one of\n\
2925'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
2926cert_type must be either 'certificate' or 'crl'.\n\
2927The function returns a list of (bytes, encoding_type) tuples. The\n\
2928encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
2929PKCS_7_ASN_ENCODING.");
Bill Janssen40a0f662008-08-12 16:56:25 +00002930
Christian Heimes46bebee2013-06-09 19:03:31 +02002931static PyObject *
2932PySSL_enum_cert_store(PyObject *self, PyObject *args, PyObject *kwds)
2933{
2934 char *kwlist[] = {"store_name", "cert_type", NULL};
2935 char *store_name;
2936 char *cert_type = "certificate";
2937 HCERTSTORE hStore = NULL;
2938 PyObject *result = NULL;
2939 PyObject *tup = NULL, *cert = NULL, *enc = NULL;
2940 int ok = 1;
2941
2942 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_cert_store",
2943 kwlist, &store_name, &cert_type)) {
2944 return NULL;
2945 }
2946
2947 if ((strcmp(cert_type, "certificate") != 0) &&
2948 (strcmp(cert_type, "crl") != 0)) {
2949 return PyErr_Format(PyExc_ValueError,
2950 "cert_type must be 'certificate' or 'crl', "
2951 "not %.100s", cert_type);
2952 }
2953
2954 if ((result = PyList_New(0)) == NULL) {
2955 return NULL;
2956 }
2957
2958 if ((hStore = CertOpenSystemStore(NULL, store_name)) == NULL) {
2959 Py_DECREF(result);
2960 return PyErr_SetFromWindowsErr(GetLastError());
2961 }
2962
2963 if (strcmp(cert_type, "certificate") == 0) {
2964 PCCERT_CONTEXT pCertCtx = NULL;
2965 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
2966 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
2967 pCertCtx->cbCertEncoded);
2968 if (!cert) {
2969 ok = 0;
2970 break;
2971 }
2972 if ((enc = PyLong_FromLong(pCertCtx->dwCertEncodingType)) == NULL) {
2973 ok = 0;
2974 break;
2975 }
2976 if ((tup = PyTuple_New(2)) == NULL) {
2977 ok = 0;
2978 break;
2979 }
2980 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
2981 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
2982
2983 if (PyList_Append(result, tup) < 0) {
2984 ok = 0;
2985 break;
2986 }
2987 Py_CLEAR(tup);
2988 }
2989 if (pCertCtx) {
2990 /* loop ended with an error, need to clean up context manually */
2991 CertFreeCertificateContext(pCertCtx);
2992 }
2993 } else {
2994 PCCRL_CONTEXT pCrlCtx = NULL;
2995 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
2996 cert = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
2997 pCrlCtx->cbCrlEncoded);
2998 if (!cert) {
2999 ok = 0;
3000 break;
3001 }
3002 if ((enc = PyLong_FromLong(pCrlCtx->dwCertEncodingType)) == NULL) {
3003 ok = 0;
3004 break;
3005 }
3006 if ((tup = PyTuple_New(2)) == NULL) {
3007 ok = 0;
3008 break;
3009 }
3010 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3011 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3012
3013 if (PyList_Append(result, tup) < 0) {
3014 ok = 0;
3015 break;
3016 }
3017 Py_CLEAR(tup);
3018 }
3019 if (pCrlCtx) {
3020 /* loop ended with an error, need to clean up context manually */
3021 CertFreeCRLContext(pCrlCtx);
3022 }
3023 }
3024
3025 /* In error cases cert, enc and tup may not be NULL */
3026 Py_XDECREF(cert);
3027 Py_XDECREF(enc);
3028 Py_XDECREF(tup);
3029
3030 if (!CertCloseStore(hStore, 0)) {
3031 /* This error case might shadow another exception.*/
3032 Py_DECREF(result);
3033 return PyErr_SetFromWindowsErr(GetLastError());
3034 }
3035 if (ok) {
3036 return result;
3037 } else {
3038 Py_DECREF(result);
3039 return NULL;
3040 }
3041}
3042#endif
Bill Janssen40a0f662008-08-12 16:56:25 +00003043
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003044/* List of functions exported by this module. */
3045
3046static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003047 {"_test_decode_cert", PySSL_test_decode_certificate,
3048 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003049#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003050 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3051 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003052 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3053 PySSL_RAND_bytes_doc},
3054 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3055 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003056 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003057 PySSL_RAND_egd_doc},
3058 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3059 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003060#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003061 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003062 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003063#ifdef _MSC_VER
3064 {"enum_cert_store", (PyCFunction)PySSL_enum_cert_store,
3065 METH_VARARGS | METH_KEYWORDS, PySSL_enum_cert_store_doc},
3066#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003067 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003068};
3069
3070
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003071#ifdef WITH_THREAD
3072
3073/* an implementation of OpenSSL threading operations in terms
3074 of the Python C thread library */
3075
3076static PyThread_type_lock *_ssl_locks = NULL;
3077
3078static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003079 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003080}
3081
Bill Janssen6e027db2007-11-15 22:23:56 +00003082static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003083 (int mode, int n, const char *file, int line) {
3084 /* this function is needed to perform locking on shared data
3085 structures. (Note that OpenSSL uses a number of global data
3086 structures that will be implicitly shared whenever multiple
3087 threads use OpenSSL.) Multi-threaded applications will
3088 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003089
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003090 locking_function() must be able to handle up to
3091 CRYPTO_num_locks() different mutex locks. It sets the n-th
3092 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003093
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003094 file and line are the file number of the function setting the
3095 lock. They can be useful for debugging.
3096 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003097
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003098 if ((_ssl_locks == NULL) ||
3099 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3100 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003101
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003102 if (mode & CRYPTO_LOCK) {
3103 PyThread_acquire_lock(_ssl_locks[n], 1);
3104 } else {
3105 PyThread_release_lock(_ssl_locks[n]);
3106 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003107}
3108
3109static int _setup_ssl_threads(void) {
3110
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003111 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003112
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003113 if (_ssl_locks == NULL) {
3114 _ssl_locks_count = CRYPTO_num_locks();
3115 _ssl_locks = (PyThread_type_lock *)
3116 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
3117 if (_ssl_locks == NULL)
3118 return 0;
3119 memset(_ssl_locks, 0,
3120 sizeof(PyThread_type_lock) * _ssl_locks_count);
3121 for (i = 0; i < _ssl_locks_count; i++) {
3122 _ssl_locks[i] = PyThread_allocate_lock();
3123 if (_ssl_locks[i] == NULL) {
3124 unsigned int j;
3125 for (j = 0; j < i; j++) {
3126 PyThread_free_lock(_ssl_locks[j]);
3127 }
3128 free(_ssl_locks);
3129 return 0;
3130 }
3131 }
3132 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
3133 CRYPTO_set_id_callback(_ssl_thread_id_function);
3134 }
3135 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003136}
3137
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003138#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003139
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003140PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003141"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003142for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003143
Martin v. Löwis1a214512008-06-11 05:26:20 +00003144
3145static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003146 PyModuleDef_HEAD_INIT,
3147 "_ssl",
3148 module_doc,
3149 -1,
3150 PySSL_methods,
3151 NULL,
3152 NULL,
3153 NULL,
3154 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003155};
3156
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003157
3158static void
3159parse_openssl_version(unsigned long libver,
3160 unsigned int *major, unsigned int *minor,
3161 unsigned int *fix, unsigned int *patch,
3162 unsigned int *status)
3163{
3164 *status = libver & 0xF;
3165 libver >>= 4;
3166 *patch = libver & 0xFF;
3167 libver >>= 8;
3168 *fix = libver & 0xFF;
3169 libver >>= 8;
3170 *minor = libver & 0xFF;
3171 libver >>= 8;
3172 *major = libver & 0xFF;
3173}
3174
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003175PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003176PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003177{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003178 PyObject *m, *d, *r;
3179 unsigned long libver;
3180 unsigned int major, minor, fix, patch, status;
3181 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003182 struct py_ssl_error_code *errcode;
3183 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003184
Antoine Pitrou152efa22010-05-16 18:19:27 +00003185 if (PyType_Ready(&PySSLContext_Type) < 0)
3186 return NULL;
3187 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003188 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003189
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003190 m = PyModule_Create(&_sslmodule);
3191 if (m == NULL)
3192 return NULL;
3193 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003194
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003195 /* Load _socket module and its C API */
3196 socket_api = PySocketModule_ImportModuleAndAPI();
3197 if (!socket_api)
3198 return NULL;
3199 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003200
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003201 /* Init OpenSSL */
3202 SSL_load_error_strings();
3203 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003204#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003205 /* note that this will start threading if not already started */
3206 if (!_setup_ssl_threads()) {
3207 return NULL;
3208 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003209#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003210 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003211
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003212 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003213 sslerror_type_slots[0].pfunc = PyExc_OSError;
3214 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003215 if (PySSLErrorObject == NULL)
3216 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003217
Antoine Pitrou41032a62011-10-27 23:56:55 +02003218 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3219 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3220 PySSLErrorObject, NULL);
3221 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3222 "ssl.SSLWantReadError", SSLWantReadError_doc,
3223 PySSLErrorObject, NULL);
3224 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3225 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3226 PySSLErrorObject, NULL);
3227 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3228 "ssl.SSLSyscallError", SSLSyscallError_doc,
3229 PySSLErrorObject, NULL);
3230 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3231 "ssl.SSLEOFError", SSLEOFError_doc,
3232 PySSLErrorObject, NULL);
3233 if (PySSLZeroReturnErrorObject == NULL
3234 || PySSLWantReadErrorObject == NULL
3235 || PySSLWantWriteErrorObject == NULL
3236 || PySSLSyscallErrorObject == NULL
3237 || PySSLEOFErrorObject == NULL)
3238 return NULL;
3239 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3240 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3241 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3242 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3243 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3244 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003245 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003246 if (PyDict_SetItemString(d, "_SSLContext",
3247 (PyObject *)&PySSLContext_Type) != 0)
3248 return NULL;
3249 if (PyDict_SetItemString(d, "_SSLSocket",
3250 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003251 return NULL;
3252 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3253 PY_SSL_ERROR_ZERO_RETURN);
3254 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3255 PY_SSL_ERROR_WANT_READ);
3256 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3257 PY_SSL_ERROR_WANT_WRITE);
3258 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3259 PY_SSL_ERROR_WANT_X509_LOOKUP);
3260 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3261 PY_SSL_ERROR_SYSCALL);
3262 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3263 PY_SSL_ERROR_SSL);
3264 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3265 PY_SSL_ERROR_WANT_CONNECT);
3266 /* non ssl.h errorcodes */
3267 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3268 PY_SSL_ERROR_EOF);
3269 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3270 PY_SSL_ERROR_INVALID_ERROR_CODE);
3271 /* cert requirements */
3272 PyModule_AddIntConstant(m, "CERT_NONE",
3273 PY_SSL_CERT_NONE);
3274 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3275 PY_SSL_CERT_OPTIONAL);
3276 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3277 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00003278
Christian Heimes46bebee2013-06-09 19:03:31 +02003279#ifdef _MSC_VER
3280 /* Windows dwCertEncodingType */
3281 PyModule_AddIntMacro(m, X509_ASN_ENCODING);
3282 PyModule_AddIntMacro(m, PKCS_7_ASN_ENCODING);
3283#endif
3284
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003285 /* Alert Descriptions from ssl.h */
3286 /* note RESERVED constants no longer intended for use have been removed */
3287 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
3288
3289#define ADD_AD_CONSTANT(s) \
3290 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
3291 SSL_AD_##s)
3292
3293 ADD_AD_CONSTANT(CLOSE_NOTIFY);
3294 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
3295 ADD_AD_CONSTANT(BAD_RECORD_MAC);
3296 ADD_AD_CONSTANT(RECORD_OVERFLOW);
3297 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
3298 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
3299 ADD_AD_CONSTANT(BAD_CERTIFICATE);
3300 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
3301 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
3302 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
3303 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
3304 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
3305 ADD_AD_CONSTANT(UNKNOWN_CA);
3306 ADD_AD_CONSTANT(ACCESS_DENIED);
3307 ADD_AD_CONSTANT(DECODE_ERROR);
3308 ADD_AD_CONSTANT(DECRYPT_ERROR);
3309 ADD_AD_CONSTANT(PROTOCOL_VERSION);
3310 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
3311 ADD_AD_CONSTANT(INTERNAL_ERROR);
3312 ADD_AD_CONSTANT(USER_CANCELLED);
3313 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003314 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003315#ifdef SSL_AD_UNSUPPORTED_EXTENSION
3316 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
3317#endif
3318#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
3319 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
3320#endif
3321#ifdef SSL_AD_UNRECOGNIZED_NAME
3322 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
3323#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003324#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
3325 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
3326#endif
3327#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
3328 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
3329#endif
3330#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
3331 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
3332#endif
3333
3334#undef ADD_AD_CONSTANT
3335
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003336 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02003337#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003338 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
3339 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02003340#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003341 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
3342 PY_SSL_VERSION_SSL3);
3343 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
3344 PY_SSL_VERSION_SSL23);
3345 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
3346 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003347#if HAVE_TLSv1_2
3348 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
3349 PY_SSL_VERSION_TLS1_1);
3350 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
3351 PY_SSL_VERSION_TLS1_2);
3352#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003353
Antoine Pitroub5218772010-05-21 09:56:06 +00003354 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01003355 PyModule_AddIntConstant(m, "OP_ALL",
3356 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00003357 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
3358 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
3359 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003360#if HAVE_TLSv1_2
3361 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
3362 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
3363#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01003364 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
3365 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003366 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003367#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003368 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003369#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003370#ifdef SSL_OP_NO_COMPRESSION
3371 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
3372 SSL_OP_NO_COMPRESSION);
3373#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00003374
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003375#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00003376 r = Py_True;
3377#else
3378 r = Py_False;
3379#endif
3380 Py_INCREF(r);
3381 PyModule_AddObject(m, "HAS_SNI", r);
3382
Antoine Pitroud6494802011-07-21 01:11:30 +02003383#if HAVE_OPENSSL_FINISHED
3384 r = Py_True;
3385#else
3386 r = Py_False;
3387#endif
3388 Py_INCREF(r);
3389 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
3390
Antoine Pitrou501da612011-12-21 09:27:41 +01003391#ifdef OPENSSL_NO_ECDH
3392 r = Py_False;
3393#else
3394 r = Py_True;
3395#endif
3396 Py_INCREF(r);
3397 PyModule_AddObject(m, "HAS_ECDH", r);
3398
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003399#ifdef OPENSSL_NPN_NEGOTIATED
3400 r = Py_True;
3401#else
3402 r = Py_False;
3403#endif
3404 Py_INCREF(r);
3405 PyModule_AddObject(m, "HAS_NPN", r);
3406
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003407 /* Mappings for error codes */
3408 err_codes_to_names = PyDict_New();
3409 err_names_to_codes = PyDict_New();
3410 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
3411 return NULL;
3412 errcode = error_codes;
3413 while (errcode->mnemonic != NULL) {
3414 PyObject *mnemo, *key;
3415 mnemo = PyUnicode_FromString(errcode->mnemonic);
3416 key = Py_BuildValue("ii", errcode->library, errcode->reason);
3417 if (mnemo == NULL || key == NULL)
3418 return NULL;
3419 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
3420 return NULL;
3421 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
3422 return NULL;
3423 Py_DECREF(key);
3424 Py_DECREF(mnemo);
3425 errcode++;
3426 }
3427 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
3428 return NULL;
3429 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
3430 return NULL;
3431
3432 lib_codes_to_names = PyDict_New();
3433 if (lib_codes_to_names == NULL)
3434 return NULL;
3435 libcode = library_codes;
3436 while (libcode->library != NULL) {
3437 PyObject *mnemo, *key;
3438 key = PyLong_FromLong(libcode->code);
3439 mnemo = PyUnicode_FromString(libcode->library);
3440 if (key == NULL || mnemo == NULL)
3441 return NULL;
3442 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
3443 return NULL;
3444 Py_DECREF(key);
3445 Py_DECREF(mnemo);
3446 libcode++;
3447 }
3448 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
3449 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02003450
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003451 /* OpenSSL version */
3452 /* SSLeay() gives us the version of the library linked against,
3453 which could be different from the headers version.
3454 */
3455 libver = SSLeay();
3456 r = PyLong_FromUnsignedLong(libver);
3457 if (r == NULL)
3458 return NULL;
3459 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
3460 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003461 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003462 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3463 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
3464 return NULL;
3465 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
3466 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
3467 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003468
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003469 libver = OPENSSL_VERSION_NUMBER;
3470 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
3471 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3472 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
3473 return NULL;
3474
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003475 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003476}