blob: c64d209ec87b879cd6fc4e764395bd46138da19c [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
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001026
1027static PyObject *
1028PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1029
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001030 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001031 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001032 X509 *x=NULL;
1033 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001034
Antoine Pitroufb046912010-11-09 20:21:19 +00001035 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1036 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001037 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001038
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001039 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1040 PyErr_SetString(PySSLErrorObject,
1041 "Can't malloc memory to read file");
1042 goto fail0;
1043 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001044
Victor Stinner3800e1e2010-05-16 21:23:48 +00001045 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001046 PyErr_SetString(PySSLErrorObject,
1047 "Can't open file");
1048 goto fail0;
1049 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001050
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001051 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1052 if (x == NULL) {
1053 PyErr_SetString(PySSLErrorObject,
1054 "Error decoding PEM-encoded file");
1055 goto fail0;
1056 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001057
Antoine Pitroufb046912010-11-09 20:21:19 +00001058 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001059 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001060
1061 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001062 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001063 if (cert != NULL) BIO_free(cert);
1064 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001065}
1066
1067
1068static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001069PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001070{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001071 PyObject *retval = NULL;
1072 int len;
1073 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001074 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001075
Antoine Pitrou721738f2012-08-15 23:20:39 +02001076 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001077 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001078
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001079 if (!self->peer_cert)
1080 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001081
Antoine Pitrou721738f2012-08-15 23:20:39 +02001082 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001083 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001084
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001085 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001086
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001087 bytes_buf = NULL;
1088 len = i2d_X509(self->peer_cert, &bytes_buf);
1089 if (len < 0) {
1090 PySSL_SetError(self, len, __FILE__, __LINE__);
1091 return NULL;
1092 }
1093 /* this is actually an immutable bytes sequence */
1094 retval = PyBytes_FromStringAndSize
1095 ((const char *) bytes_buf, len);
1096 OPENSSL_free(bytes_buf);
1097 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001098
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001100 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 if ((verification & SSL_VERIFY_PEER) == 0)
1102 return PyDict_New();
1103 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001104 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001106}
1107
1108PyDoc_STRVAR(PySSL_peercert_doc,
1109"peer_certificate([der=False]) -> certificate\n\
1110\n\
1111Returns the certificate for the peer. If no certificate was provided,\n\
1112returns None. If a certificate was provided, but not validated, returns\n\
1113an empty dictionary. Otherwise returns a dict containing information\n\
1114about the peer certificate.\n\
1115\n\
1116If the optional argument is True, returns a DER-encoded copy of the\n\
1117peer certificate, or None if no certificate was provided. This will\n\
1118return the certificate even if it wasn't validated.");
1119
Antoine Pitrou152efa22010-05-16 18:19:27 +00001120static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001121
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001122 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001123 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001124 char *cipher_name;
1125 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001126
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001128 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 current = SSL_get_current_cipher(self->ssl);
1130 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001131 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001132
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001133 retval = PyTuple_New(3);
1134 if (retval == NULL)
1135 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 cipher_name = (char *) SSL_CIPHER_get_name(current);
1138 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001139 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 PyTuple_SET_ITEM(retval, 0, Py_None);
1141 } else {
1142 v = PyUnicode_FromString(cipher_name);
1143 if (v == NULL)
1144 goto fail0;
1145 PyTuple_SET_ITEM(retval, 0, v);
1146 }
1147 cipher_protocol = SSL_CIPHER_get_version(current);
1148 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001149 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 PyTuple_SET_ITEM(retval, 1, Py_None);
1151 } else {
1152 v = PyUnicode_FromString(cipher_protocol);
1153 if (v == NULL)
1154 goto fail0;
1155 PyTuple_SET_ITEM(retval, 1, v);
1156 }
1157 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1158 if (v == NULL)
1159 goto fail0;
1160 PyTuple_SET_ITEM(retval, 2, v);
1161 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001162
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001163 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 Py_DECREF(retval);
1165 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001166}
1167
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001168#ifdef OPENSSL_NPN_NEGOTIATED
1169static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1170 const unsigned char *out;
1171 unsigned int outlen;
1172
1173 SSL_get0_next_proto_negotiated(self->ssl,
1174 &out, &outlen);
1175
1176 if (out == NULL)
1177 Py_RETURN_NONE;
1178 return PyUnicode_FromStringAndSize((char *) out, outlen);
1179}
1180#endif
1181
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001182static PyObject *PySSL_compression(PySSLSocket *self) {
1183#ifdef OPENSSL_NO_COMP
1184 Py_RETURN_NONE;
1185#else
1186 const COMP_METHOD *comp_method;
1187 const char *short_name;
1188
1189 if (self->ssl == NULL)
1190 Py_RETURN_NONE;
1191 comp_method = SSL_get_current_compression(self->ssl);
1192 if (comp_method == NULL || comp_method->type == NID_undef)
1193 Py_RETURN_NONE;
1194 short_name = OBJ_nid2sn(comp_method->type);
1195 if (short_name == NULL)
1196 Py_RETURN_NONE;
1197 return PyUnicode_DecodeFSDefault(short_name);
1198#endif
1199}
1200
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001201static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1202 Py_INCREF(self->ctx);
1203 return self->ctx;
1204}
1205
1206static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1207 void *closure) {
1208
1209 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001210#if !HAVE_SNI
1211 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1212 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001213 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001214#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001215 Py_INCREF(value);
1216 Py_DECREF(self->ctx);
1217 self->ctx = (PySSLContext *) value;
1218 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001219#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001220 } else {
1221 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1222 return -1;
1223 }
1224
1225 return 0;
1226}
1227
1228PyDoc_STRVAR(PySSL_set_context_doc,
1229"_setter_context(ctx)\n\
1230\
1231This changes the context associated with the SSLSocket. This is typically\n\
1232used from within a callback function set by the set_servername_callback\n\
1233on the SSLContext to change the certificate information associated with the\n\
1234SSLSocket before the cryptographic exchange handshake messages\n");
1235
1236
1237
Antoine Pitrou152efa22010-05-16 18:19:27 +00001238static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001239{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001240 if (self->peer_cert) /* Possible not to have one? */
1241 X509_free (self->peer_cert);
1242 if (self->ssl)
1243 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001244 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001245 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001246 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001247}
1248
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001249/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001250 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001251 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001252 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001253
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001254static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001255check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001256{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001257 fd_set fds;
1258 struct timeval tv;
1259 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001260
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001261 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1262 if (s->sock_timeout < 0.0)
1263 return SOCKET_IS_BLOCKING;
1264 else if (s->sock_timeout == 0.0)
1265 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001266
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001267 /* Guard against closed socket */
1268 if (s->sock_fd < 0)
1269 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001270
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001271 /* Prefer poll, if available, since you can poll() any fd
1272 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001273#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001274 {
1275 struct pollfd pollfd;
1276 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 pollfd.fd = s->sock_fd;
1279 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001280
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 /* s->sock_timeout is in seconds, timeout in ms */
1282 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1283 PySSL_BEGIN_ALLOW_THREADS
1284 rc = poll(&pollfd, 1, timeout);
1285 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001286
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 goto normal_return;
1288 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001289#endif
1290
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001291 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001292 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001293 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001294
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 /* Construct the arguments to select */
1296 tv.tv_sec = (int)s->sock_timeout;
1297 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1298 FD_ZERO(&fds);
1299 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001300
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001301 /* See if the socket is ready */
1302 PySSL_BEGIN_ALLOW_THREADS
1303 if (writing)
1304 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1305 else
1306 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1307 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001308
Bill Janssen6e027db2007-11-15 22:23:56 +00001309#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001310normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001311#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001312 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1313 (when we are able to write or when there's something to read) */
1314 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001315}
1316
Antoine Pitrou152efa22010-05-16 18:19:27 +00001317static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001318{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001319 Py_buffer buf;
1320 int len;
1321 int sockstate;
1322 int err;
1323 int nonblocking;
1324 PySocketSockObject *sock
1325 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001326
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001327 if (((PyObject*)sock) == Py_None) {
1328 _setSSLError("Underlying socket connection gone",
1329 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1330 return NULL;
1331 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001332 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001333
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001334 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1335 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001336 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001337 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338
1339 /* just in case the blocking state of the socket has been changed */
1340 nonblocking = (sock->sock_timeout >= 0.0);
1341 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1342 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1343
1344 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1345 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001346 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001347 "The write operation timed out");
1348 goto error;
1349 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1350 PyErr_SetString(PySSLErrorObject,
1351 "Underlying socket has been closed.");
1352 goto error;
1353 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1354 PyErr_SetString(PySSLErrorObject,
1355 "Underlying socket too large for select().");
1356 goto error;
1357 }
1358 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 PySSL_BEGIN_ALLOW_THREADS
1360 len = SSL_write(self->ssl, buf.buf, buf.len);
1361 err = SSL_get_error(self->ssl, len);
1362 PySSL_END_ALLOW_THREADS
1363 if (PyErr_CheckSignals()) {
1364 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001365 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001367 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001369 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 } else {
1371 sockstate = SOCKET_OPERATION_OK;
1372 }
1373 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001374 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001375 "The write operation timed out");
1376 goto error;
1377 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1378 PyErr_SetString(PySSLErrorObject,
1379 "Underlying socket has been closed.");
1380 goto error;
1381 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1382 break;
1383 }
1384 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001385
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001386 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001387 PyBuffer_Release(&buf);
1388 if (len > 0)
1389 return PyLong_FromLong(len);
1390 else
1391 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001392
1393error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001394 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001395 PyBuffer_Release(&buf);
1396 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001397}
1398
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001399PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001400"write(s) -> len\n\
1401\n\
1402Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001403of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001404
Antoine Pitrou152efa22010-05-16 18:19:27 +00001405static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001406{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001407 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001408
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001409 PySSL_BEGIN_ALLOW_THREADS
1410 count = SSL_pending(self->ssl);
1411 PySSL_END_ALLOW_THREADS
1412 if (count < 0)
1413 return PySSL_SetError(self, count, __FILE__, __LINE__);
1414 else
1415 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001416}
1417
1418PyDoc_STRVAR(PySSL_SSLpending_doc,
1419"pending() -> count\n\
1420\n\
1421Returns the number of already decrypted bytes available for read,\n\
1422pending on the connection.\n");
1423
Antoine Pitrou152efa22010-05-16 18:19:27 +00001424static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001425{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001426 PyObject *dest = NULL;
1427 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001428 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001429 int len, count;
1430 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001431 int sockstate;
1432 int err;
1433 int nonblocking;
1434 PySocketSockObject *sock
1435 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001436
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001437 if (((PyObject*)sock) == Py_None) {
1438 _setSSLError("Underlying socket connection gone",
1439 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1440 return NULL;
1441 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001442 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001443
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001444 buf.obj = NULL;
1445 buf.buf = NULL;
1446 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001447 goto error;
1448
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001449 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1450 dest = PyBytes_FromStringAndSize(NULL, len);
1451 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001452 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001453 mem = PyBytes_AS_STRING(dest);
1454 }
1455 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001456 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001457 mem = buf.buf;
1458 if (len <= 0 || len > buf.len) {
1459 len = (int) buf.len;
1460 if (buf.len != len) {
1461 PyErr_SetString(PyExc_OverflowError,
1462 "maximum length can't fit in a C 'int'");
1463 goto error;
1464 }
1465 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001466 }
1467
1468 /* just in case the blocking state of the socket has been changed */
1469 nonblocking = (sock->sock_timeout >= 0.0);
1470 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1471 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1472
1473 /* first check if there are bytes ready to be read */
1474 PySSL_BEGIN_ALLOW_THREADS
1475 count = SSL_pending(self->ssl);
1476 PySSL_END_ALLOW_THREADS
1477
1478 if (!count) {
1479 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1480 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001481 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001482 "The read operation timed out");
1483 goto error;
1484 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1485 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001486 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001487 goto error;
1488 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1489 count = 0;
1490 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001491 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001492 }
1493 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001494 PySSL_BEGIN_ALLOW_THREADS
1495 count = SSL_read(self->ssl, mem, len);
1496 err = SSL_get_error(self->ssl, count);
1497 PySSL_END_ALLOW_THREADS
1498 if (PyErr_CheckSignals())
1499 goto error;
1500 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001501 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001502 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001503 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001504 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1505 (SSL_get_shutdown(self->ssl) ==
1506 SSL_RECEIVED_SHUTDOWN))
1507 {
1508 count = 0;
1509 goto done;
1510 } else {
1511 sockstate = SOCKET_OPERATION_OK;
1512 }
1513 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001514 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001515 "The read operation timed out");
1516 goto error;
1517 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1518 break;
1519 }
1520 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1521 if (count <= 0) {
1522 PySSL_SetError(self, count, __FILE__, __LINE__);
1523 goto error;
1524 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001525
1526done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001527 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001529 _PyBytes_Resize(&dest, count);
1530 return dest;
1531 }
1532 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001533 PyBuffer_Release(&buf);
1534 return PyLong_FromLong(count);
1535 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001536
1537error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001538 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001539 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001540 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001541 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001542 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001543 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001544}
1545
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001546PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001547"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001548\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001549Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001550
Antoine Pitrou152efa22010-05-16 18:19:27 +00001551static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001552{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001553 int err, ssl_err, sockstate, nonblocking;
1554 int zeros = 0;
1555 PySocketSockObject *sock
1556 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001557
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558 /* Guard against closed socket */
1559 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1560 _setSSLError("Underlying socket connection gone",
1561 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1562 return NULL;
1563 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001564 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001565
1566 /* Just in case the blocking state of the socket has been changed */
1567 nonblocking = (sock->sock_timeout >= 0.0);
1568 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1569 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1570
1571 while (1) {
1572 PySSL_BEGIN_ALLOW_THREADS
1573 /* Disable read-ahead so that unwrap can work correctly.
1574 * Otherwise OpenSSL might read in too much data,
1575 * eating clear text data that happens to be
1576 * transmitted after the SSL shutdown.
1577 * Should be safe to call repeatedly everytime this
1578 * function is used and the shutdown_seen_zero != 0
1579 * condition is met.
1580 */
1581 if (self->shutdown_seen_zero)
1582 SSL_set_read_ahead(self->ssl, 0);
1583 err = SSL_shutdown(self->ssl);
1584 PySSL_END_ALLOW_THREADS
1585 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1586 if (err > 0)
1587 break;
1588 if (err == 0) {
1589 /* Don't loop endlessly; instead preserve legacy
1590 behaviour of trying SSL_shutdown() only twice.
1591 This looks necessary for OpenSSL < 0.9.8m */
1592 if (++zeros > 1)
1593 break;
1594 /* Shutdown was sent, now try receiving */
1595 self->shutdown_seen_zero = 1;
1596 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001597 }
1598
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001599 /* Possibly retry shutdown until timeout or failure */
1600 ssl_err = SSL_get_error(self->ssl, err);
1601 if (ssl_err == SSL_ERROR_WANT_READ)
1602 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1603 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1604 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1605 else
1606 break;
1607 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1608 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001609 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001610 "The read operation timed out");
1611 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001612 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001613 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001614 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001615 }
1616 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1617 PyErr_SetString(PySSLErrorObject,
1618 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001619 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001620 }
1621 else if (sockstate != SOCKET_OPERATION_OK)
1622 /* Retain the SSL error code */
1623 break;
1624 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001625
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001626 if (err < 0) {
1627 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001628 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001629 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001630 else
1631 /* It's already INCREF'ed */
1632 return (PyObject *) sock;
1633
1634error:
1635 Py_DECREF(sock);
1636 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001637}
1638
1639PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1640"shutdown(s) -> socket\n\
1641\n\
1642Does the SSL shutdown handshake with the remote end, and returns\n\
1643the underlying socket object.");
1644
Antoine Pitroud6494802011-07-21 01:11:30 +02001645#if HAVE_OPENSSL_FINISHED
1646static PyObject *
1647PySSL_tls_unique_cb(PySSLSocket *self)
1648{
1649 PyObject *retval = NULL;
1650 char buf[PySSL_CB_MAXLEN];
1651 int len;
1652
1653 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1654 /* if session is resumed XOR we are the client */
1655 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1656 }
1657 else {
1658 /* if a new session XOR we are the server */
1659 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1660 }
1661
1662 /* It cannot be negative in current OpenSSL version as of July 2011 */
1663 assert(len >= 0);
1664 if (len == 0)
1665 Py_RETURN_NONE;
1666
1667 retval = PyBytes_FromStringAndSize(buf, len);
1668
1669 return retval;
1670}
1671
1672PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1673"tls_unique_cb() -> bytes\n\
1674\n\
1675Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1676\n\
1677If the TLS handshake is not yet complete, None is returned");
1678
1679#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001680
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001681static PyGetSetDef ssl_getsetlist[] = {
1682 {"context", (getter) PySSL_get_context,
1683 (setter) PySSL_set_context, PySSL_set_context_doc},
1684 {NULL}, /* sentinel */
1685};
1686
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001687static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001688 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1689 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1690 PySSL_SSLwrite_doc},
1691 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1692 PySSL_SSLread_doc},
1693 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1694 PySSL_SSLpending_doc},
1695 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1696 PySSL_peercert_doc},
1697 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001698#ifdef OPENSSL_NPN_NEGOTIATED
1699 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1700#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001701 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001702 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1703 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001704#if HAVE_OPENSSL_FINISHED
1705 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1706 PySSL_tls_unique_cb_doc},
1707#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001708 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001709};
1710
Antoine Pitrou152efa22010-05-16 18:19:27 +00001711static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001712 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001713 "_ssl._SSLSocket", /*tp_name*/
1714 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001715 0, /*tp_itemsize*/
1716 /* methods */
1717 (destructor)PySSL_dealloc, /*tp_dealloc*/
1718 0, /*tp_print*/
1719 0, /*tp_getattr*/
1720 0, /*tp_setattr*/
1721 0, /*tp_reserved*/
1722 0, /*tp_repr*/
1723 0, /*tp_as_number*/
1724 0, /*tp_as_sequence*/
1725 0, /*tp_as_mapping*/
1726 0, /*tp_hash*/
1727 0, /*tp_call*/
1728 0, /*tp_str*/
1729 0, /*tp_getattro*/
1730 0, /*tp_setattro*/
1731 0, /*tp_as_buffer*/
1732 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1733 0, /*tp_doc*/
1734 0, /*tp_traverse*/
1735 0, /*tp_clear*/
1736 0, /*tp_richcompare*/
1737 0, /*tp_weaklistoffset*/
1738 0, /*tp_iter*/
1739 0, /*tp_iternext*/
1740 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001741 0, /*tp_members*/
1742 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001743};
1744
Antoine Pitrou152efa22010-05-16 18:19:27 +00001745
1746/*
1747 * _SSLContext objects
1748 */
1749
1750static PyObject *
1751context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1752{
1753 char *kwlist[] = {"protocol", NULL};
1754 PySSLContext *self;
1755 int proto_version = PY_SSL_VERSION_SSL23;
1756 SSL_CTX *ctx = NULL;
1757
1758 if (!PyArg_ParseTupleAndKeywords(
1759 args, kwds, "i:_SSLContext", kwlist,
1760 &proto_version))
1761 return NULL;
1762
1763 PySSL_BEGIN_ALLOW_THREADS
1764 if (proto_version == PY_SSL_VERSION_TLS1)
1765 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01001766#if HAVE_TLSv1_2
1767 else if (proto_version == PY_SSL_VERSION_TLS1_1)
1768 ctx = SSL_CTX_new(TLSv1_1_method());
1769 else if (proto_version == PY_SSL_VERSION_TLS1_2)
1770 ctx = SSL_CTX_new(TLSv1_2_method());
1771#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001772 else if (proto_version == PY_SSL_VERSION_SSL3)
1773 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001774#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001775 else if (proto_version == PY_SSL_VERSION_SSL2)
1776 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001777#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001778 else if (proto_version == PY_SSL_VERSION_SSL23)
1779 ctx = SSL_CTX_new(SSLv23_method());
1780 else
1781 proto_version = -1;
1782 PySSL_END_ALLOW_THREADS
1783
1784 if (proto_version == -1) {
1785 PyErr_SetString(PyExc_ValueError,
1786 "invalid protocol version");
1787 return NULL;
1788 }
1789 if (ctx == NULL) {
1790 PyErr_SetString(PySSLErrorObject,
1791 "failed to allocate SSL context");
1792 return NULL;
1793 }
1794
1795 assert(type != NULL && type->tp_alloc != NULL);
1796 self = (PySSLContext *) type->tp_alloc(type, 0);
1797 if (self == NULL) {
1798 SSL_CTX_free(ctx);
1799 return NULL;
1800 }
1801 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001802#ifdef OPENSSL_NPN_NEGOTIATED
1803 self->npn_protocols = NULL;
1804#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001805#ifndef OPENSSL_NO_TLSEXT
1806 self->set_hostname = NULL;
1807#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001808 /* Defaults */
1809 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001810 SSL_CTX_set_options(self->ctx,
1811 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001812
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001813#define SID_CTX "Python"
1814 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1815 sizeof(SID_CTX));
1816#undef SID_CTX
1817
Antoine Pitrou152efa22010-05-16 18:19:27 +00001818 return (PyObject *)self;
1819}
1820
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001821static int
1822context_traverse(PySSLContext *self, visitproc visit, void *arg)
1823{
1824#ifndef OPENSSL_NO_TLSEXT
1825 Py_VISIT(self->set_hostname);
1826#endif
1827 return 0;
1828}
1829
1830static int
1831context_clear(PySSLContext *self)
1832{
1833#ifndef OPENSSL_NO_TLSEXT
1834 Py_CLEAR(self->set_hostname);
1835#endif
1836 return 0;
1837}
1838
Antoine Pitrou152efa22010-05-16 18:19:27 +00001839static void
1840context_dealloc(PySSLContext *self)
1841{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001842 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001843 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001844#ifdef OPENSSL_NPN_NEGOTIATED
1845 PyMem_Free(self->npn_protocols);
1846#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001847 Py_TYPE(self)->tp_free(self);
1848}
1849
1850static PyObject *
1851set_ciphers(PySSLContext *self, PyObject *args)
1852{
1853 int ret;
1854 const char *cipherlist;
1855
1856 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1857 return NULL;
1858 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1859 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001860 /* Clearing the error queue is necessary on some OpenSSL versions,
1861 otherwise the error will be reported again when another SSL call
1862 is done. */
1863 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001864 PyErr_SetString(PySSLErrorObject,
1865 "No cipher can be selected.");
1866 return NULL;
1867 }
1868 Py_RETURN_NONE;
1869}
1870
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001871#ifdef OPENSSL_NPN_NEGOTIATED
1872/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1873static int
1874_advertiseNPN_cb(SSL *s,
1875 const unsigned char **data, unsigned int *len,
1876 void *args)
1877{
1878 PySSLContext *ssl_ctx = (PySSLContext *) args;
1879
1880 if (ssl_ctx->npn_protocols == NULL) {
1881 *data = (unsigned char *) "";
1882 *len = 0;
1883 } else {
1884 *data = (unsigned char *) ssl_ctx->npn_protocols;
1885 *len = ssl_ctx->npn_protocols_len;
1886 }
1887
1888 return SSL_TLSEXT_ERR_OK;
1889}
1890/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1891static int
1892_selectNPN_cb(SSL *s,
1893 unsigned char **out, unsigned char *outlen,
1894 const unsigned char *server, unsigned int server_len,
1895 void *args)
1896{
1897 PySSLContext *ssl_ctx = (PySSLContext *) args;
1898
1899 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1900 int client_len;
1901
1902 if (client == NULL) {
1903 client = (unsigned char *) "";
1904 client_len = 0;
1905 } else {
1906 client_len = ssl_ctx->npn_protocols_len;
1907 }
1908
1909 SSL_select_next_proto(out, outlen,
1910 server, server_len,
1911 client, client_len);
1912
1913 return SSL_TLSEXT_ERR_OK;
1914}
1915#endif
1916
1917static PyObject *
1918_set_npn_protocols(PySSLContext *self, PyObject *args)
1919{
1920#ifdef OPENSSL_NPN_NEGOTIATED
1921 Py_buffer protos;
1922
1923 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1924 return NULL;
1925
Christian Heimes5cb31c92012-09-20 12:42:54 +02001926 if (self->npn_protocols != NULL) {
1927 PyMem_Free(self->npn_protocols);
1928 }
1929
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001930 self->npn_protocols = PyMem_Malloc(protos.len);
1931 if (self->npn_protocols == NULL) {
1932 PyBuffer_Release(&protos);
1933 return PyErr_NoMemory();
1934 }
1935 memcpy(self->npn_protocols, protos.buf, protos.len);
1936 self->npn_protocols_len = (int) protos.len;
1937
1938 /* set both server and client callbacks, because the context can
1939 * be used to create both types of sockets */
1940 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
1941 _advertiseNPN_cb,
1942 self);
1943 SSL_CTX_set_next_proto_select_cb(self->ctx,
1944 _selectNPN_cb,
1945 self);
1946
1947 PyBuffer_Release(&protos);
1948 Py_RETURN_NONE;
1949#else
1950 PyErr_SetString(PyExc_NotImplementedError,
1951 "The NPN extension requires OpenSSL 1.0.1 or later.");
1952 return NULL;
1953#endif
1954}
1955
Antoine Pitrou152efa22010-05-16 18:19:27 +00001956static PyObject *
1957get_verify_mode(PySSLContext *self, void *c)
1958{
1959 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1960 case SSL_VERIFY_NONE:
1961 return PyLong_FromLong(PY_SSL_CERT_NONE);
1962 case SSL_VERIFY_PEER:
1963 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1964 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1965 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1966 }
1967 PyErr_SetString(PySSLErrorObject,
1968 "invalid return value from SSL_CTX_get_verify_mode");
1969 return NULL;
1970}
1971
1972static int
1973set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1974{
1975 int n, mode;
1976 if (!PyArg_Parse(arg, "i", &n))
1977 return -1;
1978 if (n == PY_SSL_CERT_NONE)
1979 mode = SSL_VERIFY_NONE;
1980 else if (n == PY_SSL_CERT_OPTIONAL)
1981 mode = SSL_VERIFY_PEER;
1982 else if (n == PY_SSL_CERT_REQUIRED)
1983 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1984 else {
1985 PyErr_SetString(PyExc_ValueError,
1986 "invalid value for verify_mode");
1987 return -1;
1988 }
1989 SSL_CTX_set_verify(self->ctx, mode, NULL);
1990 return 0;
1991}
1992
1993static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001994get_options(PySSLContext *self, void *c)
1995{
1996 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1997}
1998
1999static int
2000set_options(PySSLContext *self, PyObject *arg, void *c)
2001{
2002 long new_opts, opts, set, clear;
2003 if (!PyArg_Parse(arg, "l", &new_opts))
2004 return -1;
2005 opts = SSL_CTX_get_options(self->ctx);
2006 clear = opts & ~new_opts;
2007 set = ~opts & new_opts;
2008 if (clear) {
2009#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2010 SSL_CTX_clear_options(self->ctx, clear);
2011#else
2012 PyErr_SetString(PyExc_ValueError,
2013 "can't clear options before OpenSSL 0.9.8m");
2014 return -1;
2015#endif
2016 }
2017 if (set)
2018 SSL_CTX_set_options(self->ctx, set);
2019 return 0;
2020}
2021
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002022typedef struct {
2023 PyThreadState *thread_state;
2024 PyObject *callable;
2025 char *password;
2026 Py_ssize_t size;
2027 int error;
2028} _PySSLPasswordInfo;
2029
2030static int
2031_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2032 const char *bad_type_error)
2033{
2034 /* Set the password and size fields of a _PySSLPasswordInfo struct
2035 from a unicode, bytes, or byte array object.
2036 The password field will be dynamically allocated and must be freed
2037 by the caller */
2038 PyObject *password_bytes = NULL;
2039 const char *data = NULL;
2040 Py_ssize_t size;
2041
2042 if (PyUnicode_Check(password)) {
2043 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2044 if (!password_bytes) {
2045 goto error;
2046 }
2047 data = PyBytes_AS_STRING(password_bytes);
2048 size = PyBytes_GET_SIZE(password_bytes);
2049 } else if (PyBytes_Check(password)) {
2050 data = PyBytes_AS_STRING(password);
2051 size = PyBytes_GET_SIZE(password);
2052 } else if (PyByteArray_Check(password)) {
2053 data = PyByteArray_AS_STRING(password);
2054 size = PyByteArray_GET_SIZE(password);
2055 } else {
2056 PyErr_SetString(PyExc_TypeError, bad_type_error);
2057 goto error;
2058 }
2059
2060 free(pw_info->password);
2061 pw_info->password = malloc(size);
2062 if (!pw_info->password) {
2063 PyErr_SetString(PyExc_MemoryError,
2064 "unable to allocate password buffer");
2065 goto error;
2066 }
2067 memcpy(pw_info->password, data, size);
2068 pw_info->size = size;
2069
2070 Py_XDECREF(password_bytes);
2071 return 1;
2072
2073error:
2074 Py_XDECREF(password_bytes);
2075 return 0;
2076}
2077
2078static int
2079_password_callback(char *buf, int size, int rwflag, void *userdata)
2080{
2081 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2082 PyObject *fn_ret = NULL;
2083
2084 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2085
2086 if (pw_info->callable) {
2087 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2088 if (!fn_ret) {
2089 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2090 core python API, so we could use it to add a frame here */
2091 goto error;
2092 }
2093
2094 if (!_pwinfo_set(pw_info, fn_ret,
2095 "password callback must return a string")) {
2096 goto error;
2097 }
2098 Py_CLEAR(fn_ret);
2099 }
2100
2101 if (pw_info->size > size) {
2102 PyErr_Format(PyExc_ValueError,
2103 "password cannot be longer than %d bytes", size);
2104 goto error;
2105 }
2106
2107 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2108 memcpy(buf, pw_info->password, pw_info->size);
2109 return pw_info->size;
2110
2111error:
2112 Py_XDECREF(fn_ret);
2113 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2114 pw_info->error = 1;
2115 return -1;
2116}
2117
Antoine Pitroub5218772010-05-21 09:56:06 +00002118static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002119load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2120{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002121 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2122 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002123 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002124 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2125 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2126 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002127 int r;
2128
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002129 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002130 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002131 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002132 "O|OO:load_cert_chain", kwlist,
2133 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002134 return NULL;
2135 if (keyfile == Py_None)
2136 keyfile = NULL;
2137 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2138 PyErr_SetString(PyExc_TypeError,
2139 "certfile should be a valid filesystem path");
2140 return NULL;
2141 }
2142 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2143 PyErr_SetString(PyExc_TypeError,
2144 "keyfile should be a valid filesystem path");
2145 goto error;
2146 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002147 if (password && password != Py_None) {
2148 if (PyCallable_Check(password)) {
2149 pw_info.callable = password;
2150 } else if (!_pwinfo_set(&pw_info, password,
2151 "password should be a string or callable")) {
2152 goto error;
2153 }
2154 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2155 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2156 }
2157 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002158 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2159 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002160 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002161 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002162 if (pw_info.error) {
2163 ERR_clear_error();
2164 /* the password callback has already set the error information */
2165 }
2166 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002167 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002168 PyErr_SetFromErrno(PyExc_IOError);
2169 }
2170 else {
2171 _setSSLError(NULL, 0, __FILE__, __LINE__);
2172 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002173 goto error;
2174 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002175 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002176 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002177 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2178 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002179 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2180 Py_CLEAR(keyfile_bytes);
2181 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002182 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002183 if (pw_info.error) {
2184 ERR_clear_error();
2185 /* the password callback has already set the error information */
2186 }
2187 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002188 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002189 PyErr_SetFromErrno(PyExc_IOError);
2190 }
2191 else {
2192 _setSSLError(NULL, 0, __FILE__, __LINE__);
2193 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002194 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002195 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002196 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002197 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002198 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002199 if (r != 1) {
2200 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002201 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002202 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002203 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2204 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2205 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002206 Py_RETURN_NONE;
2207
2208error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002209 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2210 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2211 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002212 Py_XDECREF(keyfile_bytes);
2213 Py_XDECREF(certfile_bytes);
2214 return NULL;
2215}
2216
2217static PyObject *
2218load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2219{
2220 char *kwlist[] = {"cafile", "capath", NULL};
2221 PyObject *cafile = NULL, *capath = NULL;
2222 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2223 const char *cafile_buf = NULL, *capath_buf = NULL;
2224 int r;
2225
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002226 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002227 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2228 "|OO:load_verify_locations", kwlist,
2229 &cafile, &capath))
2230 return NULL;
2231 if (cafile == Py_None)
2232 cafile = NULL;
2233 if (capath == Py_None)
2234 capath = NULL;
2235 if (cafile == NULL && capath == NULL) {
2236 PyErr_SetString(PyExc_TypeError,
2237 "cafile and capath cannot be both omitted");
2238 return NULL;
2239 }
2240 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2241 PyErr_SetString(PyExc_TypeError,
2242 "cafile should be a valid filesystem path");
2243 return NULL;
2244 }
2245 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002246 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002247 PyErr_SetString(PyExc_TypeError,
2248 "capath should be a valid filesystem path");
2249 return NULL;
2250 }
2251 if (cafile)
2252 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2253 if (capath)
2254 capath_buf = PyBytes_AS_STRING(capath_bytes);
2255 PySSL_BEGIN_ALLOW_THREADS
2256 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2257 PySSL_END_ALLOW_THREADS
2258 Py_XDECREF(cafile_bytes);
2259 Py_XDECREF(capath_bytes);
2260 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002261 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002262 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002263 PyErr_SetFromErrno(PyExc_IOError);
2264 }
2265 else {
2266 _setSSLError(NULL, 0, __FILE__, __LINE__);
2267 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002268 return NULL;
2269 }
2270 Py_RETURN_NONE;
2271}
2272
2273static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002274load_dh_params(PySSLContext *self, PyObject *filepath)
2275{
2276 FILE *f;
2277 DH *dh;
2278
2279 f = _Py_fopen(filepath, "rb");
2280 if (f == NULL) {
2281 if (!PyErr_Occurred())
2282 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2283 return NULL;
2284 }
2285 errno = 0;
2286 PySSL_BEGIN_ALLOW_THREADS
2287 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002288 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002289 PySSL_END_ALLOW_THREADS
2290 if (dh == NULL) {
2291 if (errno != 0) {
2292 ERR_clear_error();
2293 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2294 }
2295 else {
2296 _setSSLError(NULL, 0, __FILE__, __LINE__);
2297 }
2298 return NULL;
2299 }
2300 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2301 _setSSLError(NULL, 0, __FILE__, __LINE__);
2302 DH_free(dh);
2303 Py_RETURN_NONE;
2304}
2305
2306static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002307context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2308{
Antoine Pitroud5323212010-10-22 18:19:07 +00002309 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002310 PySocketSockObject *sock;
2311 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002312 char *hostname = NULL;
2313 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002314
Antoine Pitroud5323212010-10-22 18:19:07 +00002315 /* server_hostname is either None (or absent), or to be encoded
2316 using the idna encoding. */
2317 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002318 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002319 &sock, &server_side,
2320 Py_TYPE(Py_None), &hostname_obj)) {
2321 PyErr_Clear();
2322 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2323 PySocketModule.Sock_Type,
2324 &sock, &server_side,
2325 "idna", &hostname))
2326 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002327#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002328 PyMem_Free(hostname);
2329 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2330 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002331 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002332#endif
2333 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002334
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002335 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002336 hostname);
2337 if (hostname != NULL)
2338 PyMem_Free(hostname);
2339 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002340}
2341
Antoine Pitroub0182c82010-10-12 20:09:02 +00002342static PyObject *
2343session_stats(PySSLContext *self, PyObject *unused)
2344{
2345 int r;
2346 PyObject *value, *stats = PyDict_New();
2347 if (!stats)
2348 return NULL;
2349
2350#define ADD_STATS(SSL_NAME, KEY_NAME) \
2351 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2352 if (value == NULL) \
2353 goto error; \
2354 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2355 Py_DECREF(value); \
2356 if (r < 0) \
2357 goto error;
2358
2359 ADD_STATS(number, "number");
2360 ADD_STATS(connect, "connect");
2361 ADD_STATS(connect_good, "connect_good");
2362 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2363 ADD_STATS(accept, "accept");
2364 ADD_STATS(accept_good, "accept_good");
2365 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2366 ADD_STATS(accept, "accept");
2367 ADD_STATS(hits, "hits");
2368 ADD_STATS(misses, "misses");
2369 ADD_STATS(timeouts, "timeouts");
2370 ADD_STATS(cache_full, "cache_full");
2371
2372#undef ADD_STATS
2373
2374 return stats;
2375
2376error:
2377 Py_DECREF(stats);
2378 return NULL;
2379}
2380
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002381static PyObject *
2382set_default_verify_paths(PySSLContext *self, PyObject *unused)
2383{
2384 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2385 _setSSLError(NULL, 0, __FILE__, __LINE__);
2386 return NULL;
2387 }
2388 Py_RETURN_NONE;
2389}
2390
Antoine Pitrou501da612011-12-21 09:27:41 +01002391#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002392static PyObject *
2393set_ecdh_curve(PySSLContext *self, PyObject *name)
2394{
2395 PyObject *name_bytes;
2396 int nid;
2397 EC_KEY *key;
2398
2399 if (!PyUnicode_FSConverter(name, &name_bytes))
2400 return NULL;
2401 assert(PyBytes_Check(name_bytes));
2402 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2403 Py_DECREF(name_bytes);
2404 if (nid == 0) {
2405 PyErr_Format(PyExc_ValueError,
2406 "unknown elliptic curve name %R", name);
2407 return NULL;
2408 }
2409 key = EC_KEY_new_by_curve_name(nid);
2410 if (key == NULL) {
2411 _setSSLError(NULL, 0, __FILE__, __LINE__);
2412 return NULL;
2413 }
2414 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2415 EC_KEY_free(key);
2416 Py_RETURN_NONE;
2417}
Antoine Pitrou501da612011-12-21 09:27:41 +01002418#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002419
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002420#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002421static int
2422_servername_callback(SSL *s, int *al, void *args)
2423{
2424 int ret;
2425 PySSLContext *ssl_ctx = (PySSLContext *) args;
2426 PySSLSocket *ssl;
2427 PyObject *servername_o;
2428 PyObject *servername_idna;
2429 PyObject *result;
2430 /* The high-level ssl.SSLSocket object */
2431 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002432 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002433#ifdef WITH_THREAD
2434 PyGILState_STATE gstate = PyGILState_Ensure();
2435#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002436
2437 if (ssl_ctx->set_hostname == NULL) {
2438 /* remove race condition in this the call back while if removing the
2439 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002440#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002441 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002442#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002443 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002444 }
2445
2446 ssl = SSL_get_app_data(s);
2447 assert(PySSLSocket_Check(ssl));
2448 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2449 Py_INCREF(ssl_socket);
2450 if (ssl_socket == Py_None) {
2451 goto error;
2452 }
2453
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002454 if (servername == NULL) {
2455 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2456 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002457 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002458 else {
2459 servername_o = PyBytes_FromString(servername);
2460 if (servername_o == NULL) {
2461 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2462 goto error;
2463 }
2464 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2465 if (servername_idna == NULL) {
2466 PyErr_WriteUnraisable(servername_o);
2467 Py_DECREF(servername_o);
2468 goto error;
2469 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002470 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002471 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2472 servername_idna, ssl_ctx, NULL);
2473 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002474 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002475 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002476
2477 if (result == NULL) {
2478 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2479 *al = SSL_AD_HANDSHAKE_FAILURE;
2480 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2481 }
2482 else {
2483 if (result != Py_None) {
2484 *al = (int) PyLong_AsLong(result);
2485 if (PyErr_Occurred()) {
2486 PyErr_WriteUnraisable(result);
2487 *al = SSL_AD_INTERNAL_ERROR;
2488 }
2489 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2490 }
2491 else {
2492 ret = SSL_TLSEXT_ERR_OK;
2493 }
2494 Py_DECREF(result);
2495 }
2496
Stefan Krah20d60802013-01-17 17:07:17 +01002497#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002498 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002499#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002500 return ret;
2501
2502error:
2503 Py_DECREF(ssl_socket);
2504 *al = SSL_AD_INTERNAL_ERROR;
2505 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002506#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002507 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002508#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002509 return ret;
2510}
Antoine Pitroua5963382013-03-30 16:39:00 +01002511#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002512
2513PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2514"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002515\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002516This sets a callback that will be called when a server name is provided by\n\
2517the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002518\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002519If the argument is None then the callback is disabled. The method is called\n\
2520with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002521See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002522
2523static PyObject *
2524set_servername_callback(PySSLContext *self, PyObject *args)
2525{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002526#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002527 PyObject *cb;
2528
2529 if (!PyArg_ParseTuple(args, "O", &cb))
2530 return NULL;
2531
2532 Py_CLEAR(self->set_hostname);
2533 if (cb == Py_None) {
2534 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2535 }
2536 else {
2537 if (!PyCallable_Check(cb)) {
2538 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2539 PyErr_SetString(PyExc_TypeError,
2540 "not a callable object");
2541 return NULL;
2542 }
2543 Py_INCREF(cb);
2544 self->set_hostname = cb;
2545 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
2546 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
2547 }
2548 Py_RETURN_NONE;
2549#else
2550 PyErr_SetString(PyExc_NotImplementedError,
2551 "The TLS extension servername callback, "
2552 "SSL_CTX_set_tlsext_servername_callback, "
2553 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002554 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002555#endif
2556}
2557
Antoine Pitrou152efa22010-05-16 18:19:27 +00002558static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002559 {"options", (getter) get_options,
2560 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002561 {"verify_mode", (getter) get_verify_mode,
2562 (setter) set_verify_mode, NULL},
2563 {NULL}, /* sentinel */
2564};
2565
2566static struct PyMethodDef context_methods[] = {
2567 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2568 METH_VARARGS | METH_KEYWORDS, NULL},
2569 {"set_ciphers", (PyCFunction) set_ciphers,
2570 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002571 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2572 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002573 {"load_cert_chain", (PyCFunction) load_cert_chain,
2574 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002575 {"load_dh_params", (PyCFunction) load_dh_params,
2576 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002577 {"load_verify_locations", (PyCFunction) load_verify_locations,
2578 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002579 {"session_stats", (PyCFunction) session_stats,
2580 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002581 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2582 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002583#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002584 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2585 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002586#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002587 {"set_servername_callback", (PyCFunction) set_servername_callback,
2588 METH_VARARGS, PySSL_set_servername_callback_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002589 {NULL, NULL} /* sentinel */
2590};
2591
2592static PyTypeObject PySSLContext_Type = {
2593 PyVarObject_HEAD_INIT(NULL, 0)
2594 "_ssl._SSLContext", /*tp_name*/
2595 sizeof(PySSLContext), /*tp_basicsize*/
2596 0, /*tp_itemsize*/
2597 (destructor)context_dealloc, /*tp_dealloc*/
2598 0, /*tp_print*/
2599 0, /*tp_getattr*/
2600 0, /*tp_setattr*/
2601 0, /*tp_reserved*/
2602 0, /*tp_repr*/
2603 0, /*tp_as_number*/
2604 0, /*tp_as_sequence*/
2605 0, /*tp_as_mapping*/
2606 0, /*tp_hash*/
2607 0, /*tp_call*/
2608 0, /*tp_str*/
2609 0, /*tp_getattro*/
2610 0, /*tp_setattro*/
2611 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002612 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002613 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002614 (traverseproc) context_traverse, /*tp_traverse*/
2615 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002616 0, /*tp_richcompare*/
2617 0, /*tp_weaklistoffset*/
2618 0, /*tp_iter*/
2619 0, /*tp_iternext*/
2620 context_methods, /*tp_methods*/
2621 0, /*tp_members*/
2622 context_getsetlist, /*tp_getset*/
2623 0, /*tp_base*/
2624 0, /*tp_dict*/
2625 0, /*tp_descr_get*/
2626 0, /*tp_descr_set*/
2627 0, /*tp_dictoffset*/
2628 0, /*tp_init*/
2629 0, /*tp_alloc*/
2630 context_new, /*tp_new*/
2631};
2632
2633
2634
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002635#ifdef HAVE_OPENSSL_RAND
2636
2637/* helper routines for seeding the SSL PRNG */
2638static PyObject *
2639PySSL_RAND_add(PyObject *self, PyObject *args)
2640{
2641 char *buf;
2642 int len;
2643 double entropy;
2644
2645 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002646 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002647 RAND_add(buf, len, entropy);
2648 Py_INCREF(Py_None);
2649 return Py_None;
2650}
2651
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002652PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002653"RAND_add(string, entropy)\n\
2654\n\
2655Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002656bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002657
2658static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002659PySSL_RAND(int len, int pseudo)
2660{
2661 int ok;
2662 PyObject *bytes;
2663 unsigned long err;
2664 const char *errstr;
2665 PyObject *v;
2666
2667 bytes = PyBytes_FromStringAndSize(NULL, len);
2668 if (bytes == NULL)
2669 return NULL;
2670 if (pseudo) {
2671 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2672 if (ok == 0 || ok == 1)
2673 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2674 }
2675 else {
2676 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2677 if (ok == 1)
2678 return bytes;
2679 }
2680 Py_DECREF(bytes);
2681
2682 err = ERR_get_error();
2683 errstr = ERR_reason_error_string(err);
2684 v = Py_BuildValue("(ks)", err, errstr);
2685 if (v != NULL) {
2686 PyErr_SetObject(PySSLErrorObject, v);
2687 Py_DECREF(v);
2688 }
2689 return NULL;
2690}
2691
2692static PyObject *
2693PySSL_RAND_bytes(PyObject *self, PyObject *args)
2694{
2695 int len;
2696 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2697 return NULL;
2698 return PySSL_RAND(len, 0);
2699}
2700
2701PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2702"RAND_bytes(n) -> bytes\n\
2703\n\
2704Generate n cryptographically strong pseudo-random bytes.");
2705
2706static PyObject *
2707PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2708{
2709 int len;
2710 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2711 return NULL;
2712 return PySSL_RAND(len, 1);
2713}
2714
2715PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2716"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2717\n\
2718Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2719generated are cryptographically strong.");
2720
2721static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002722PySSL_RAND_status(PyObject *self)
2723{
Christian Heimes217cfd12007-12-02 14:31:20 +00002724 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002725}
2726
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002727PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002728"RAND_status() -> 0 or 1\n\
2729\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002730Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2731It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2732using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002733
2734static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002735PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002736{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002737 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002738 int bytes;
2739
Jesus Ceac8754a12012-09-11 02:00:58 +02002740 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002741 PyUnicode_FSConverter, &path))
2742 return NULL;
2743
2744 bytes = RAND_egd(PyBytes_AsString(path));
2745 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002746 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002747 PyErr_SetString(PySSLErrorObject,
2748 "EGD connection failed or EGD did not return "
2749 "enough data to seed the PRNG");
2750 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002751 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002752 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002753}
2754
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002755PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002756"RAND_egd(path) -> bytes\n\
2757\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002758Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2759Returns number of bytes read. Raises SSLError if connection to EGD\n\
2760fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002761
2762#endif
2763
Bill Janssen40a0f662008-08-12 16:56:25 +00002764
2765
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002766/* List of functions exported by this module. */
2767
2768static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002769 {"_test_decode_cert", PySSL_test_decode_certificate,
2770 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002771#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002772 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2773 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002774 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2775 PySSL_RAND_bytes_doc},
2776 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2777 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002778 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002779 PySSL_RAND_egd_doc},
2780 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2781 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002782#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002783 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002784};
2785
2786
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002787#ifdef WITH_THREAD
2788
2789/* an implementation of OpenSSL threading operations in terms
2790 of the Python C thread library */
2791
2792static PyThread_type_lock *_ssl_locks = NULL;
2793
2794static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002795 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002796}
2797
Bill Janssen6e027db2007-11-15 22:23:56 +00002798static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002799 (int mode, int n, const char *file, int line) {
2800 /* this function is needed to perform locking on shared data
2801 structures. (Note that OpenSSL uses a number of global data
2802 structures that will be implicitly shared whenever multiple
2803 threads use OpenSSL.) Multi-threaded applications will
2804 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002805
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002806 locking_function() must be able to handle up to
2807 CRYPTO_num_locks() different mutex locks. It sets the n-th
2808 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002809
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002810 file and line are the file number of the function setting the
2811 lock. They can be useful for debugging.
2812 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002813
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002814 if ((_ssl_locks == NULL) ||
2815 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2816 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002817
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002818 if (mode & CRYPTO_LOCK) {
2819 PyThread_acquire_lock(_ssl_locks[n], 1);
2820 } else {
2821 PyThread_release_lock(_ssl_locks[n]);
2822 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002823}
2824
2825static int _setup_ssl_threads(void) {
2826
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002827 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002828
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002829 if (_ssl_locks == NULL) {
2830 _ssl_locks_count = CRYPTO_num_locks();
2831 _ssl_locks = (PyThread_type_lock *)
2832 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2833 if (_ssl_locks == NULL)
2834 return 0;
2835 memset(_ssl_locks, 0,
2836 sizeof(PyThread_type_lock) * _ssl_locks_count);
2837 for (i = 0; i < _ssl_locks_count; i++) {
2838 _ssl_locks[i] = PyThread_allocate_lock();
2839 if (_ssl_locks[i] == NULL) {
2840 unsigned int j;
2841 for (j = 0; j < i; j++) {
2842 PyThread_free_lock(_ssl_locks[j]);
2843 }
2844 free(_ssl_locks);
2845 return 0;
2846 }
2847 }
2848 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2849 CRYPTO_set_id_callback(_ssl_thread_id_function);
2850 }
2851 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002852}
2853
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002854#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002855
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002856PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002857"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002858for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002859
Martin v. Löwis1a214512008-06-11 05:26:20 +00002860
2861static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002862 PyModuleDef_HEAD_INIT,
2863 "_ssl",
2864 module_doc,
2865 -1,
2866 PySSL_methods,
2867 NULL,
2868 NULL,
2869 NULL,
2870 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002871};
2872
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002873
2874static void
2875parse_openssl_version(unsigned long libver,
2876 unsigned int *major, unsigned int *minor,
2877 unsigned int *fix, unsigned int *patch,
2878 unsigned int *status)
2879{
2880 *status = libver & 0xF;
2881 libver >>= 4;
2882 *patch = libver & 0xFF;
2883 libver >>= 8;
2884 *fix = libver & 0xFF;
2885 libver >>= 8;
2886 *minor = libver & 0xFF;
2887 libver >>= 8;
2888 *major = libver & 0xFF;
2889}
2890
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002891PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002892PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002893{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002894 PyObject *m, *d, *r;
2895 unsigned long libver;
2896 unsigned int major, minor, fix, patch, status;
2897 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002898 struct py_ssl_error_code *errcode;
2899 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002900
Antoine Pitrou152efa22010-05-16 18:19:27 +00002901 if (PyType_Ready(&PySSLContext_Type) < 0)
2902 return NULL;
2903 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002904 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002905
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002906 m = PyModule_Create(&_sslmodule);
2907 if (m == NULL)
2908 return NULL;
2909 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002910
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002911 /* Load _socket module and its C API */
2912 socket_api = PySocketModule_ImportModuleAndAPI();
2913 if (!socket_api)
2914 return NULL;
2915 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002916
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002917 /* Init OpenSSL */
2918 SSL_load_error_strings();
2919 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002920#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002921 /* note that this will start threading if not already started */
2922 if (!_setup_ssl_threads()) {
2923 return NULL;
2924 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002925#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002926 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002927
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002928 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002929 sslerror_type_slots[0].pfunc = PyExc_OSError;
2930 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002931 if (PySSLErrorObject == NULL)
2932 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002933
Antoine Pitrou41032a62011-10-27 23:56:55 +02002934 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2935 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2936 PySSLErrorObject, NULL);
2937 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2938 "ssl.SSLWantReadError", SSLWantReadError_doc,
2939 PySSLErrorObject, NULL);
2940 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2941 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2942 PySSLErrorObject, NULL);
2943 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2944 "ssl.SSLSyscallError", SSLSyscallError_doc,
2945 PySSLErrorObject, NULL);
2946 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2947 "ssl.SSLEOFError", SSLEOFError_doc,
2948 PySSLErrorObject, NULL);
2949 if (PySSLZeroReturnErrorObject == NULL
2950 || PySSLWantReadErrorObject == NULL
2951 || PySSLWantWriteErrorObject == NULL
2952 || PySSLSyscallErrorObject == NULL
2953 || PySSLEOFErrorObject == NULL)
2954 return NULL;
2955 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2956 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2957 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2958 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2959 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2960 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002961 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002962 if (PyDict_SetItemString(d, "_SSLContext",
2963 (PyObject *)&PySSLContext_Type) != 0)
2964 return NULL;
2965 if (PyDict_SetItemString(d, "_SSLSocket",
2966 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002967 return NULL;
2968 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2969 PY_SSL_ERROR_ZERO_RETURN);
2970 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2971 PY_SSL_ERROR_WANT_READ);
2972 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2973 PY_SSL_ERROR_WANT_WRITE);
2974 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2975 PY_SSL_ERROR_WANT_X509_LOOKUP);
2976 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2977 PY_SSL_ERROR_SYSCALL);
2978 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2979 PY_SSL_ERROR_SSL);
2980 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2981 PY_SSL_ERROR_WANT_CONNECT);
2982 /* non ssl.h errorcodes */
2983 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2984 PY_SSL_ERROR_EOF);
2985 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2986 PY_SSL_ERROR_INVALID_ERROR_CODE);
2987 /* cert requirements */
2988 PyModule_AddIntConstant(m, "CERT_NONE",
2989 PY_SSL_CERT_NONE);
2990 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2991 PY_SSL_CERT_OPTIONAL);
2992 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2993 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002994
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002995 /* Alert Descriptions from ssl.h */
2996 /* note RESERVED constants no longer intended for use have been removed */
2997 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
2998
2999#define ADD_AD_CONSTANT(s) \
3000 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
3001 SSL_AD_##s)
3002
3003 ADD_AD_CONSTANT(CLOSE_NOTIFY);
3004 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
3005 ADD_AD_CONSTANT(BAD_RECORD_MAC);
3006 ADD_AD_CONSTANT(RECORD_OVERFLOW);
3007 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
3008 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
3009 ADD_AD_CONSTANT(BAD_CERTIFICATE);
3010 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
3011 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
3012 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
3013 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
3014 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
3015 ADD_AD_CONSTANT(UNKNOWN_CA);
3016 ADD_AD_CONSTANT(ACCESS_DENIED);
3017 ADD_AD_CONSTANT(DECODE_ERROR);
3018 ADD_AD_CONSTANT(DECRYPT_ERROR);
3019 ADD_AD_CONSTANT(PROTOCOL_VERSION);
3020 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
3021 ADD_AD_CONSTANT(INTERNAL_ERROR);
3022 ADD_AD_CONSTANT(USER_CANCELLED);
3023 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003024 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003025#ifdef SSL_AD_UNSUPPORTED_EXTENSION
3026 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
3027#endif
3028#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
3029 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
3030#endif
3031#ifdef SSL_AD_UNRECOGNIZED_NAME
3032 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
3033#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003034#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
3035 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
3036#endif
3037#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
3038 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
3039#endif
3040#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
3041 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
3042#endif
3043
3044#undef ADD_AD_CONSTANT
3045
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003046 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02003047#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003048 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
3049 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02003050#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003051 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
3052 PY_SSL_VERSION_SSL3);
3053 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
3054 PY_SSL_VERSION_SSL23);
3055 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
3056 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003057#if HAVE_TLSv1_2
3058 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
3059 PY_SSL_VERSION_TLS1_1);
3060 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
3061 PY_SSL_VERSION_TLS1_2);
3062#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003063
Antoine Pitroub5218772010-05-21 09:56:06 +00003064 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01003065 PyModule_AddIntConstant(m, "OP_ALL",
3066 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00003067 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
3068 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
3069 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003070#if HAVE_TLSv1_2
3071 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
3072 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
3073#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01003074 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
3075 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003076 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003077#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003078 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003079#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003080#ifdef SSL_OP_NO_COMPRESSION
3081 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
3082 SSL_OP_NO_COMPRESSION);
3083#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00003084
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003085#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00003086 r = Py_True;
3087#else
3088 r = Py_False;
3089#endif
3090 Py_INCREF(r);
3091 PyModule_AddObject(m, "HAS_SNI", r);
3092
Antoine Pitroud6494802011-07-21 01:11:30 +02003093#if HAVE_OPENSSL_FINISHED
3094 r = Py_True;
3095#else
3096 r = Py_False;
3097#endif
3098 Py_INCREF(r);
3099 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
3100
Antoine Pitrou501da612011-12-21 09:27:41 +01003101#ifdef OPENSSL_NO_ECDH
3102 r = Py_False;
3103#else
3104 r = Py_True;
3105#endif
3106 Py_INCREF(r);
3107 PyModule_AddObject(m, "HAS_ECDH", r);
3108
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003109#ifdef OPENSSL_NPN_NEGOTIATED
3110 r = Py_True;
3111#else
3112 r = Py_False;
3113#endif
3114 Py_INCREF(r);
3115 PyModule_AddObject(m, "HAS_NPN", r);
3116
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003117 /* Mappings for error codes */
3118 err_codes_to_names = PyDict_New();
3119 err_names_to_codes = PyDict_New();
3120 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
3121 return NULL;
3122 errcode = error_codes;
3123 while (errcode->mnemonic != NULL) {
3124 PyObject *mnemo, *key;
3125 mnemo = PyUnicode_FromString(errcode->mnemonic);
3126 key = Py_BuildValue("ii", errcode->library, errcode->reason);
3127 if (mnemo == NULL || key == NULL)
3128 return NULL;
3129 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
3130 return NULL;
3131 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
3132 return NULL;
3133 Py_DECREF(key);
3134 Py_DECREF(mnemo);
3135 errcode++;
3136 }
3137 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
3138 return NULL;
3139 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
3140 return NULL;
3141
3142 lib_codes_to_names = PyDict_New();
3143 if (lib_codes_to_names == NULL)
3144 return NULL;
3145 libcode = library_codes;
3146 while (libcode->library != NULL) {
3147 PyObject *mnemo, *key;
3148 key = PyLong_FromLong(libcode->code);
3149 mnemo = PyUnicode_FromString(libcode->library);
3150 if (key == NULL || mnemo == NULL)
3151 return NULL;
3152 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
3153 return NULL;
3154 Py_DECREF(key);
3155 Py_DECREF(mnemo);
3156 libcode++;
3157 }
3158 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
3159 return NULL;
3160
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003161 /* OpenSSL version */
3162 /* SSLeay() gives us the version of the library linked against,
3163 which could be different from the headers version.
3164 */
3165 libver = SSLeay();
3166 r = PyLong_FromUnsignedLong(libver);
3167 if (r == NULL)
3168 return NULL;
3169 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
3170 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003171 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003172 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3173 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
3174 return NULL;
3175 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
3176 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
3177 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003178
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003179 libver = OPENSSL_VERSION_NUMBER;
3180 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
3181 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3182 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
3183 return NULL;
3184
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003185 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003186}