blob: 971dd05a0e7aeef4d8b44c8e402833bf92230a49 [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;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000473
Antoine Pitrou152efa22010-05-16 18:19:27 +0000474 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000475 if (self == NULL)
476 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000477
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000478 self->peer_cert = NULL;
479 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000480 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100481 self->ctx = sslctx;
482 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000483
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000484 /* Make sure the SSL error state is initialized */
485 (void) ERR_get_state();
486 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000487
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000488 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000489 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000490 PySSL_END_ALLOW_THREADS
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100491 SSL_set_app_data(self->ssl,self);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000492 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000493#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000494 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000495#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000496
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100497#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000498 if (server_hostname != NULL)
499 SSL_set_tlsext_host_name(self->ssl, server_hostname);
500#endif
501
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000502 /* If the socket is in non-blocking mode or timeout mode, set the BIO
503 * to non-blocking mode (blocking is the default)
504 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000505 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000506 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
507 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
508 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000509
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000510 PySSL_BEGIN_ALLOW_THREADS
511 if (socket_type == PY_SSL_CLIENT)
512 SSL_set_connect_state(self->ssl);
513 else
514 SSL_set_accept_state(self->ssl);
515 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000516
Antoine Pitroud6494802011-07-21 01:11:30 +0200517 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000518 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000519 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000520}
521
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000522/* SSL object methods */
523
Antoine Pitrou152efa22010-05-16 18:19:27 +0000524static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000525{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000526 int ret;
527 int err;
528 int sockstate, nonblocking;
529 PySocketSockObject *sock
530 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000531
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000532 if (((PyObject*)sock) == Py_None) {
533 _setSSLError("Underlying socket connection gone",
534 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
535 return NULL;
536 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000537 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000538
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000539 /* just in case the blocking state of the socket has been changed */
540 nonblocking = (sock->sock_timeout >= 0.0);
541 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
542 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000543
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000544 /* Actually negotiate SSL connection */
545 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000546 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000547 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000548 ret = SSL_do_handshake(self->ssl);
549 err = SSL_get_error(self->ssl, ret);
550 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000551 if (PyErr_CheckSignals())
552 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000553 if (err == SSL_ERROR_WANT_READ) {
554 sockstate = check_socket_and_wait_for_timeout(sock, 0);
555 } else if (err == SSL_ERROR_WANT_WRITE) {
556 sockstate = check_socket_and_wait_for_timeout(sock, 1);
557 } else {
558 sockstate = SOCKET_OPERATION_OK;
559 }
560 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000561 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000562 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000563 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000564 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
565 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000566 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000567 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000568 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
569 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000570 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000571 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000572 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
573 break;
574 }
575 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000576 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000577 if (ret < 1)
578 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000579
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000580 if (self->peer_cert)
581 X509_free (self->peer_cert);
582 PySSL_BEGIN_ALLOW_THREADS
583 self->peer_cert = SSL_get_peer_certificate(self->ssl);
584 PySSL_END_ALLOW_THREADS
585
586 Py_INCREF(Py_None);
587 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000588
589error:
590 Py_DECREF(sock);
591 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000592}
593
Thomas Woutersed03b412007-08-28 21:37:11 +0000594static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000595_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000596
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000597 char namebuf[X509_NAME_MAXLEN];
598 int buflen;
599 PyObject *name_obj;
600 PyObject *value_obj;
601 PyObject *attr;
602 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000603
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000604 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
605 if (buflen < 0) {
606 _setSSLError(NULL, 0, __FILE__, __LINE__);
607 goto fail;
608 }
609 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
610 if (name_obj == NULL)
611 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000612
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000613 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
614 if (buflen < 0) {
615 _setSSLError(NULL, 0, __FILE__, __LINE__);
616 Py_DECREF(name_obj);
617 goto fail;
618 }
619 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000620 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000621 OPENSSL_free(valuebuf);
622 if (value_obj == NULL) {
623 Py_DECREF(name_obj);
624 goto fail;
625 }
626 attr = PyTuple_New(2);
627 if (attr == NULL) {
628 Py_DECREF(name_obj);
629 Py_DECREF(value_obj);
630 goto fail;
631 }
632 PyTuple_SET_ITEM(attr, 0, name_obj);
633 PyTuple_SET_ITEM(attr, 1, value_obj);
634 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000635
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000636 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000637 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000638}
639
640static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000641_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000642{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000643 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
644 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
645 PyObject *rdnt;
646 PyObject *attr = NULL; /* tuple to hold an attribute */
647 int entry_count = X509_NAME_entry_count(xname);
648 X509_NAME_ENTRY *entry;
649 ASN1_OBJECT *name;
650 ASN1_STRING *value;
651 int index_counter;
652 int rdn_level = -1;
653 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000654
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000655 dn = PyList_New(0);
656 if (dn == NULL)
657 return NULL;
658 /* now create another tuple to hold the top-level RDN */
659 rdn = PyList_New(0);
660 if (rdn == NULL)
661 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000662
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000663 for (index_counter = 0;
664 index_counter < entry_count;
665 index_counter++)
666 {
667 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000668
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000669 /* check to see if we've gotten to a new RDN */
670 if (rdn_level >= 0) {
671 if (rdn_level != entry->set) {
672 /* yes, new RDN */
673 /* add old RDN to DN */
674 rdnt = PyList_AsTuple(rdn);
675 Py_DECREF(rdn);
676 if (rdnt == NULL)
677 goto fail0;
678 retcode = PyList_Append(dn, rdnt);
679 Py_DECREF(rdnt);
680 if (retcode < 0)
681 goto fail0;
682 /* create new RDN */
683 rdn = PyList_New(0);
684 if (rdn == NULL)
685 goto fail0;
686 }
687 }
688 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000689
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000690 /* now add this attribute to the current RDN */
691 name = X509_NAME_ENTRY_get_object(entry);
692 value = X509_NAME_ENTRY_get_data(entry);
693 attr = _create_tuple_for_attribute(name, value);
694 /*
695 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
696 entry->set,
697 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
698 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
699 */
700 if (attr == NULL)
701 goto fail1;
702 retcode = PyList_Append(rdn, attr);
703 Py_DECREF(attr);
704 if (retcode < 0)
705 goto fail1;
706 }
707 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100708 if (rdn != NULL) {
709 if (PyList_GET_SIZE(rdn) > 0) {
710 rdnt = PyList_AsTuple(rdn);
711 Py_DECREF(rdn);
712 if (rdnt == NULL)
713 goto fail0;
714 retcode = PyList_Append(dn, rdnt);
715 Py_DECREF(rdnt);
716 if (retcode < 0)
717 goto fail0;
718 }
719 else {
720 Py_DECREF(rdn);
721 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000722 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000723
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000724 /* convert list to tuple */
725 rdnt = PyList_AsTuple(dn);
726 Py_DECREF(dn);
727 if (rdnt == NULL)
728 return NULL;
729 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000730
731 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000732 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000733
734 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 Py_XDECREF(dn);
736 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000737}
738
739static PyObject *
740_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000741
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000742 /* this code follows the procedure outlined in
743 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
744 function to extract the STACK_OF(GENERAL_NAME),
745 then iterates through the stack to add the
746 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000747
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000748 int i, j;
749 PyObject *peer_alt_names = Py_None;
750 PyObject *v, *t;
751 X509_EXTENSION *ext = NULL;
752 GENERAL_NAMES *names = NULL;
753 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000754 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000755 BIO *biobuf = NULL;
756 char buf[2048];
757 char *vptr;
758 int len;
759 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000760#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000761 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000762#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000763 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000764#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000765
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000766 if (certificate == NULL)
767 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000768
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 /* get a memory buffer */
770 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000771
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200772 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000773 while ((i = X509_get_ext_by_NID(
774 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000775
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000776 if (peer_alt_names == Py_None) {
777 peer_alt_names = PyList_New(0);
778 if (peer_alt_names == NULL)
779 goto fail;
780 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000781
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000782 /* now decode the altName */
783 ext = X509_get_ext(certificate, i);
784 if(!(method = X509V3_EXT_get(ext))) {
785 PyErr_SetString
786 (PySSLErrorObject,
787 ERRSTR("No method for internalizing subjectAltName!"));
788 goto fail;
789 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000790
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000791 p = ext->value->data;
792 if (method->it)
793 names = (GENERAL_NAMES*)
794 (ASN1_item_d2i(NULL,
795 &p,
796 ext->value->length,
797 ASN1_ITEM_ptr(method->it)));
798 else
799 names = (GENERAL_NAMES*)
800 (method->d2i(NULL,
801 &p,
802 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000803
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000804 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000806 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000808 name = sk_GENERAL_NAME_value(names, j);
809 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000811 /* we special-case DirName as a tuple of
812 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000813
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000814 t = PyTuple_New(2);
815 if (t == NULL) {
816 goto fail;
817 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000818
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000819 v = PyUnicode_FromString("DirName");
820 if (v == NULL) {
821 Py_DECREF(t);
822 goto fail;
823 }
824 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000825
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 v = _create_tuple_for_X509_NAME (name->d.dirn);
827 if (v == NULL) {
828 Py_DECREF(t);
829 goto fail;
830 }
831 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000832
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000834
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000835 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000836
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000837 (void) BIO_reset(biobuf);
838 GENERAL_NAME_print(biobuf, name);
839 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
840 if (len < 0) {
841 _setSSLError(NULL, 0, __FILE__, __LINE__);
842 goto fail;
843 }
844 vptr = strchr(buf, ':');
845 if (vptr == NULL)
846 goto fail;
847 t = PyTuple_New(2);
848 if (t == NULL)
849 goto fail;
850 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
851 if (v == NULL) {
852 Py_DECREF(t);
853 goto fail;
854 }
855 PyTuple_SET_ITEM(t, 0, v);
856 v = PyUnicode_FromStringAndSize((vptr + 1),
857 (len - (vptr - buf + 1)));
858 if (v == NULL) {
859 Py_DECREF(t);
860 goto fail;
861 }
862 PyTuple_SET_ITEM(t, 1, v);
863 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000864
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000865 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000866
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000867 if (PyList_Append(peer_alt_names, t) < 0) {
868 Py_DECREF(t);
869 goto fail;
870 }
871 Py_DECREF(t);
872 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100873 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000874 }
875 BIO_free(biobuf);
876 if (peer_alt_names != Py_None) {
877 v = PyList_AsTuple(peer_alt_names);
878 Py_DECREF(peer_alt_names);
879 return v;
880 } else {
881 return peer_alt_names;
882 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000883
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000884
885 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000886 if (biobuf != NULL)
887 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000888
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000889 if (peer_alt_names != Py_None) {
890 Py_XDECREF(peer_alt_names);
891 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000892
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000893 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000894}
895
896static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000897_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000898
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000899 PyObject *retval = NULL;
900 BIO *biobuf = NULL;
901 PyObject *peer;
902 PyObject *peer_alt_names = NULL;
903 PyObject *issuer;
904 PyObject *version;
905 PyObject *sn_obj;
906 ASN1_INTEGER *serialNumber;
907 char buf[2048];
908 int len;
909 ASN1_TIME *notBefore, *notAfter;
910 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000911
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000912 retval = PyDict_New();
913 if (retval == NULL)
914 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000915
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000916 peer = _create_tuple_for_X509_NAME(
917 X509_get_subject_name(certificate));
918 if (peer == NULL)
919 goto fail0;
920 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
921 Py_DECREF(peer);
922 goto fail0;
923 }
924 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000925
Antoine Pitroufb046912010-11-09 20:21:19 +0000926 issuer = _create_tuple_for_X509_NAME(
927 X509_get_issuer_name(certificate));
928 if (issuer == NULL)
929 goto fail0;
930 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000932 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000934 Py_DECREF(issuer);
935
936 version = PyLong_FromLong(X509_get_version(certificate) + 1);
937 if (PyDict_SetItemString(retval, "version", version) < 0) {
938 Py_DECREF(version);
939 goto fail0;
940 }
941 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000942
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 /* get a memory buffer */
944 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000945
Antoine Pitroufb046912010-11-09 20:21:19 +0000946 (void) BIO_reset(biobuf);
947 serialNumber = X509_get_serialNumber(certificate);
948 /* should not exceed 20 octets, 160 bits, so buf is big enough */
949 i2a_ASN1_INTEGER(biobuf, serialNumber);
950 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
951 if (len < 0) {
952 _setSSLError(NULL, 0, __FILE__, __LINE__);
953 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000954 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000955 sn_obj = PyUnicode_FromStringAndSize(buf, len);
956 if (sn_obj == NULL)
957 goto fail1;
958 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
959 Py_DECREF(sn_obj);
960 goto fail1;
961 }
962 Py_DECREF(sn_obj);
963
964 (void) BIO_reset(biobuf);
965 notBefore = X509_get_notBefore(certificate);
966 ASN1_TIME_print(biobuf, notBefore);
967 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
968 if (len < 0) {
969 _setSSLError(NULL, 0, __FILE__, __LINE__);
970 goto fail1;
971 }
972 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
973 if (pnotBefore == NULL)
974 goto fail1;
975 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
976 Py_DECREF(pnotBefore);
977 goto fail1;
978 }
979 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000980
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000981 (void) BIO_reset(biobuf);
982 notAfter = X509_get_notAfter(certificate);
983 ASN1_TIME_print(biobuf, notAfter);
984 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
985 if (len < 0) {
986 _setSSLError(NULL, 0, __FILE__, __LINE__);
987 goto fail1;
988 }
989 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
990 if (pnotAfter == NULL)
991 goto fail1;
992 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
993 Py_DECREF(pnotAfter);
994 goto fail1;
995 }
996 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000997
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000998 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000999
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001000 peer_alt_names = _get_peer_alt_names(certificate);
1001 if (peer_alt_names == NULL)
1002 goto fail1;
1003 else if (peer_alt_names != Py_None) {
1004 if (PyDict_SetItemString(retval, "subjectAltName",
1005 peer_alt_names) < 0) {
1006 Py_DECREF(peer_alt_names);
1007 goto fail1;
1008 }
1009 Py_DECREF(peer_alt_names);
1010 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001011
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001012 BIO_free(biobuf);
1013 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001014
1015 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001016 if (biobuf != NULL)
1017 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001018 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001019 Py_XDECREF(retval);
1020 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001021}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001022
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001023
1024static PyObject *
1025PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1026
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001027 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001028 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001029 X509 *x=NULL;
1030 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001031
Antoine Pitroufb046912010-11-09 20:21:19 +00001032 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1033 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001034 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001035
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001036 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1037 PyErr_SetString(PySSLErrorObject,
1038 "Can't malloc memory to read file");
1039 goto fail0;
1040 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001041
Victor Stinner3800e1e2010-05-16 21:23:48 +00001042 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001043 PyErr_SetString(PySSLErrorObject,
1044 "Can't open file");
1045 goto fail0;
1046 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001047
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001048 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1049 if (x == NULL) {
1050 PyErr_SetString(PySSLErrorObject,
1051 "Error decoding PEM-encoded file");
1052 goto fail0;
1053 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001054
Antoine Pitroufb046912010-11-09 20:21:19 +00001055 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001056 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001057
1058 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001059 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001060 if (cert != NULL) BIO_free(cert);
1061 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001062}
1063
1064
1065static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001066PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001067{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068 PyObject *retval = NULL;
1069 int len;
1070 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001071 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001072
Antoine Pitrou721738f2012-08-15 23:20:39 +02001073 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001074 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001076 if (!self->peer_cert)
1077 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001078
Antoine Pitrou721738f2012-08-15 23:20:39 +02001079 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001080 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001081
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001082 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001083
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001084 bytes_buf = NULL;
1085 len = i2d_X509(self->peer_cert, &bytes_buf);
1086 if (len < 0) {
1087 PySSL_SetError(self, len, __FILE__, __LINE__);
1088 return NULL;
1089 }
1090 /* this is actually an immutable bytes sequence */
1091 retval = PyBytes_FromStringAndSize
1092 ((const char *) bytes_buf, len);
1093 OPENSSL_free(bytes_buf);
1094 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001095
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001096 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001097 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001098 if ((verification & SSL_VERIFY_PEER) == 0)
1099 return PyDict_New();
1100 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001101 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001102 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001103}
1104
1105PyDoc_STRVAR(PySSL_peercert_doc,
1106"peer_certificate([der=False]) -> certificate\n\
1107\n\
1108Returns the certificate for the peer. If no certificate was provided,\n\
1109returns None. If a certificate was provided, but not validated, returns\n\
1110an empty dictionary. Otherwise returns a dict containing information\n\
1111about the peer certificate.\n\
1112\n\
1113If the optional argument is True, returns a DER-encoded copy of the\n\
1114peer certificate, or None if no certificate was provided. This will\n\
1115return the certificate even if it wasn't validated.");
1116
Antoine Pitrou152efa22010-05-16 18:19:27 +00001117static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001118
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001119 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001120 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001121 char *cipher_name;
1122 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001123
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001124 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001125 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001126 current = SSL_get_current_cipher(self->ssl);
1127 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001128 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001129
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001130 retval = PyTuple_New(3);
1131 if (retval == NULL)
1132 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001133
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001134 cipher_name = (char *) SSL_CIPHER_get_name(current);
1135 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001136 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 PyTuple_SET_ITEM(retval, 0, Py_None);
1138 } else {
1139 v = PyUnicode_FromString(cipher_name);
1140 if (v == NULL)
1141 goto fail0;
1142 PyTuple_SET_ITEM(retval, 0, v);
1143 }
1144 cipher_protocol = SSL_CIPHER_get_version(current);
1145 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001146 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 PyTuple_SET_ITEM(retval, 1, Py_None);
1148 } else {
1149 v = PyUnicode_FromString(cipher_protocol);
1150 if (v == NULL)
1151 goto fail0;
1152 PyTuple_SET_ITEM(retval, 1, v);
1153 }
1154 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1155 if (v == NULL)
1156 goto fail0;
1157 PyTuple_SET_ITEM(retval, 2, v);
1158 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001159
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001160 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001161 Py_DECREF(retval);
1162 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001163}
1164
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001165#ifdef OPENSSL_NPN_NEGOTIATED
1166static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1167 const unsigned char *out;
1168 unsigned int outlen;
1169
1170 SSL_get0_next_proto_negotiated(self->ssl,
1171 &out, &outlen);
1172
1173 if (out == NULL)
1174 Py_RETURN_NONE;
1175 return PyUnicode_FromStringAndSize((char *) out, outlen);
1176}
1177#endif
1178
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001179static PyObject *PySSL_compression(PySSLSocket *self) {
1180#ifdef OPENSSL_NO_COMP
1181 Py_RETURN_NONE;
1182#else
1183 const COMP_METHOD *comp_method;
1184 const char *short_name;
1185
1186 if (self->ssl == NULL)
1187 Py_RETURN_NONE;
1188 comp_method = SSL_get_current_compression(self->ssl);
1189 if (comp_method == NULL || comp_method->type == NID_undef)
1190 Py_RETURN_NONE;
1191 short_name = OBJ_nid2sn(comp_method->type);
1192 if (short_name == NULL)
1193 Py_RETURN_NONE;
1194 return PyUnicode_DecodeFSDefault(short_name);
1195#endif
1196}
1197
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001198static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1199 Py_INCREF(self->ctx);
1200 return self->ctx;
1201}
1202
1203static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1204 void *closure) {
1205
1206 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001207#if !HAVE_SNI
1208 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1209 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001210 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001211#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001212 Py_INCREF(value);
1213 Py_DECREF(self->ctx);
1214 self->ctx = (PySSLContext *) value;
1215 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001216#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001217 } else {
1218 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1219 return -1;
1220 }
1221
1222 return 0;
1223}
1224
1225PyDoc_STRVAR(PySSL_set_context_doc,
1226"_setter_context(ctx)\n\
1227\
1228This changes the context associated with the SSLSocket. This is typically\n\
1229used from within a callback function set by the set_servername_callback\n\
1230on the SSLContext to change the certificate information associated with the\n\
1231SSLSocket before the cryptographic exchange handshake messages\n");
1232
1233
1234
Antoine Pitrou152efa22010-05-16 18:19:27 +00001235static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001236{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001237 if (self->peer_cert) /* Possible not to have one? */
1238 X509_free (self->peer_cert);
1239 if (self->ssl)
1240 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001242 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001244}
1245
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001246/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001247 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001248 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001249 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001250
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001251static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001252check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001253{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001254 fd_set fds;
1255 struct timeval tv;
1256 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001257
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001258 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1259 if (s->sock_timeout < 0.0)
1260 return SOCKET_IS_BLOCKING;
1261 else if (s->sock_timeout == 0.0)
1262 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001263
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001264 /* Guard against closed socket */
1265 if (s->sock_fd < 0)
1266 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001267
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001268 /* Prefer poll, if available, since you can poll() any fd
1269 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001270#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001271 {
1272 struct pollfd pollfd;
1273 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001274
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001275 pollfd.fd = s->sock_fd;
1276 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 /* s->sock_timeout is in seconds, timeout in ms */
1279 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1280 PySSL_BEGIN_ALLOW_THREADS
1281 rc = poll(&pollfd, 1, timeout);
1282 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001283
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001284 goto normal_return;
1285 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001286#endif
1287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001289 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001291
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001292 /* Construct the arguments to select */
1293 tv.tv_sec = (int)s->sock_timeout;
1294 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1295 FD_ZERO(&fds);
1296 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001297
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001298 /* See if the socket is ready */
1299 PySSL_BEGIN_ALLOW_THREADS
1300 if (writing)
1301 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1302 else
1303 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1304 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001305
Bill Janssen6e027db2007-11-15 22:23:56 +00001306#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001307normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001308#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001309 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1310 (when we are able to write or when there's something to read) */
1311 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001312}
1313
Antoine Pitrou152efa22010-05-16 18:19:27 +00001314static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001315{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001316 Py_buffer buf;
1317 int len;
1318 int sockstate;
1319 int err;
1320 int nonblocking;
1321 PySocketSockObject *sock
1322 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001323
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001324 if (((PyObject*)sock) == Py_None) {
1325 _setSSLError("Underlying socket connection gone",
1326 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1327 return NULL;
1328 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001329 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001331 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1332 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001333 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001334 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001335
1336 /* just in case the blocking state of the socket has been changed */
1337 nonblocking = (sock->sock_timeout >= 0.0);
1338 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1339 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1340
1341 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1342 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001343 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001344 "The write operation timed out");
1345 goto error;
1346 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1347 PyErr_SetString(PySSLErrorObject,
1348 "Underlying socket has been closed.");
1349 goto error;
1350 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1351 PyErr_SetString(PySSLErrorObject,
1352 "Underlying socket too large for select().");
1353 goto error;
1354 }
1355 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001356 PySSL_BEGIN_ALLOW_THREADS
1357 len = SSL_write(self->ssl, buf.buf, buf.len);
1358 err = SSL_get_error(self->ssl, len);
1359 PySSL_END_ALLOW_THREADS
1360 if (PyErr_CheckSignals()) {
1361 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001362 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001363 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001364 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001365 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001366 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001367 } else {
1368 sockstate = SOCKET_OPERATION_OK;
1369 }
1370 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001371 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001372 "The write operation timed out");
1373 goto error;
1374 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1375 PyErr_SetString(PySSLErrorObject,
1376 "Underlying socket has been closed.");
1377 goto error;
1378 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1379 break;
1380 }
1381 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001382
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001383 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001384 PyBuffer_Release(&buf);
1385 if (len > 0)
1386 return PyLong_FromLong(len);
1387 else
1388 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001389
1390error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001391 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001392 PyBuffer_Release(&buf);
1393 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001394}
1395
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001396PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001397"write(s) -> len\n\
1398\n\
1399Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001400of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001401
Antoine Pitrou152efa22010-05-16 18:19:27 +00001402static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001403{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001404 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001405
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001406 PySSL_BEGIN_ALLOW_THREADS
1407 count = SSL_pending(self->ssl);
1408 PySSL_END_ALLOW_THREADS
1409 if (count < 0)
1410 return PySSL_SetError(self, count, __FILE__, __LINE__);
1411 else
1412 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001413}
1414
1415PyDoc_STRVAR(PySSL_SSLpending_doc,
1416"pending() -> count\n\
1417\n\
1418Returns the number of already decrypted bytes available for read,\n\
1419pending on the connection.\n");
1420
Antoine Pitrou152efa22010-05-16 18:19:27 +00001421static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001422{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001423 PyObject *dest = NULL;
1424 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001425 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001426 int len, count;
1427 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001428 int sockstate;
1429 int err;
1430 int nonblocking;
1431 PySocketSockObject *sock
1432 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001433
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001434 if (((PyObject*)sock) == Py_None) {
1435 _setSSLError("Underlying socket connection gone",
1436 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1437 return NULL;
1438 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001439 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001440
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001441 buf.obj = NULL;
1442 buf.buf = NULL;
1443 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001444 goto error;
1445
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001446 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1447 dest = PyBytes_FromStringAndSize(NULL, len);
1448 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001449 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001450 mem = PyBytes_AS_STRING(dest);
1451 }
1452 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001453 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001454 mem = buf.buf;
1455 if (len <= 0 || len > buf.len) {
1456 len = (int) buf.len;
1457 if (buf.len != len) {
1458 PyErr_SetString(PyExc_OverflowError,
1459 "maximum length can't fit in a C 'int'");
1460 goto error;
1461 }
1462 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001463 }
1464
1465 /* just in case the blocking state of the socket has been changed */
1466 nonblocking = (sock->sock_timeout >= 0.0);
1467 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1468 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1469
1470 /* first check if there are bytes ready to be read */
1471 PySSL_BEGIN_ALLOW_THREADS
1472 count = SSL_pending(self->ssl);
1473 PySSL_END_ALLOW_THREADS
1474
1475 if (!count) {
1476 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1477 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001478 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001479 "The read operation timed out");
1480 goto error;
1481 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1482 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001483 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001484 goto error;
1485 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1486 count = 0;
1487 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001488 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001489 }
1490 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001491 PySSL_BEGIN_ALLOW_THREADS
1492 count = SSL_read(self->ssl, mem, len);
1493 err = SSL_get_error(self->ssl, count);
1494 PySSL_END_ALLOW_THREADS
1495 if (PyErr_CheckSignals())
1496 goto error;
1497 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001498 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001499 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001500 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001501 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1502 (SSL_get_shutdown(self->ssl) ==
1503 SSL_RECEIVED_SHUTDOWN))
1504 {
1505 count = 0;
1506 goto done;
1507 } else {
1508 sockstate = SOCKET_OPERATION_OK;
1509 }
1510 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001511 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001512 "The read operation timed out");
1513 goto error;
1514 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1515 break;
1516 }
1517 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1518 if (count <= 0) {
1519 PySSL_SetError(self, count, __FILE__, __LINE__);
1520 goto error;
1521 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001522
1523done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001524 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001525 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001526 _PyBytes_Resize(&dest, count);
1527 return dest;
1528 }
1529 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001530 PyBuffer_Release(&buf);
1531 return PyLong_FromLong(count);
1532 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001533
1534error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001535 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001536 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001537 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001538 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001539 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001540 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001541}
1542
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001543PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001544"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001545\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001546Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001547
Antoine Pitrou152efa22010-05-16 18:19:27 +00001548static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001549{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001550 int err, ssl_err, sockstate, nonblocking;
1551 int zeros = 0;
1552 PySocketSockObject *sock
1553 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001554
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001555 /* Guard against closed socket */
1556 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1557 _setSSLError("Underlying socket connection gone",
1558 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1559 return NULL;
1560 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001561 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001562
1563 /* Just in case the blocking state of the socket has been changed */
1564 nonblocking = (sock->sock_timeout >= 0.0);
1565 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1566 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1567
1568 while (1) {
1569 PySSL_BEGIN_ALLOW_THREADS
1570 /* Disable read-ahead so that unwrap can work correctly.
1571 * Otherwise OpenSSL might read in too much data,
1572 * eating clear text data that happens to be
1573 * transmitted after the SSL shutdown.
1574 * Should be safe to call repeatedly everytime this
1575 * function is used and the shutdown_seen_zero != 0
1576 * condition is met.
1577 */
1578 if (self->shutdown_seen_zero)
1579 SSL_set_read_ahead(self->ssl, 0);
1580 err = SSL_shutdown(self->ssl);
1581 PySSL_END_ALLOW_THREADS
1582 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1583 if (err > 0)
1584 break;
1585 if (err == 0) {
1586 /* Don't loop endlessly; instead preserve legacy
1587 behaviour of trying SSL_shutdown() only twice.
1588 This looks necessary for OpenSSL < 0.9.8m */
1589 if (++zeros > 1)
1590 break;
1591 /* Shutdown was sent, now try receiving */
1592 self->shutdown_seen_zero = 1;
1593 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001594 }
1595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001596 /* Possibly retry shutdown until timeout or failure */
1597 ssl_err = SSL_get_error(self->ssl, err);
1598 if (ssl_err == SSL_ERROR_WANT_READ)
1599 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1600 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1601 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1602 else
1603 break;
1604 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1605 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001606 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001607 "The read operation timed out");
1608 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001609 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001610 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001611 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001612 }
1613 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1614 PyErr_SetString(PySSLErrorObject,
1615 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001616 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001617 }
1618 else if (sockstate != SOCKET_OPERATION_OK)
1619 /* Retain the SSL error code */
1620 break;
1621 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001622
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001623 if (err < 0) {
1624 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001625 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001626 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001627 else
1628 /* It's already INCREF'ed */
1629 return (PyObject *) sock;
1630
1631error:
1632 Py_DECREF(sock);
1633 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001634}
1635
1636PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1637"shutdown(s) -> socket\n\
1638\n\
1639Does the SSL shutdown handshake with the remote end, and returns\n\
1640the underlying socket object.");
1641
Antoine Pitroud6494802011-07-21 01:11:30 +02001642#if HAVE_OPENSSL_FINISHED
1643static PyObject *
1644PySSL_tls_unique_cb(PySSLSocket *self)
1645{
1646 PyObject *retval = NULL;
1647 char buf[PySSL_CB_MAXLEN];
1648 int len;
1649
1650 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1651 /* if session is resumed XOR we are the client */
1652 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1653 }
1654 else {
1655 /* if a new session XOR we are the server */
1656 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1657 }
1658
1659 /* It cannot be negative in current OpenSSL version as of July 2011 */
1660 assert(len >= 0);
1661 if (len == 0)
1662 Py_RETURN_NONE;
1663
1664 retval = PyBytes_FromStringAndSize(buf, len);
1665
1666 return retval;
1667}
1668
1669PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1670"tls_unique_cb() -> bytes\n\
1671\n\
1672Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1673\n\
1674If the TLS handshake is not yet complete, None is returned");
1675
1676#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001677
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001678static PyGetSetDef ssl_getsetlist[] = {
1679 {"context", (getter) PySSL_get_context,
1680 (setter) PySSL_set_context, PySSL_set_context_doc},
1681 {NULL}, /* sentinel */
1682};
1683
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001684static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001685 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1686 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1687 PySSL_SSLwrite_doc},
1688 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1689 PySSL_SSLread_doc},
1690 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1691 PySSL_SSLpending_doc},
1692 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1693 PySSL_peercert_doc},
1694 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001695#ifdef OPENSSL_NPN_NEGOTIATED
1696 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1697#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001698 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001699 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1700 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001701#if HAVE_OPENSSL_FINISHED
1702 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1703 PySSL_tls_unique_cb_doc},
1704#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001705 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001706};
1707
Antoine Pitrou152efa22010-05-16 18:19:27 +00001708static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001709 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001710 "_ssl._SSLSocket", /*tp_name*/
1711 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001712 0, /*tp_itemsize*/
1713 /* methods */
1714 (destructor)PySSL_dealloc, /*tp_dealloc*/
1715 0, /*tp_print*/
1716 0, /*tp_getattr*/
1717 0, /*tp_setattr*/
1718 0, /*tp_reserved*/
1719 0, /*tp_repr*/
1720 0, /*tp_as_number*/
1721 0, /*tp_as_sequence*/
1722 0, /*tp_as_mapping*/
1723 0, /*tp_hash*/
1724 0, /*tp_call*/
1725 0, /*tp_str*/
1726 0, /*tp_getattro*/
1727 0, /*tp_setattro*/
1728 0, /*tp_as_buffer*/
1729 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1730 0, /*tp_doc*/
1731 0, /*tp_traverse*/
1732 0, /*tp_clear*/
1733 0, /*tp_richcompare*/
1734 0, /*tp_weaklistoffset*/
1735 0, /*tp_iter*/
1736 0, /*tp_iternext*/
1737 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001738 0, /*tp_members*/
1739 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001740};
1741
Antoine Pitrou152efa22010-05-16 18:19:27 +00001742
1743/*
1744 * _SSLContext objects
1745 */
1746
1747static PyObject *
1748context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1749{
1750 char *kwlist[] = {"protocol", NULL};
1751 PySSLContext *self;
1752 int proto_version = PY_SSL_VERSION_SSL23;
1753 SSL_CTX *ctx = NULL;
1754
1755 if (!PyArg_ParseTupleAndKeywords(
1756 args, kwds, "i:_SSLContext", kwlist,
1757 &proto_version))
1758 return NULL;
1759
1760 PySSL_BEGIN_ALLOW_THREADS
1761 if (proto_version == PY_SSL_VERSION_TLS1)
1762 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01001763#if HAVE_TLSv1_2
1764 else if (proto_version == PY_SSL_VERSION_TLS1_1)
1765 ctx = SSL_CTX_new(TLSv1_1_method());
1766 else if (proto_version == PY_SSL_VERSION_TLS1_2)
1767 ctx = SSL_CTX_new(TLSv1_2_method());
1768#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001769 else if (proto_version == PY_SSL_VERSION_SSL3)
1770 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001771#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001772 else if (proto_version == PY_SSL_VERSION_SSL2)
1773 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001774#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001775 else if (proto_version == PY_SSL_VERSION_SSL23)
1776 ctx = SSL_CTX_new(SSLv23_method());
1777 else
1778 proto_version = -1;
1779 PySSL_END_ALLOW_THREADS
1780
1781 if (proto_version == -1) {
1782 PyErr_SetString(PyExc_ValueError,
1783 "invalid protocol version");
1784 return NULL;
1785 }
1786 if (ctx == NULL) {
1787 PyErr_SetString(PySSLErrorObject,
1788 "failed to allocate SSL context");
1789 return NULL;
1790 }
1791
1792 assert(type != NULL && type->tp_alloc != NULL);
1793 self = (PySSLContext *) type->tp_alloc(type, 0);
1794 if (self == NULL) {
1795 SSL_CTX_free(ctx);
1796 return NULL;
1797 }
1798 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001799#ifdef OPENSSL_NPN_NEGOTIATED
1800 self->npn_protocols = NULL;
1801#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001802#ifndef OPENSSL_NO_TLSEXT
1803 self->set_hostname = NULL;
1804#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001805 /* Defaults */
1806 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001807 SSL_CTX_set_options(self->ctx,
1808 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001809
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001810#define SID_CTX "Python"
1811 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1812 sizeof(SID_CTX));
1813#undef SID_CTX
1814
Antoine Pitrou152efa22010-05-16 18:19:27 +00001815 return (PyObject *)self;
1816}
1817
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001818static int
1819context_traverse(PySSLContext *self, visitproc visit, void *arg)
1820{
1821#ifndef OPENSSL_NO_TLSEXT
1822 Py_VISIT(self->set_hostname);
1823#endif
1824 return 0;
1825}
1826
1827static int
1828context_clear(PySSLContext *self)
1829{
1830#ifndef OPENSSL_NO_TLSEXT
1831 Py_CLEAR(self->set_hostname);
1832#endif
1833 return 0;
1834}
1835
Antoine Pitrou152efa22010-05-16 18:19:27 +00001836static void
1837context_dealloc(PySSLContext *self)
1838{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001839 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001840 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001841#ifdef OPENSSL_NPN_NEGOTIATED
1842 PyMem_Free(self->npn_protocols);
1843#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001844 Py_TYPE(self)->tp_free(self);
1845}
1846
1847static PyObject *
1848set_ciphers(PySSLContext *self, PyObject *args)
1849{
1850 int ret;
1851 const char *cipherlist;
1852
1853 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1854 return NULL;
1855 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1856 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001857 /* Clearing the error queue is necessary on some OpenSSL versions,
1858 otherwise the error will be reported again when another SSL call
1859 is done. */
1860 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001861 PyErr_SetString(PySSLErrorObject,
1862 "No cipher can be selected.");
1863 return NULL;
1864 }
1865 Py_RETURN_NONE;
1866}
1867
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001868#ifdef OPENSSL_NPN_NEGOTIATED
1869/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1870static int
1871_advertiseNPN_cb(SSL *s,
1872 const unsigned char **data, unsigned int *len,
1873 void *args)
1874{
1875 PySSLContext *ssl_ctx = (PySSLContext *) args;
1876
1877 if (ssl_ctx->npn_protocols == NULL) {
1878 *data = (unsigned char *) "";
1879 *len = 0;
1880 } else {
1881 *data = (unsigned char *) ssl_ctx->npn_protocols;
1882 *len = ssl_ctx->npn_protocols_len;
1883 }
1884
1885 return SSL_TLSEXT_ERR_OK;
1886}
1887/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1888static int
1889_selectNPN_cb(SSL *s,
1890 unsigned char **out, unsigned char *outlen,
1891 const unsigned char *server, unsigned int server_len,
1892 void *args)
1893{
1894 PySSLContext *ssl_ctx = (PySSLContext *) args;
1895
1896 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1897 int client_len;
1898
1899 if (client == NULL) {
1900 client = (unsigned char *) "";
1901 client_len = 0;
1902 } else {
1903 client_len = ssl_ctx->npn_protocols_len;
1904 }
1905
1906 SSL_select_next_proto(out, outlen,
1907 server, server_len,
1908 client, client_len);
1909
1910 return SSL_TLSEXT_ERR_OK;
1911}
1912#endif
1913
1914static PyObject *
1915_set_npn_protocols(PySSLContext *self, PyObject *args)
1916{
1917#ifdef OPENSSL_NPN_NEGOTIATED
1918 Py_buffer protos;
1919
1920 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1921 return NULL;
1922
Christian Heimes5cb31c92012-09-20 12:42:54 +02001923 if (self->npn_protocols != NULL) {
1924 PyMem_Free(self->npn_protocols);
1925 }
1926
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001927 self->npn_protocols = PyMem_Malloc(protos.len);
1928 if (self->npn_protocols == NULL) {
1929 PyBuffer_Release(&protos);
1930 return PyErr_NoMemory();
1931 }
1932 memcpy(self->npn_protocols, protos.buf, protos.len);
1933 self->npn_protocols_len = (int) protos.len;
1934
1935 /* set both server and client callbacks, because the context can
1936 * be used to create both types of sockets */
1937 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
1938 _advertiseNPN_cb,
1939 self);
1940 SSL_CTX_set_next_proto_select_cb(self->ctx,
1941 _selectNPN_cb,
1942 self);
1943
1944 PyBuffer_Release(&protos);
1945 Py_RETURN_NONE;
1946#else
1947 PyErr_SetString(PyExc_NotImplementedError,
1948 "The NPN extension requires OpenSSL 1.0.1 or later.");
1949 return NULL;
1950#endif
1951}
1952
Antoine Pitrou152efa22010-05-16 18:19:27 +00001953static PyObject *
1954get_verify_mode(PySSLContext *self, void *c)
1955{
1956 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1957 case SSL_VERIFY_NONE:
1958 return PyLong_FromLong(PY_SSL_CERT_NONE);
1959 case SSL_VERIFY_PEER:
1960 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1961 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1962 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1963 }
1964 PyErr_SetString(PySSLErrorObject,
1965 "invalid return value from SSL_CTX_get_verify_mode");
1966 return NULL;
1967}
1968
1969static int
1970set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1971{
1972 int n, mode;
1973 if (!PyArg_Parse(arg, "i", &n))
1974 return -1;
1975 if (n == PY_SSL_CERT_NONE)
1976 mode = SSL_VERIFY_NONE;
1977 else if (n == PY_SSL_CERT_OPTIONAL)
1978 mode = SSL_VERIFY_PEER;
1979 else if (n == PY_SSL_CERT_REQUIRED)
1980 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1981 else {
1982 PyErr_SetString(PyExc_ValueError,
1983 "invalid value for verify_mode");
1984 return -1;
1985 }
1986 SSL_CTX_set_verify(self->ctx, mode, NULL);
1987 return 0;
1988}
1989
1990static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001991get_options(PySSLContext *self, void *c)
1992{
1993 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1994}
1995
1996static int
1997set_options(PySSLContext *self, PyObject *arg, void *c)
1998{
1999 long new_opts, opts, set, clear;
2000 if (!PyArg_Parse(arg, "l", &new_opts))
2001 return -1;
2002 opts = SSL_CTX_get_options(self->ctx);
2003 clear = opts & ~new_opts;
2004 set = ~opts & new_opts;
2005 if (clear) {
2006#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2007 SSL_CTX_clear_options(self->ctx, clear);
2008#else
2009 PyErr_SetString(PyExc_ValueError,
2010 "can't clear options before OpenSSL 0.9.8m");
2011 return -1;
2012#endif
2013 }
2014 if (set)
2015 SSL_CTX_set_options(self->ctx, set);
2016 return 0;
2017}
2018
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002019typedef struct {
2020 PyThreadState *thread_state;
2021 PyObject *callable;
2022 char *password;
2023 Py_ssize_t size;
2024 int error;
2025} _PySSLPasswordInfo;
2026
2027static int
2028_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2029 const char *bad_type_error)
2030{
2031 /* Set the password and size fields of a _PySSLPasswordInfo struct
2032 from a unicode, bytes, or byte array object.
2033 The password field will be dynamically allocated and must be freed
2034 by the caller */
2035 PyObject *password_bytes = NULL;
2036 const char *data = NULL;
2037 Py_ssize_t size;
2038
2039 if (PyUnicode_Check(password)) {
2040 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2041 if (!password_bytes) {
2042 goto error;
2043 }
2044 data = PyBytes_AS_STRING(password_bytes);
2045 size = PyBytes_GET_SIZE(password_bytes);
2046 } else if (PyBytes_Check(password)) {
2047 data = PyBytes_AS_STRING(password);
2048 size = PyBytes_GET_SIZE(password);
2049 } else if (PyByteArray_Check(password)) {
2050 data = PyByteArray_AS_STRING(password);
2051 size = PyByteArray_GET_SIZE(password);
2052 } else {
2053 PyErr_SetString(PyExc_TypeError, bad_type_error);
2054 goto error;
2055 }
2056
2057 free(pw_info->password);
2058 pw_info->password = malloc(size);
2059 if (!pw_info->password) {
2060 PyErr_SetString(PyExc_MemoryError,
2061 "unable to allocate password buffer");
2062 goto error;
2063 }
2064 memcpy(pw_info->password, data, size);
2065 pw_info->size = size;
2066
2067 Py_XDECREF(password_bytes);
2068 return 1;
2069
2070error:
2071 Py_XDECREF(password_bytes);
2072 return 0;
2073}
2074
2075static int
2076_password_callback(char *buf, int size, int rwflag, void *userdata)
2077{
2078 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2079 PyObject *fn_ret = NULL;
2080
2081 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2082
2083 if (pw_info->callable) {
2084 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2085 if (!fn_ret) {
2086 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2087 core python API, so we could use it to add a frame here */
2088 goto error;
2089 }
2090
2091 if (!_pwinfo_set(pw_info, fn_ret,
2092 "password callback must return a string")) {
2093 goto error;
2094 }
2095 Py_CLEAR(fn_ret);
2096 }
2097
2098 if (pw_info->size > size) {
2099 PyErr_Format(PyExc_ValueError,
2100 "password cannot be longer than %d bytes", size);
2101 goto error;
2102 }
2103
2104 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2105 memcpy(buf, pw_info->password, pw_info->size);
2106 return pw_info->size;
2107
2108error:
2109 Py_XDECREF(fn_ret);
2110 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2111 pw_info->error = 1;
2112 return -1;
2113}
2114
Antoine Pitroub5218772010-05-21 09:56:06 +00002115static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002116load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2117{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002118 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2119 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002120 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002121 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2122 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2123 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002124 int r;
2125
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002126 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002127 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002128 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002129 "O|OO:load_cert_chain", kwlist,
2130 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002131 return NULL;
2132 if (keyfile == Py_None)
2133 keyfile = NULL;
2134 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2135 PyErr_SetString(PyExc_TypeError,
2136 "certfile should be a valid filesystem path");
2137 return NULL;
2138 }
2139 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2140 PyErr_SetString(PyExc_TypeError,
2141 "keyfile should be a valid filesystem path");
2142 goto error;
2143 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002144 if (password && password != Py_None) {
2145 if (PyCallable_Check(password)) {
2146 pw_info.callable = password;
2147 } else if (!_pwinfo_set(&pw_info, password,
2148 "password should be a string or callable")) {
2149 goto error;
2150 }
2151 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2152 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2153 }
2154 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002155 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2156 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002157 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002158 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002159 if (pw_info.error) {
2160 ERR_clear_error();
2161 /* the password callback has already set the error information */
2162 }
2163 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002164 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002165 PyErr_SetFromErrno(PyExc_IOError);
2166 }
2167 else {
2168 _setSSLError(NULL, 0, __FILE__, __LINE__);
2169 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002170 goto error;
2171 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002172 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002173 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002174 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2175 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002176 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2177 Py_CLEAR(keyfile_bytes);
2178 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002179 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002180 if (pw_info.error) {
2181 ERR_clear_error();
2182 /* the password callback has already set the error information */
2183 }
2184 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002185 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002186 PyErr_SetFromErrno(PyExc_IOError);
2187 }
2188 else {
2189 _setSSLError(NULL, 0, __FILE__, __LINE__);
2190 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002191 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002192 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002193 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002194 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002195 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002196 if (r != 1) {
2197 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002198 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002199 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002200 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2201 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2202 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002203 Py_RETURN_NONE;
2204
2205error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002206 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2207 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2208 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002209 Py_XDECREF(keyfile_bytes);
2210 Py_XDECREF(certfile_bytes);
2211 return NULL;
2212}
2213
2214static PyObject *
2215load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2216{
2217 char *kwlist[] = {"cafile", "capath", NULL};
2218 PyObject *cafile = NULL, *capath = NULL;
2219 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2220 const char *cafile_buf = NULL, *capath_buf = NULL;
2221 int r;
2222
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002223 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002224 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2225 "|OO:load_verify_locations", kwlist,
2226 &cafile, &capath))
2227 return NULL;
2228 if (cafile == Py_None)
2229 cafile = NULL;
2230 if (capath == Py_None)
2231 capath = NULL;
2232 if (cafile == NULL && capath == NULL) {
2233 PyErr_SetString(PyExc_TypeError,
2234 "cafile and capath cannot be both omitted");
2235 return NULL;
2236 }
2237 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2238 PyErr_SetString(PyExc_TypeError,
2239 "cafile should be a valid filesystem path");
2240 return NULL;
2241 }
2242 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002243 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002244 PyErr_SetString(PyExc_TypeError,
2245 "capath should be a valid filesystem path");
2246 return NULL;
2247 }
2248 if (cafile)
2249 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2250 if (capath)
2251 capath_buf = PyBytes_AS_STRING(capath_bytes);
2252 PySSL_BEGIN_ALLOW_THREADS
2253 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2254 PySSL_END_ALLOW_THREADS
2255 Py_XDECREF(cafile_bytes);
2256 Py_XDECREF(capath_bytes);
2257 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002258 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002259 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002260 PyErr_SetFromErrno(PyExc_IOError);
2261 }
2262 else {
2263 _setSSLError(NULL, 0, __FILE__, __LINE__);
2264 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002265 return NULL;
2266 }
2267 Py_RETURN_NONE;
2268}
2269
2270static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002271load_dh_params(PySSLContext *self, PyObject *filepath)
2272{
2273 FILE *f;
2274 DH *dh;
2275
2276 f = _Py_fopen(filepath, "rb");
2277 if (f == NULL) {
2278 if (!PyErr_Occurred())
2279 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2280 return NULL;
2281 }
2282 errno = 0;
2283 PySSL_BEGIN_ALLOW_THREADS
2284 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002285 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002286 PySSL_END_ALLOW_THREADS
2287 if (dh == NULL) {
2288 if (errno != 0) {
2289 ERR_clear_error();
2290 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2291 }
2292 else {
2293 _setSSLError(NULL, 0, __FILE__, __LINE__);
2294 }
2295 return NULL;
2296 }
2297 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2298 _setSSLError(NULL, 0, __FILE__, __LINE__);
2299 DH_free(dh);
2300 Py_RETURN_NONE;
2301}
2302
2303static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002304context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2305{
Antoine Pitroud5323212010-10-22 18:19:07 +00002306 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002307 PySocketSockObject *sock;
2308 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002309 char *hostname = NULL;
2310 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002311
Antoine Pitroud5323212010-10-22 18:19:07 +00002312 /* server_hostname is either None (or absent), or to be encoded
2313 using the idna encoding. */
2314 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002315 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002316 &sock, &server_side,
2317 Py_TYPE(Py_None), &hostname_obj)) {
2318 PyErr_Clear();
2319 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2320 PySocketModule.Sock_Type,
2321 &sock, &server_side,
2322 "idna", &hostname))
2323 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002324#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002325 PyMem_Free(hostname);
2326 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2327 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002328 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002329#endif
2330 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002331
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002332 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002333 hostname);
2334 if (hostname != NULL)
2335 PyMem_Free(hostname);
2336 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002337}
2338
Antoine Pitroub0182c82010-10-12 20:09:02 +00002339static PyObject *
2340session_stats(PySSLContext *self, PyObject *unused)
2341{
2342 int r;
2343 PyObject *value, *stats = PyDict_New();
2344 if (!stats)
2345 return NULL;
2346
2347#define ADD_STATS(SSL_NAME, KEY_NAME) \
2348 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2349 if (value == NULL) \
2350 goto error; \
2351 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2352 Py_DECREF(value); \
2353 if (r < 0) \
2354 goto error;
2355
2356 ADD_STATS(number, "number");
2357 ADD_STATS(connect, "connect");
2358 ADD_STATS(connect_good, "connect_good");
2359 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2360 ADD_STATS(accept, "accept");
2361 ADD_STATS(accept_good, "accept_good");
2362 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2363 ADD_STATS(accept, "accept");
2364 ADD_STATS(hits, "hits");
2365 ADD_STATS(misses, "misses");
2366 ADD_STATS(timeouts, "timeouts");
2367 ADD_STATS(cache_full, "cache_full");
2368
2369#undef ADD_STATS
2370
2371 return stats;
2372
2373error:
2374 Py_DECREF(stats);
2375 return NULL;
2376}
2377
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002378static PyObject *
2379set_default_verify_paths(PySSLContext *self, PyObject *unused)
2380{
2381 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2382 _setSSLError(NULL, 0, __FILE__, __LINE__);
2383 return NULL;
2384 }
2385 Py_RETURN_NONE;
2386}
2387
Antoine Pitrou501da612011-12-21 09:27:41 +01002388#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002389static PyObject *
2390set_ecdh_curve(PySSLContext *self, PyObject *name)
2391{
2392 PyObject *name_bytes;
2393 int nid;
2394 EC_KEY *key;
2395
2396 if (!PyUnicode_FSConverter(name, &name_bytes))
2397 return NULL;
2398 assert(PyBytes_Check(name_bytes));
2399 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2400 Py_DECREF(name_bytes);
2401 if (nid == 0) {
2402 PyErr_Format(PyExc_ValueError,
2403 "unknown elliptic curve name %R", name);
2404 return NULL;
2405 }
2406 key = EC_KEY_new_by_curve_name(nid);
2407 if (key == NULL) {
2408 _setSSLError(NULL, 0, __FILE__, __LINE__);
2409 return NULL;
2410 }
2411 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2412 EC_KEY_free(key);
2413 Py_RETURN_NONE;
2414}
Antoine Pitrou501da612011-12-21 09:27:41 +01002415#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002416
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002417#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002418static int
2419_servername_callback(SSL *s, int *al, void *args)
2420{
2421 int ret;
2422 PySSLContext *ssl_ctx = (PySSLContext *) args;
2423 PySSLSocket *ssl;
2424 PyObject *servername_o;
2425 PyObject *servername_idna;
2426 PyObject *result;
2427 /* The high-level ssl.SSLSocket object */
2428 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002429 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002430#ifdef WITH_THREAD
2431 PyGILState_STATE gstate = PyGILState_Ensure();
2432#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002433
2434 if (ssl_ctx->set_hostname == NULL) {
2435 /* remove race condition in this the call back while if removing the
2436 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002437#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002438 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002439#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002440 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002441 }
2442
2443 ssl = SSL_get_app_data(s);
2444 assert(PySSLSocket_Check(ssl));
2445 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2446 Py_INCREF(ssl_socket);
2447 if (ssl_socket == Py_None) {
2448 goto error;
2449 }
2450
2451 servername_o = PyBytes_FromString(servername);
2452 if (servername_o == NULL) {
2453 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2454 goto error;
2455 }
2456 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2457 if (servername_idna == NULL) {
2458 PyErr_WriteUnraisable(servername_o);
2459 Py_DECREF(servername_o);
2460 goto error;
2461 }
2462 Py_DECREF(servername_o);
2463 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2464 servername_idna, ssl_ctx, NULL);
2465 Py_DECREF(ssl_socket);
2466 Py_DECREF(servername_idna);
2467
2468 if (result == NULL) {
2469 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2470 *al = SSL_AD_HANDSHAKE_FAILURE;
2471 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2472 }
2473 else {
2474 if (result != Py_None) {
2475 *al = (int) PyLong_AsLong(result);
2476 if (PyErr_Occurred()) {
2477 PyErr_WriteUnraisable(result);
2478 *al = SSL_AD_INTERNAL_ERROR;
2479 }
2480 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2481 }
2482 else {
2483 ret = SSL_TLSEXT_ERR_OK;
2484 }
2485 Py_DECREF(result);
2486 }
2487
Stefan Krah20d60802013-01-17 17:07:17 +01002488#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002489 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002490#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002491 return ret;
2492
2493error:
2494 Py_DECREF(ssl_socket);
2495 *al = SSL_AD_INTERNAL_ERROR;
2496 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
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}
Antoine Pitroua5963382013-03-30 16:39:00 +01002502#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002503
2504PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2505"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002506\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002507This sets a callback that will be called when a server name is provided by\n\
2508the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002509\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002510If the argument is None then the callback is disabled. The method is called\n\
2511with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002512See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002513
2514static PyObject *
2515set_servername_callback(PySSLContext *self, PyObject *args)
2516{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002517#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002518 PyObject *cb;
2519
2520 if (!PyArg_ParseTuple(args, "O", &cb))
2521 return NULL;
2522
2523 Py_CLEAR(self->set_hostname);
2524 if (cb == Py_None) {
2525 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2526 }
2527 else {
2528 if (!PyCallable_Check(cb)) {
2529 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2530 PyErr_SetString(PyExc_TypeError,
2531 "not a callable object");
2532 return NULL;
2533 }
2534 Py_INCREF(cb);
2535 self->set_hostname = cb;
2536 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
2537 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
2538 }
2539 Py_RETURN_NONE;
2540#else
2541 PyErr_SetString(PyExc_NotImplementedError,
2542 "The TLS extension servername callback, "
2543 "SSL_CTX_set_tlsext_servername_callback, "
2544 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002545 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002546#endif
2547}
2548
Antoine Pitrou152efa22010-05-16 18:19:27 +00002549static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002550 {"options", (getter) get_options,
2551 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002552 {"verify_mode", (getter) get_verify_mode,
2553 (setter) set_verify_mode, NULL},
2554 {NULL}, /* sentinel */
2555};
2556
2557static struct PyMethodDef context_methods[] = {
2558 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2559 METH_VARARGS | METH_KEYWORDS, NULL},
2560 {"set_ciphers", (PyCFunction) set_ciphers,
2561 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002562 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2563 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002564 {"load_cert_chain", (PyCFunction) load_cert_chain,
2565 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002566 {"load_dh_params", (PyCFunction) load_dh_params,
2567 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002568 {"load_verify_locations", (PyCFunction) load_verify_locations,
2569 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002570 {"session_stats", (PyCFunction) session_stats,
2571 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002572 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2573 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002574#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002575 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2576 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002577#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002578 {"set_servername_callback", (PyCFunction) set_servername_callback,
2579 METH_VARARGS, PySSL_set_servername_callback_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002580 {NULL, NULL} /* sentinel */
2581};
2582
2583static PyTypeObject PySSLContext_Type = {
2584 PyVarObject_HEAD_INIT(NULL, 0)
2585 "_ssl._SSLContext", /*tp_name*/
2586 sizeof(PySSLContext), /*tp_basicsize*/
2587 0, /*tp_itemsize*/
2588 (destructor)context_dealloc, /*tp_dealloc*/
2589 0, /*tp_print*/
2590 0, /*tp_getattr*/
2591 0, /*tp_setattr*/
2592 0, /*tp_reserved*/
2593 0, /*tp_repr*/
2594 0, /*tp_as_number*/
2595 0, /*tp_as_sequence*/
2596 0, /*tp_as_mapping*/
2597 0, /*tp_hash*/
2598 0, /*tp_call*/
2599 0, /*tp_str*/
2600 0, /*tp_getattro*/
2601 0, /*tp_setattro*/
2602 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002603 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002604 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002605 (traverseproc) context_traverse, /*tp_traverse*/
2606 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002607 0, /*tp_richcompare*/
2608 0, /*tp_weaklistoffset*/
2609 0, /*tp_iter*/
2610 0, /*tp_iternext*/
2611 context_methods, /*tp_methods*/
2612 0, /*tp_members*/
2613 context_getsetlist, /*tp_getset*/
2614 0, /*tp_base*/
2615 0, /*tp_dict*/
2616 0, /*tp_descr_get*/
2617 0, /*tp_descr_set*/
2618 0, /*tp_dictoffset*/
2619 0, /*tp_init*/
2620 0, /*tp_alloc*/
2621 context_new, /*tp_new*/
2622};
2623
2624
2625
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002626#ifdef HAVE_OPENSSL_RAND
2627
2628/* helper routines for seeding the SSL PRNG */
2629static PyObject *
2630PySSL_RAND_add(PyObject *self, PyObject *args)
2631{
2632 char *buf;
2633 int len;
2634 double entropy;
2635
2636 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002637 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002638 RAND_add(buf, len, entropy);
2639 Py_INCREF(Py_None);
2640 return Py_None;
2641}
2642
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002643PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002644"RAND_add(string, entropy)\n\
2645\n\
2646Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002647bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002648
2649static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002650PySSL_RAND(int len, int pseudo)
2651{
2652 int ok;
2653 PyObject *bytes;
2654 unsigned long err;
2655 const char *errstr;
2656 PyObject *v;
2657
2658 bytes = PyBytes_FromStringAndSize(NULL, len);
2659 if (bytes == NULL)
2660 return NULL;
2661 if (pseudo) {
2662 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2663 if (ok == 0 || ok == 1)
2664 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2665 }
2666 else {
2667 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2668 if (ok == 1)
2669 return bytes;
2670 }
2671 Py_DECREF(bytes);
2672
2673 err = ERR_get_error();
2674 errstr = ERR_reason_error_string(err);
2675 v = Py_BuildValue("(ks)", err, errstr);
2676 if (v != NULL) {
2677 PyErr_SetObject(PySSLErrorObject, v);
2678 Py_DECREF(v);
2679 }
2680 return NULL;
2681}
2682
2683static PyObject *
2684PySSL_RAND_bytes(PyObject *self, PyObject *args)
2685{
2686 int len;
2687 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2688 return NULL;
2689 return PySSL_RAND(len, 0);
2690}
2691
2692PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2693"RAND_bytes(n) -> bytes\n\
2694\n\
2695Generate n cryptographically strong pseudo-random bytes.");
2696
2697static PyObject *
2698PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2699{
2700 int len;
2701 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2702 return NULL;
2703 return PySSL_RAND(len, 1);
2704}
2705
2706PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2707"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2708\n\
2709Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2710generated are cryptographically strong.");
2711
2712static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002713PySSL_RAND_status(PyObject *self)
2714{
Christian Heimes217cfd12007-12-02 14:31:20 +00002715 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002716}
2717
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002718PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002719"RAND_status() -> 0 or 1\n\
2720\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002721Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2722It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2723using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002724
2725static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002726PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002727{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002728 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002729 int bytes;
2730
Jesus Ceac8754a12012-09-11 02:00:58 +02002731 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002732 PyUnicode_FSConverter, &path))
2733 return NULL;
2734
2735 bytes = RAND_egd(PyBytes_AsString(path));
2736 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002737 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002738 PyErr_SetString(PySSLErrorObject,
2739 "EGD connection failed or EGD did not return "
2740 "enough data to seed the PRNG");
2741 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002742 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002743 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002744}
2745
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002746PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002747"RAND_egd(path) -> bytes\n\
2748\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002749Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2750Returns number of bytes read. Raises SSLError if connection to EGD\n\
2751fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002752
2753#endif
2754
Bill Janssen40a0f662008-08-12 16:56:25 +00002755
2756
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002757/* List of functions exported by this module. */
2758
2759static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002760 {"_test_decode_cert", PySSL_test_decode_certificate,
2761 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002762#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002763 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2764 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002765 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2766 PySSL_RAND_bytes_doc},
2767 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2768 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002769 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002770 PySSL_RAND_egd_doc},
2771 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2772 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002773#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002774 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002775};
2776
2777
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002778#ifdef WITH_THREAD
2779
2780/* an implementation of OpenSSL threading operations in terms
2781 of the Python C thread library */
2782
2783static PyThread_type_lock *_ssl_locks = NULL;
2784
2785static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002786 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002787}
2788
Bill Janssen6e027db2007-11-15 22:23:56 +00002789static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002790 (int mode, int n, const char *file, int line) {
2791 /* this function is needed to perform locking on shared data
2792 structures. (Note that OpenSSL uses a number of global data
2793 structures that will be implicitly shared whenever multiple
2794 threads use OpenSSL.) Multi-threaded applications will
2795 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002796
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002797 locking_function() must be able to handle up to
2798 CRYPTO_num_locks() different mutex locks. It sets the n-th
2799 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002800
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002801 file and line are the file number of the function setting the
2802 lock. They can be useful for debugging.
2803 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002804
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002805 if ((_ssl_locks == NULL) ||
2806 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2807 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002808
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002809 if (mode & CRYPTO_LOCK) {
2810 PyThread_acquire_lock(_ssl_locks[n], 1);
2811 } else {
2812 PyThread_release_lock(_ssl_locks[n]);
2813 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002814}
2815
2816static int _setup_ssl_threads(void) {
2817
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002818 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002819
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002820 if (_ssl_locks == NULL) {
2821 _ssl_locks_count = CRYPTO_num_locks();
2822 _ssl_locks = (PyThread_type_lock *)
2823 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2824 if (_ssl_locks == NULL)
2825 return 0;
2826 memset(_ssl_locks, 0,
2827 sizeof(PyThread_type_lock) * _ssl_locks_count);
2828 for (i = 0; i < _ssl_locks_count; i++) {
2829 _ssl_locks[i] = PyThread_allocate_lock();
2830 if (_ssl_locks[i] == NULL) {
2831 unsigned int j;
2832 for (j = 0; j < i; j++) {
2833 PyThread_free_lock(_ssl_locks[j]);
2834 }
2835 free(_ssl_locks);
2836 return 0;
2837 }
2838 }
2839 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2840 CRYPTO_set_id_callback(_ssl_thread_id_function);
2841 }
2842 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002843}
2844
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002845#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002846
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002847PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002848"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002849for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002850
Martin v. Löwis1a214512008-06-11 05:26:20 +00002851
2852static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002853 PyModuleDef_HEAD_INIT,
2854 "_ssl",
2855 module_doc,
2856 -1,
2857 PySSL_methods,
2858 NULL,
2859 NULL,
2860 NULL,
2861 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002862};
2863
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002864
2865static void
2866parse_openssl_version(unsigned long libver,
2867 unsigned int *major, unsigned int *minor,
2868 unsigned int *fix, unsigned int *patch,
2869 unsigned int *status)
2870{
2871 *status = libver & 0xF;
2872 libver >>= 4;
2873 *patch = libver & 0xFF;
2874 libver >>= 8;
2875 *fix = libver & 0xFF;
2876 libver >>= 8;
2877 *minor = libver & 0xFF;
2878 libver >>= 8;
2879 *major = libver & 0xFF;
2880}
2881
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002882PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002883PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002884{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002885 PyObject *m, *d, *r;
2886 unsigned long libver;
2887 unsigned int major, minor, fix, patch, status;
2888 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002889 struct py_ssl_error_code *errcode;
2890 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002891
Antoine Pitrou152efa22010-05-16 18:19:27 +00002892 if (PyType_Ready(&PySSLContext_Type) < 0)
2893 return NULL;
2894 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002895 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002896
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002897 m = PyModule_Create(&_sslmodule);
2898 if (m == NULL)
2899 return NULL;
2900 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002901
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002902 /* Load _socket module and its C API */
2903 socket_api = PySocketModule_ImportModuleAndAPI();
2904 if (!socket_api)
2905 return NULL;
2906 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002907
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002908 /* Init OpenSSL */
2909 SSL_load_error_strings();
2910 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002911#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002912 /* note that this will start threading if not already started */
2913 if (!_setup_ssl_threads()) {
2914 return NULL;
2915 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002916#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002917 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002918
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002919 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002920 sslerror_type_slots[0].pfunc = PyExc_OSError;
2921 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002922 if (PySSLErrorObject == NULL)
2923 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002924
Antoine Pitrou41032a62011-10-27 23:56:55 +02002925 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2926 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2927 PySSLErrorObject, NULL);
2928 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2929 "ssl.SSLWantReadError", SSLWantReadError_doc,
2930 PySSLErrorObject, NULL);
2931 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2932 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2933 PySSLErrorObject, NULL);
2934 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2935 "ssl.SSLSyscallError", SSLSyscallError_doc,
2936 PySSLErrorObject, NULL);
2937 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2938 "ssl.SSLEOFError", SSLEOFError_doc,
2939 PySSLErrorObject, NULL);
2940 if (PySSLZeroReturnErrorObject == NULL
2941 || PySSLWantReadErrorObject == NULL
2942 || PySSLWantWriteErrorObject == NULL
2943 || PySSLSyscallErrorObject == NULL
2944 || PySSLEOFErrorObject == NULL)
2945 return NULL;
2946 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2947 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2948 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2949 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2950 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2951 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002952 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002953 if (PyDict_SetItemString(d, "_SSLContext",
2954 (PyObject *)&PySSLContext_Type) != 0)
2955 return NULL;
2956 if (PyDict_SetItemString(d, "_SSLSocket",
2957 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002958 return NULL;
2959 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2960 PY_SSL_ERROR_ZERO_RETURN);
2961 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2962 PY_SSL_ERROR_WANT_READ);
2963 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2964 PY_SSL_ERROR_WANT_WRITE);
2965 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2966 PY_SSL_ERROR_WANT_X509_LOOKUP);
2967 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2968 PY_SSL_ERROR_SYSCALL);
2969 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2970 PY_SSL_ERROR_SSL);
2971 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2972 PY_SSL_ERROR_WANT_CONNECT);
2973 /* non ssl.h errorcodes */
2974 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2975 PY_SSL_ERROR_EOF);
2976 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2977 PY_SSL_ERROR_INVALID_ERROR_CODE);
2978 /* cert requirements */
2979 PyModule_AddIntConstant(m, "CERT_NONE",
2980 PY_SSL_CERT_NONE);
2981 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2982 PY_SSL_CERT_OPTIONAL);
2983 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2984 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002985
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002986 /* Alert Descriptions from ssl.h */
2987 /* note RESERVED constants no longer intended for use have been removed */
2988 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
2989
2990#define ADD_AD_CONSTANT(s) \
2991 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
2992 SSL_AD_##s)
2993
2994 ADD_AD_CONSTANT(CLOSE_NOTIFY);
2995 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
2996 ADD_AD_CONSTANT(BAD_RECORD_MAC);
2997 ADD_AD_CONSTANT(RECORD_OVERFLOW);
2998 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
2999 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
3000 ADD_AD_CONSTANT(BAD_CERTIFICATE);
3001 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
3002 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
3003 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
3004 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
3005 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
3006 ADD_AD_CONSTANT(UNKNOWN_CA);
3007 ADD_AD_CONSTANT(ACCESS_DENIED);
3008 ADD_AD_CONSTANT(DECODE_ERROR);
3009 ADD_AD_CONSTANT(DECRYPT_ERROR);
3010 ADD_AD_CONSTANT(PROTOCOL_VERSION);
3011 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
3012 ADD_AD_CONSTANT(INTERNAL_ERROR);
3013 ADD_AD_CONSTANT(USER_CANCELLED);
3014 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003015 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003016#ifdef SSL_AD_UNSUPPORTED_EXTENSION
3017 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
3018#endif
3019#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
3020 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
3021#endif
3022#ifdef SSL_AD_UNRECOGNIZED_NAME
3023 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
3024#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003025#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
3026 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
3027#endif
3028#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
3029 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
3030#endif
3031#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
3032 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
3033#endif
3034
3035#undef ADD_AD_CONSTANT
3036
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003037 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02003038#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003039 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
3040 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02003041#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003042 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
3043 PY_SSL_VERSION_SSL3);
3044 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
3045 PY_SSL_VERSION_SSL23);
3046 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
3047 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003048#if HAVE_TLSv1_2
3049 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
3050 PY_SSL_VERSION_TLS1_1);
3051 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
3052 PY_SSL_VERSION_TLS1_2);
3053#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003054
Antoine Pitroub5218772010-05-21 09:56:06 +00003055 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01003056 PyModule_AddIntConstant(m, "OP_ALL",
3057 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00003058 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
3059 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
3060 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003061#if HAVE_TLSv1_2
3062 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
3063 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
3064#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01003065 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
3066 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003067 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003068#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003069 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003070#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003071#ifdef SSL_OP_NO_COMPRESSION
3072 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
3073 SSL_OP_NO_COMPRESSION);
3074#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00003075
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003076#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00003077 r = Py_True;
3078#else
3079 r = Py_False;
3080#endif
3081 Py_INCREF(r);
3082 PyModule_AddObject(m, "HAS_SNI", r);
3083
Antoine Pitroud6494802011-07-21 01:11:30 +02003084#if HAVE_OPENSSL_FINISHED
3085 r = Py_True;
3086#else
3087 r = Py_False;
3088#endif
3089 Py_INCREF(r);
3090 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
3091
Antoine Pitrou501da612011-12-21 09:27:41 +01003092#ifdef OPENSSL_NO_ECDH
3093 r = Py_False;
3094#else
3095 r = Py_True;
3096#endif
3097 Py_INCREF(r);
3098 PyModule_AddObject(m, "HAS_ECDH", r);
3099
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003100#ifdef OPENSSL_NPN_NEGOTIATED
3101 r = Py_True;
3102#else
3103 r = Py_False;
3104#endif
3105 Py_INCREF(r);
3106 PyModule_AddObject(m, "HAS_NPN", r);
3107
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003108 /* Mappings for error codes */
3109 err_codes_to_names = PyDict_New();
3110 err_names_to_codes = PyDict_New();
3111 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
3112 return NULL;
3113 errcode = error_codes;
3114 while (errcode->mnemonic != NULL) {
3115 PyObject *mnemo, *key;
3116 mnemo = PyUnicode_FromString(errcode->mnemonic);
3117 key = Py_BuildValue("ii", errcode->library, errcode->reason);
3118 if (mnemo == NULL || key == NULL)
3119 return NULL;
3120 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
3121 return NULL;
3122 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
3123 return NULL;
3124 Py_DECREF(key);
3125 Py_DECREF(mnemo);
3126 errcode++;
3127 }
3128 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
3129 return NULL;
3130 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
3131 return NULL;
3132
3133 lib_codes_to_names = PyDict_New();
3134 if (lib_codes_to_names == NULL)
3135 return NULL;
3136 libcode = library_codes;
3137 while (libcode->library != NULL) {
3138 PyObject *mnemo, *key;
3139 key = PyLong_FromLong(libcode->code);
3140 mnemo = PyUnicode_FromString(libcode->library);
3141 if (key == NULL || mnemo == NULL)
3142 return NULL;
3143 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
3144 return NULL;
3145 Py_DECREF(key);
3146 Py_DECREF(mnemo);
3147 libcode++;
3148 }
3149 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
3150 return NULL;
3151
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003152 /* OpenSSL version */
3153 /* SSLeay() gives us the version of the library linked against,
3154 which could be different from the headers version.
3155 */
3156 libver = SSLeay();
3157 r = PyLong_FromUnsignedLong(libver);
3158 if (r == NULL)
3159 return NULL;
3160 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
3161 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003162 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003163 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3164 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
3165 return NULL;
3166 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
3167 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
3168 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003169
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003170 libver = OPENSSL_VERSION_NUMBER;
3171 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
3172 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3173 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
3174 return NULL;
3175
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003176 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003177}