blob: 8212cd1aa4ea597ddfccf2a35a9dbac8b09e2a01 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
17#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000018
Thomas Wouters1b7f8912007-09-19 03:06:30 +000019#ifdef WITH_THREAD
20#include "pythread.h"
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020021#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
22 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
23#define PySSL_END_ALLOW_THREADS_S(save) \
24 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000025#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000026 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020027 PySSL_BEGIN_ALLOW_THREADS_S(_save);
28#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
29#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
30#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000031
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000032#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000033
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020034#define PySSL_BEGIN_ALLOW_THREADS_S(save)
35#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036#define PySSL_BEGIN_ALLOW_THREADS
37#define PySSL_BLOCK_THREADS
38#define PySSL_UNBLOCK_THREADS
39#define PySSL_END_ALLOW_THREADS
40
41#endif
42
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000043enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000044 /* these mirror ssl.h */
45 PY_SSL_ERROR_NONE,
46 PY_SSL_ERROR_SSL,
47 PY_SSL_ERROR_WANT_READ,
48 PY_SSL_ERROR_WANT_WRITE,
49 PY_SSL_ERROR_WANT_X509_LOOKUP,
50 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
51 PY_SSL_ERROR_ZERO_RETURN,
52 PY_SSL_ERROR_WANT_CONNECT,
53 /* start of non ssl.h errorcodes */
54 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
55 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
56 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +000057};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000058
Thomas Woutersed03b412007-08-28 21:37:11 +000059enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000060 PY_SSL_CLIENT,
61 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +000062};
63
64enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000065 PY_SSL_CERT_NONE,
66 PY_SSL_CERT_OPTIONAL,
67 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +000068};
69
70enum py_ssl_version {
Victor Stinner3de49192011-05-09 00:42:58 +020071#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000072 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +020073#endif
74 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000075 PY_SSL_VERSION_SSL23,
76 PY_SSL_VERSION_TLS1
Thomas Woutersed03b412007-08-28 21:37:11 +000077};
78
Antoine Pitrou3b36fb12012-06-22 21:11:52 +020079struct py_ssl_error_code {
80 const char *mnemonic;
81 int library, reason;
82};
83
84struct py_ssl_library_code {
85 const char *library;
86 int code;
87};
88
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000089/* Include symbols from _socket module */
90#include "socketmodule.h"
91
Benjamin Petersonb173f782009-05-05 22:31:58 +000092static PySocketModule_APIObject PySocketModule;
93
Thomas Woutersed03b412007-08-28 21:37:11 +000094#if defined(HAVE_POLL_H)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000095#include <poll.h>
96#elif defined(HAVE_SYS_POLL_H)
97#include <sys/poll.h>
98#endif
99
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000100/* Include OpenSSL header files */
101#include "openssl/rsa.h"
102#include "openssl/crypto.h"
103#include "openssl/x509.h"
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000104#include "openssl/x509v3.h"
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000105#include "openssl/pem.h"
106#include "openssl/ssl.h"
107#include "openssl/err.h"
108#include "openssl/rand.h"
109
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200110/* Include generated data (error codes) */
111#include "_ssl_data.h"
112
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000113/* SSL error object */
114static PyObject *PySSLErrorObject;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200115static PyObject *PySSLZeroReturnErrorObject;
116static PyObject *PySSLWantReadErrorObject;
117static PyObject *PySSLWantWriteErrorObject;
118static PyObject *PySSLSyscallErrorObject;
119static PyObject *PySSLEOFErrorObject;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000120
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200121/* Error mappings */
122static PyObject *err_codes_to_names;
123static PyObject *err_names_to_codes;
124static PyObject *lib_codes_to_names;
125
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000126#ifdef WITH_THREAD
127
128/* serves as a flag to see whether we've initialized the SSL thread support. */
129/* 0 means no, greater than 0 means yes */
130
131static unsigned int _ssl_locks_count = 0;
132
133#endif /* def WITH_THREAD */
134
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000135/* SSL socket object */
136
137#define X509_NAME_MAXLEN 256
138
139/* RAND_* APIs got added to OpenSSL in 0.9.5 */
140#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
141# define HAVE_OPENSSL_RAND 1
142#else
143# undef HAVE_OPENSSL_RAND
144#endif
145
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000146/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
147 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
148 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
149#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000150# define HAVE_SSL_CTX_CLEAR_OPTIONS
151#else
152# undef HAVE_SSL_CTX_CLEAR_OPTIONS
153#endif
154
Antoine Pitroud6494802011-07-21 01:11:30 +0200155/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
156 * older SSL, but let's be safe */
157#define PySSL_CB_MAXLEN 128
158
159/* SSL_get_finished got added to OpenSSL in 0.9.5 */
160#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
161# define HAVE_OPENSSL_FINISHED 1
162#else
163# define HAVE_OPENSSL_FINISHED 0
164#endif
165
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100166/* ECDH support got added to OpenSSL in 0.9.8 */
167#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
168# define OPENSSL_NO_ECDH
169#endif
170
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100171/* compression support got added to OpenSSL in 0.9.8 */
172#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
173# define OPENSSL_NO_COMP
174#endif
175
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100176
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000177typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000178 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000179 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100180#ifdef OPENSSL_NPN_NEGOTIATED
181 char *npn_protocols;
182 int npn_protocols_len;
183#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100184#ifndef OPENSSL_NO_TLSEXT
185 PyObject *set_hostname;
186#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000187} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000188
Antoine Pitrou152efa22010-05-16 18:19:27 +0000189typedef struct {
190 PyObject_HEAD
191 PyObject *Socket; /* weakref to socket on which we're layered */
192 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100193 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000194 X509 *peer_cert;
195 int shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200196 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000197} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000198
Antoine Pitrou152efa22010-05-16 18:19:27 +0000199static PyTypeObject PySSLContext_Type;
200static PyTypeObject PySSLSocket_Type;
201
202static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
203static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000204static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000205 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000206static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
207static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000208
Antoine Pitrou152efa22010-05-16 18:19:27 +0000209#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
210#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000211
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000212typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000213 SOCKET_IS_NONBLOCKING,
214 SOCKET_IS_BLOCKING,
215 SOCKET_HAS_TIMED_OUT,
216 SOCKET_HAS_BEEN_CLOSED,
217 SOCKET_TOO_LARGE_FOR_SELECT,
218 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000219} timeout_state;
220
Thomas Woutersed03b412007-08-28 21:37:11 +0000221/* Wrap error strings with filename and line # */
222#define STRINGIFY1(x) #x
223#define STRINGIFY2(x) STRINGIFY1(x)
224#define ERRSTR1(x,y,z) (x ":" y ": " z)
225#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
226
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200227
228/*
229 * SSL errors.
230 */
231
232PyDoc_STRVAR(SSLError_doc,
233"An error occurred in the SSL implementation.");
234
235PyDoc_STRVAR(SSLZeroReturnError_doc,
236"SSL/TLS session closed cleanly.");
237
238PyDoc_STRVAR(SSLWantReadError_doc,
239"Non-blocking SSL socket needs to read more data\n"
240"before the requested operation can be completed.");
241
242PyDoc_STRVAR(SSLWantWriteError_doc,
243"Non-blocking SSL socket needs to write more data\n"
244"before the requested operation can be completed.");
245
246PyDoc_STRVAR(SSLSyscallError_doc,
247"System error when attempting SSL operation.");
248
249PyDoc_STRVAR(SSLEOFError_doc,
250"SSL/TLS connection terminated abruptly.");
251
252static PyObject *
253SSLError_str(PyOSErrorObject *self)
254{
255 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
256 Py_INCREF(self->strerror);
257 return self->strerror;
258 }
259 else
260 return PyObject_Str(self->args);
261}
262
263static PyType_Slot sslerror_type_slots[] = {
264 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
265 {Py_tp_doc, SSLError_doc},
266 {Py_tp_str, SSLError_str},
267 {0, 0},
268};
269
270static PyType_Spec sslerror_type_spec = {
271 "ssl.SSLError",
272 sizeof(PyOSErrorObject),
273 0,
274 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
275 sslerror_type_slots
276};
277
278static void
279fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
280 int lineno, unsigned long errcode)
281{
282 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
283 PyObject *init_value, *msg, *key;
284 _Py_IDENTIFIER(reason);
285 _Py_IDENTIFIER(library);
286
287 if (errcode != 0) {
288 int lib, reason;
289
290 lib = ERR_GET_LIB(errcode);
291 reason = ERR_GET_REASON(errcode);
292 key = Py_BuildValue("ii", lib, reason);
293 if (key == NULL)
294 goto fail;
295 reason_obj = PyDict_GetItem(err_codes_to_names, key);
296 Py_DECREF(key);
297 if (reason_obj == NULL) {
298 /* XXX if reason < 100, it might reflect a library number (!!) */
299 PyErr_Clear();
300 }
301 key = PyLong_FromLong(lib);
302 if (key == NULL)
303 goto fail;
304 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
305 Py_DECREF(key);
306 if (lib_obj == NULL) {
307 PyErr_Clear();
308 }
309 if (errstr == NULL)
310 errstr = ERR_reason_error_string(errcode);
311 }
312 if (errstr == NULL)
313 errstr = "unknown error";
314
315 if (reason_obj && lib_obj)
316 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
317 lib_obj, reason_obj, errstr, lineno);
318 else if (lib_obj)
319 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
320 lib_obj, errstr, lineno);
321 else
322 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
323
324 if (msg == NULL)
325 goto fail;
326 init_value = Py_BuildValue("iN", ssl_errno, msg);
327 err_value = PyObject_CallObject(type, init_value);
328 Py_DECREF(init_value);
329 if (err_value == NULL)
330 goto fail;
331 if (reason_obj == NULL)
332 reason_obj = Py_None;
333 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
334 goto fail;
335 if (lib_obj == NULL)
336 lib_obj = Py_None;
337 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
338 goto fail;
339 PyErr_SetObject(type, err_value);
340fail:
341 Py_XDECREF(err_value);
342}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000343
344static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000345PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000346{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200347 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200348 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000349 int err;
350 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200351 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000352
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000353 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200354 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000355
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000356 if (obj->ssl != NULL) {
357 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000358
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000359 switch (err) {
360 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200361 errstr = "TLS/SSL connection has been closed (EOF)";
362 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000363 p = PY_SSL_ERROR_ZERO_RETURN;
364 break;
365 case SSL_ERROR_WANT_READ:
366 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200367 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000368 p = PY_SSL_ERROR_WANT_READ;
369 break;
370 case SSL_ERROR_WANT_WRITE:
371 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200372 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000373 errstr = "The operation did not complete (write)";
374 break;
375 case SSL_ERROR_WANT_X509_LOOKUP:
376 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000377 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000378 break;
379 case SSL_ERROR_WANT_CONNECT:
380 p = PY_SSL_ERROR_WANT_CONNECT;
381 errstr = "The operation did not complete (connect)";
382 break;
383 case SSL_ERROR_SYSCALL:
384 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000385 if (e == 0) {
386 PySocketSockObject *s
387 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
388 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000389 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200390 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000391 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000392 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000393 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000394 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000395 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200396 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000397 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200398 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000399 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000400 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200401 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000402 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000403 }
404 } else {
405 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000406 }
407 break;
408 }
409 case SSL_ERROR_SSL:
410 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000411 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200412 if (e == 0)
413 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000414 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000415 break;
416 }
417 default:
418 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
419 errstr = "Invalid error code";
420 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000421 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200422 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000423 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000424 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000425}
426
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000427static PyObject *
428_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
429
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200430 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000431 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200432 else
433 errcode = 0;
434 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000435 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000436 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000437}
438
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200439/*
440 * SSL objects
441 */
442
Antoine Pitrou152efa22010-05-16 18:19:27 +0000443static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100444newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000445 enum py_ssl_server_or_client socket_type,
446 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000447{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000448 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100449 SSL_CTX *ctx = sslctx->ctx;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000450
Antoine Pitrou152efa22010-05-16 18:19:27 +0000451 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000452 if (self == NULL)
453 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000454
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000455 self->peer_cert = NULL;
456 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000457 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100458 self->ctx = sslctx;
459 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000460
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000461 /* Make sure the SSL error state is initialized */
462 (void) ERR_get_state();
463 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000464
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000465 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000466 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000467 PySSL_END_ALLOW_THREADS
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100468 SSL_set_app_data(self->ssl,self);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000469 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000470#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000471 SSL_set_mode(self->ssl, SSL_MODE_AUTO_RETRY);
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000472#endif
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000473
Antoine Pitroud5323212010-10-22 18:19:07 +0000474#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
475 if (server_hostname != NULL)
476 SSL_set_tlsext_host_name(self->ssl, server_hostname);
477#endif
478
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000479 /* If the socket is in non-blocking mode or timeout mode, set the BIO
480 * to non-blocking mode (blocking is the default)
481 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000482 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000483 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
484 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
485 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000486
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000487 PySSL_BEGIN_ALLOW_THREADS
488 if (socket_type == PY_SSL_CLIENT)
489 SSL_set_connect_state(self->ssl);
490 else
491 SSL_set_accept_state(self->ssl);
492 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000493
Antoine Pitroud6494802011-07-21 01:11:30 +0200494 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000495 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000496 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000497}
498
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000499/* SSL object methods */
500
Antoine Pitrou152efa22010-05-16 18:19:27 +0000501static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000502{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000503 int ret;
504 int err;
505 int sockstate, nonblocking;
506 PySocketSockObject *sock
507 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000508
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000509 if (((PyObject*)sock) == Py_None) {
510 _setSSLError("Underlying socket connection gone",
511 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
512 return NULL;
513 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000514 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000515
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000516 /* just in case the blocking state of the socket has been changed */
517 nonblocking = (sock->sock_timeout >= 0.0);
518 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
519 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000520
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000521 /* Actually negotiate SSL connection */
522 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000523 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000524 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000525 ret = SSL_do_handshake(self->ssl);
526 err = SSL_get_error(self->ssl, ret);
527 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000528 if (PyErr_CheckSignals())
529 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000530 if (err == SSL_ERROR_WANT_READ) {
531 sockstate = check_socket_and_wait_for_timeout(sock, 0);
532 } else if (err == SSL_ERROR_WANT_WRITE) {
533 sockstate = check_socket_and_wait_for_timeout(sock, 1);
534 } else {
535 sockstate = SOCKET_OPERATION_OK;
536 }
537 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000538 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000539 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000540 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000541 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
542 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000543 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000544 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000545 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
546 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000547 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000548 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000549 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
550 break;
551 }
552 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000553 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000554 if (ret < 1)
555 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000556
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000557 if (self->peer_cert)
558 X509_free (self->peer_cert);
559 PySSL_BEGIN_ALLOW_THREADS
560 self->peer_cert = SSL_get_peer_certificate(self->ssl);
561 PySSL_END_ALLOW_THREADS
562
563 Py_INCREF(Py_None);
564 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000565
566error:
567 Py_DECREF(sock);
568 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000569}
570
Thomas Woutersed03b412007-08-28 21:37:11 +0000571static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000572_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000573
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000574 char namebuf[X509_NAME_MAXLEN];
575 int buflen;
576 PyObject *name_obj;
577 PyObject *value_obj;
578 PyObject *attr;
579 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000580
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000581 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
582 if (buflen < 0) {
583 _setSSLError(NULL, 0, __FILE__, __LINE__);
584 goto fail;
585 }
586 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
587 if (name_obj == NULL)
588 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000589
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
591 if (buflen < 0) {
592 _setSSLError(NULL, 0, __FILE__, __LINE__);
593 Py_DECREF(name_obj);
594 goto fail;
595 }
596 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000597 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000598 OPENSSL_free(valuebuf);
599 if (value_obj == NULL) {
600 Py_DECREF(name_obj);
601 goto fail;
602 }
603 attr = PyTuple_New(2);
604 if (attr == NULL) {
605 Py_DECREF(name_obj);
606 Py_DECREF(value_obj);
607 goto fail;
608 }
609 PyTuple_SET_ITEM(attr, 0, name_obj);
610 PyTuple_SET_ITEM(attr, 1, value_obj);
611 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000612
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000613 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000614 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000615}
616
617static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000618_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000619{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000620 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
621 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
622 PyObject *rdnt;
623 PyObject *attr = NULL; /* tuple to hold an attribute */
624 int entry_count = X509_NAME_entry_count(xname);
625 X509_NAME_ENTRY *entry;
626 ASN1_OBJECT *name;
627 ASN1_STRING *value;
628 int index_counter;
629 int rdn_level = -1;
630 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000631
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000632 dn = PyList_New(0);
633 if (dn == NULL)
634 return NULL;
635 /* now create another tuple to hold the top-level RDN */
636 rdn = PyList_New(0);
637 if (rdn == NULL)
638 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000639
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000640 for (index_counter = 0;
641 index_counter < entry_count;
642 index_counter++)
643 {
644 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000645
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000646 /* check to see if we've gotten to a new RDN */
647 if (rdn_level >= 0) {
648 if (rdn_level != entry->set) {
649 /* yes, new RDN */
650 /* add old RDN to DN */
651 rdnt = PyList_AsTuple(rdn);
652 Py_DECREF(rdn);
653 if (rdnt == NULL)
654 goto fail0;
655 retcode = PyList_Append(dn, rdnt);
656 Py_DECREF(rdnt);
657 if (retcode < 0)
658 goto fail0;
659 /* create new RDN */
660 rdn = PyList_New(0);
661 if (rdn == NULL)
662 goto fail0;
663 }
664 }
665 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000666
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000667 /* now add this attribute to the current RDN */
668 name = X509_NAME_ENTRY_get_object(entry);
669 value = X509_NAME_ENTRY_get_data(entry);
670 attr = _create_tuple_for_attribute(name, value);
671 /*
672 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
673 entry->set,
674 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
675 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
676 */
677 if (attr == NULL)
678 goto fail1;
679 retcode = PyList_Append(rdn, attr);
680 Py_DECREF(attr);
681 if (retcode < 0)
682 goto fail1;
683 }
684 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100685 if (rdn != NULL) {
686 if (PyList_GET_SIZE(rdn) > 0) {
687 rdnt = PyList_AsTuple(rdn);
688 Py_DECREF(rdn);
689 if (rdnt == NULL)
690 goto fail0;
691 retcode = PyList_Append(dn, rdnt);
692 Py_DECREF(rdnt);
693 if (retcode < 0)
694 goto fail0;
695 }
696 else {
697 Py_DECREF(rdn);
698 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000699 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000700
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000701 /* convert list to tuple */
702 rdnt = PyList_AsTuple(dn);
703 Py_DECREF(dn);
704 if (rdnt == NULL)
705 return NULL;
706 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000707
708 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000709 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000710
711 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000712 Py_XDECREF(dn);
713 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000714}
715
716static PyObject *
717_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000718
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000719 /* this code follows the procedure outlined in
720 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
721 function to extract the STACK_OF(GENERAL_NAME),
722 then iterates through the stack to add the
723 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000724
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000725 int i, j;
726 PyObject *peer_alt_names = Py_None;
727 PyObject *v, *t;
728 X509_EXTENSION *ext = NULL;
729 GENERAL_NAMES *names = NULL;
730 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000731 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000732 BIO *biobuf = NULL;
733 char buf[2048];
734 char *vptr;
735 int len;
736 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000737#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000738 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000739#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000740 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000741#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000742
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 if (certificate == NULL)
744 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000745
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000746 /* get a memory buffer */
747 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000748
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200749 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000750 while ((i = X509_get_ext_by_NID(
751 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000752
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000753 if (peer_alt_names == Py_None) {
754 peer_alt_names = PyList_New(0);
755 if (peer_alt_names == NULL)
756 goto fail;
757 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000758
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000759 /* now decode the altName */
760 ext = X509_get_ext(certificate, i);
761 if(!(method = X509V3_EXT_get(ext))) {
762 PyErr_SetString
763 (PySSLErrorObject,
764 ERRSTR("No method for internalizing subjectAltName!"));
765 goto fail;
766 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000767
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000768 p = ext->value->data;
769 if (method->it)
770 names = (GENERAL_NAMES*)
771 (ASN1_item_d2i(NULL,
772 &p,
773 ext->value->length,
774 ASN1_ITEM_ptr(method->it)));
775 else
776 names = (GENERAL_NAMES*)
777 (method->d2i(NULL,
778 &p,
779 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000780
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000781 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000782
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 /* get a rendering of each name in the set of names */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000784
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 name = sk_GENERAL_NAME_value(names, j);
786 if (name->type == GEN_DIRNAME) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000787
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000788 /* we special-case DirName as a tuple of
789 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000790
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000791 t = PyTuple_New(2);
792 if (t == NULL) {
793 goto fail;
794 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000795
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 v = PyUnicode_FromString("DirName");
797 if (v == NULL) {
798 Py_DECREF(t);
799 goto fail;
800 }
801 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 v = _create_tuple_for_X509_NAME (name->d.dirn);
804 if (v == NULL) {
805 Py_DECREF(t);
806 goto fail;
807 }
808 PyTuple_SET_ITEM(t, 1, v);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000809
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000810 } else {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000811
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 /* for everything else, we use the OpenSSL print form */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000813
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000814 (void) BIO_reset(biobuf);
815 GENERAL_NAME_print(biobuf, name);
816 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
817 if (len < 0) {
818 _setSSLError(NULL, 0, __FILE__, __LINE__);
819 goto fail;
820 }
821 vptr = strchr(buf, ':');
822 if (vptr == NULL)
823 goto fail;
824 t = PyTuple_New(2);
825 if (t == NULL)
826 goto fail;
827 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
828 if (v == NULL) {
829 Py_DECREF(t);
830 goto fail;
831 }
832 PyTuple_SET_ITEM(t, 0, v);
833 v = PyUnicode_FromStringAndSize((vptr + 1),
834 (len - (vptr - buf + 1)));
835 if (v == NULL) {
836 Py_DECREF(t);
837 goto fail;
838 }
839 PyTuple_SET_ITEM(t, 1, v);
840 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000841
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000842 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000843
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000844 if (PyList_Append(peer_alt_names, t) < 0) {
845 Py_DECREF(t);
846 goto fail;
847 }
848 Py_DECREF(t);
849 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100850 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000851 }
852 BIO_free(biobuf);
853 if (peer_alt_names != Py_None) {
854 v = PyList_AsTuple(peer_alt_names);
855 Py_DECREF(peer_alt_names);
856 return v;
857 } else {
858 return peer_alt_names;
859 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000860
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000861
862 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000863 if (biobuf != NULL)
864 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000865
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000866 if (peer_alt_names != Py_None) {
867 Py_XDECREF(peer_alt_names);
868 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000869
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000870 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000871}
872
873static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000874_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000875
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000876 PyObject *retval = NULL;
877 BIO *biobuf = NULL;
878 PyObject *peer;
879 PyObject *peer_alt_names = NULL;
880 PyObject *issuer;
881 PyObject *version;
882 PyObject *sn_obj;
883 ASN1_INTEGER *serialNumber;
884 char buf[2048];
885 int len;
886 ASN1_TIME *notBefore, *notAfter;
887 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000888
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000889 retval = PyDict_New();
890 if (retval == NULL)
891 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000892
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000893 peer = _create_tuple_for_X509_NAME(
894 X509_get_subject_name(certificate));
895 if (peer == NULL)
896 goto fail0;
897 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
898 Py_DECREF(peer);
899 goto fail0;
900 }
901 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000902
Antoine Pitroufb046912010-11-09 20:21:19 +0000903 issuer = _create_tuple_for_X509_NAME(
904 X509_get_issuer_name(certificate));
905 if (issuer == NULL)
906 goto fail0;
907 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000908 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000909 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000910 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000911 Py_DECREF(issuer);
912
913 version = PyLong_FromLong(X509_get_version(certificate) + 1);
914 if (PyDict_SetItemString(retval, "version", version) < 0) {
915 Py_DECREF(version);
916 goto fail0;
917 }
918 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +0000919
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000920 /* get a memory buffer */
921 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +0000922
Antoine Pitroufb046912010-11-09 20:21:19 +0000923 (void) BIO_reset(biobuf);
924 serialNumber = X509_get_serialNumber(certificate);
925 /* should not exceed 20 octets, 160 bits, so buf is big enough */
926 i2a_ASN1_INTEGER(biobuf, serialNumber);
927 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
928 if (len < 0) {
929 _setSSLError(NULL, 0, __FILE__, __LINE__);
930 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000932 sn_obj = PyUnicode_FromStringAndSize(buf, len);
933 if (sn_obj == NULL)
934 goto fail1;
935 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
936 Py_DECREF(sn_obj);
937 goto fail1;
938 }
939 Py_DECREF(sn_obj);
940
941 (void) BIO_reset(biobuf);
942 notBefore = X509_get_notBefore(certificate);
943 ASN1_TIME_print(biobuf, notBefore);
944 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
945 if (len < 0) {
946 _setSSLError(NULL, 0, __FILE__, __LINE__);
947 goto fail1;
948 }
949 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
950 if (pnotBefore == NULL)
951 goto fail1;
952 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
953 Py_DECREF(pnotBefore);
954 goto fail1;
955 }
956 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +0000957
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000958 (void) BIO_reset(biobuf);
959 notAfter = X509_get_notAfter(certificate);
960 ASN1_TIME_print(biobuf, notAfter);
961 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
962 if (len < 0) {
963 _setSSLError(NULL, 0, __FILE__, __LINE__);
964 goto fail1;
965 }
966 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
967 if (pnotAfter == NULL)
968 goto fail1;
969 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
970 Py_DECREF(pnotAfter);
971 goto fail1;
972 }
973 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000974
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000975 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000976
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000977 peer_alt_names = _get_peer_alt_names(certificate);
978 if (peer_alt_names == NULL)
979 goto fail1;
980 else if (peer_alt_names != Py_None) {
981 if (PyDict_SetItemString(retval, "subjectAltName",
982 peer_alt_names) < 0) {
983 Py_DECREF(peer_alt_names);
984 goto fail1;
985 }
986 Py_DECREF(peer_alt_names);
987 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000988
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000989 BIO_free(biobuf);
990 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +0000991
992 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000993 if (biobuf != NULL)
994 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +0000995 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000996 Py_XDECREF(retval);
997 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000998}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000999
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001000
1001static PyObject *
1002PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1003
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001004 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001005 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001006 X509 *x=NULL;
1007 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001008
Antoine Pitroufb046912010-11-09 20:21:19 +00001009 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1010 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001011 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001012
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001013 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1014 PyErr_SetString(PySSLErrorObject,
1015 "Can't malloc memory to read file");
1016 goto fail0;
1017 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001018
Victor Stinner3800e1e2010-05-16 21:23:48 +00001019 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001020 PyErr_SetString(PySSLErrorObject,
1021 "Can't open file");
1022 goto fail0;
1023 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001024
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001025 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1026 if (x == NULL) {
1027 PyErr_SetString(PySSLErrorObject,
1028 "Error decoding PEM-encoded file");
1029 goto fail0;
1030 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001031
Antoine Pitroufb046912010-11-09 20:21:19 +00001032 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001033 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001034
1035 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001036 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001037 if (cert != NULL) BIO_free(cert);
1038 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001039}
1040
1041
1042static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001043PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001044{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001045 PyObject *retval = NULL;
1046 int len;
1047 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001048 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001049
Antoine Pitrou721738f2012-08-15 23:20:39 +02001050 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001051 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001052
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001053 if (!self->peer_cert)
1054 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001055
Antoine Pitrou721738f2012-08-15 23:20:39 +02001056 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 /* return cert in DER-encoded format */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001058
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 unsigned char *bytes_buf = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001060
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001061 bytes_buf = NULL;
1062 len = i2d_X509(self->peer_cert, &bytes_buf);
1063 if (len < 0) {
1064 PySSL_SetError(self, len, __FILE__, __LINE__);
1065 return NULL;
1066 }
1067 /* this is actually an immutable bytes sequence */
1068 retval = PyBytes_FromStringAndSize
1069 ((const char *) bytes_buf, len);
1070 OPENSSL_free(bytes_buf);
1071 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001072
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001073 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001074 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001075 if ((verification & SSL_VERIFY_PEER) == 0)
1076 return PyDict_New();
1077 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001078 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001079 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001080}
1081
1082PyDoc_STRVAR(PySSL_peercert_doc,
1083"peer_certificate([der=False]) -> certificate\n\
1084\n\
1085Returns the certificate for the peer. If no certificate was provided,\n\
1086returns None. If a certificate was provided, but not validated, returns\n\
1087an empty dictionary. Otherwise returns a dict containing information\n\
1088about the peer certificate.\n\
1089\n\
1090If the optional argument is True, returns a DER-encoded copy of the\n\
1091peer certificate, or None if no certificate was provided. This will\n\
1092return the certificate even if it wasn't validated.");
1093
Antoine Pitrou152efa22010-05-16 18:19:27 +00001094static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001095
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001096 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001097 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001098 char *cipher_name;
1099 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001100
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001102 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 current = SSL_get_current_cipher(self->ssl);
1104 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001105 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001106
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 retval = PyTuple_New(3);
1108 if (retval == NULL)
1109 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001110
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 cipher_name = (char *) SSL_CIPHER_get_name(current);
1112 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001113 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 PyTuple_SET_ITEM(retval, 0, Py_None);
1115 } else {
1116 v = PyUnicode_FromString(cipher_name);
1117 if (v == NULL)
1118 goto fail0;
1119 PyTuple_SET_ITEM(retval, 0, v);
1120 }
1121 cipher_protocol = SSL_CIPHER_get_version(current);
1122 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001123 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001124 PyTuple_SET_ITEM(retval, 1, Py_None);
1125 } else {
1126 v = PyUnicode_FromString(cipher_protocol);
1127 if (v == NULL)
1128 goto fail0;
1129 PyTuple_SET_ITEM(retval, 1, v);
1130 }
1131 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1132 if (v == NULL)
1133 goto fail0;
1134 PyTuple_SET_ITEM(retval, 2, v);
1135 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001136
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001137 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001138 Py_DECREF(retval);
1139 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001140}
1141
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001142#ifdef OPENSSL_NPN_NEGOTIATED
1143static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1144 const unsigned char *out;
1145 unsigned int outlen;
1146
1147 SSL_get0_next_proto_negotiated(self->ssl,
1148 &out, &outlen);
1149
1150 if (out == NULL)
1151 Py_RETURN_NONE;
1152 return PyUnicode_FromStringAndSize((char *) out, outlen);
1153}
1154#endif
1155
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001156static PyObject *PySSL_compression(PySSLSocket *self) {
1157#ifdef OPENSSL_NO_COMP
1158 Py_RETURN_NONE;
1159#else
1160 const COMP_METHOD *comp_method;
1161 const char *short_name;
1162
1163 if (self->ssl == NULL)
1164 Py_RETURN_NONE;
1165 comp_method = SSL_get_current_compression(self->ssl);
1166 if (comp_method == NULL || comp_method->type == NID_undef)
1167 Py_RETURN_NONE;
1168 short_name = OBJ_nid2sn(comp_method->type);
1169 if (short_name == NULL)
1170 Py_RETURN_NONE;
1171 return PyUnicode_DecodeFSDefault(short_name);
1172#endif
1173}
1174
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001175static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1176 Py_INCREF(self->ctx);
1177 return self->ctx;
1178}
1179
1180static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1181 void *closure) {
1182
1183 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
1184
1185 Py_INCREF(value);
1186 Py_DECREF(self->ctx);
1187 self->ctx = (PySSLContext *) value;
1188 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
1189 } else {
1190 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1191 return -1;
1192 }
1193
1194 return 0;
1195}
1196
1197PyDoc_STRVAR(PySSL_set_context_doc,
1198"_setter_context(ctx)\n\
1199\
1200This changes the context associated with the SSLSocket. This is typically\n\
1201used from within a callback function set by the set_servername_callback\n\
1202on the SSLContext to change the certificate information associated with the\n\
1203SSLSocket before the cryptographic exchange handshake messages\n");
1204
1205
1206
Antoine Pitrou152efa22010-05-16 18:19:27 +00001207static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001208{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001209 if (self->peer_cert) /* Possible not to have one? */
1210 X509_free (self->peer_cert);
1211 if (self->ssl)
1212 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001213 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001214 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001215 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001216}
1217
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001218/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001219 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001220 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001221 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001222
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001223static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001224check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001225{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001226 fd_set fds;
1227 struct timeval tv;
1228 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001229
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001230 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1231 if (s->sock_timeout < 0.0)
1232 return SOCKET_IS_BLOCKING;
1233 else if (s->sock_timeout == 0.0)
1234 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001235
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001236 /* Guard against closed socket */
1237 if (s->sock_fd < 0)
1238 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001239
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001240 /* Prefer poll, if available, since you can poll() any fd
1241 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001242#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 {
1244 struct pollfd pollfd;
1245 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001246
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001247 pollfd.fd = s->sock_fd;
1248 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001249
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001250 /* s->sock_timeout is in seconds, timeout in ms */
1251 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1252 PySSL_BEGIN_ALLOW_THREADS
1253 rc = poll(&pollfd, 1, timeout);
1254 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001255
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001256 goto normal_return;
1257 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001258#endif
1259
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001260 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001261 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001262 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001263
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001264 /* Construct the arguments to select */
1265 tv.tv_sec = (int)s->sock_timeout;
1266 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1267 FD_ZERO(&fds);
1268 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001269
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001270 /* See if the socket is ready */
1271 PySSL_BEGIN_ALLOW_THREADS
1272 if (writing)
1273 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1274 else
1275 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1276 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001277
Bill Janssen6e027db2007-11-15 22:23:56 +00001278#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001279normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001280#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1282 (when we are able to write or when there's something to read) */
1283 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001284}
1285
Antoine Pitrou152efa22010-05-16 18:19:27 +00001286static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001287{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 Py_buffer buf;
1289 int len;
1290 int sockstate;
1291 int err;
1292 int nonblocking;
1293 PySocketSockObject *sock
1294 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001295
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001296 if (((PyObject*)sock) == Py_None) {
1297 _setSSLError("Underlying socket connection gone",
1298 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1299 return NULL;
1300 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001301 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001302
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001303 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1304 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001305 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001306 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001307
1308 /* just in case the blocking state of the socket has been changed */
1309 nonblocking = (sock->sock_timeout >= 0.0);
1310 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1311 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1312
1313 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1314 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001315 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001316 "The write operation timed out");
1317 goto error;
1318 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1319 PyErr_SetString(PySSLErrorObject,
1320 "Underlying socket has been closed.");
1321 goto error;
1322 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1323 PyErr_SetString(PySSLErrorObject,
1324 "Underlying socket too large for select().");
1325 goto error;
1326 }
1327 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001328 PySSL_BEGIN_ALLOW_THREADS
1329 len = SSL_write(self->ssl, buf.buf, buf.len);
1330 err = SSL_get_error(self->ssl, len);
1331 PySSL_END_ALLOW_THREADS
1332 if (PyErr_CheckSignals()) {
1333 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001334 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001335 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001336 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001337 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001338 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001339 } else {
1340 sockstate = SOCKET_OPERATION_OK;
1341 }
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_IS_NONBLOCKING) {
1351 break;
1352 }
1353 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001354
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001355 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001356 PyBuffer_Release(&buf);
1357 if (len > 0)
1358 return PyLong_FromLong(len);
1359 else
1360 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001361
1362error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001363 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 PyBuffer_Release(&buf);
1365 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001366}
1367
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001368PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001369"write(s) -> len\n\
1370\n\
1371Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001372of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001373
Antoine Pitrou152efa22010-05-16 18:19:27 +00001374static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001375{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001376 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001377
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 PySSL_BEGIN_ALLOW_THREADS
1379 count = SSL_pending(self->ssl);
1380 PySSL_END_ALLOW_THREADS
1381 if (count < 0)
1382 return PySSL_SetError(self, count, __FILE__, __LINE__);
1383 else
1384 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001385}
1386
1387PyDoc_STRVAR(PySSL_SSLpending_doc,
1388"pending() -> count\n\
1389\n\
1390Returns the number of already decrypted bytes available for read,\n\
1391pending on the connection.\n");
1392
Antoine Pitrou152efa22010-05-16 18:19:27 +00001393static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001394{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001395 PyObject *dest = NULL;
1396 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001398 int len, count;
1399 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001400 int sockstate;
1401 int err;
1402 int nonblocking;
1403 PySocketSockObject *sock
1404 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001405
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001406 if (((PyObject*)sock) == Py_None) {
1407 _setSSLError("Underlying socket connection gone",
1408 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1409 return NULL;
1410 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001411 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001412
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001413 buf.obj = NULL;
1414 buf.buf = NULL;
1415 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001416 goto error;
1417
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001418 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1419 dest = PyBytes_FromStringAndSize(NULL, len);
1420 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001421 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001422 mem = PyBytes_AS_STRING(dest);
1423 }
1424 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001425 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001426 mem = buf.buf;
1427 if (len <= 0 || len > buf.len) {
1428 len = (int) buf.len;
1429 if (buf.len != len) {
1430 PyErr_SetString(PyExc_OverflowError,
1431 "maximum length can't fit in a C 'int'");
1432 goto error;
1433 }
1434 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001435 }
1436
1437 /* just in case the blocking state of the socket has been changed */
1438 nonblocking = (sock->sock_timeout >= 0.0);
1439 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1440 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1441
1442 /* first check if there are bytes ready to be read */
1443 PySSL_BEGIN_ALLOW_THREADS
1444 count = SSL_pending(self->ssl);
1445 PySSL_END_ALLOW_THREADS
1446
1447 if (!count) {
1448 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1449 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001450 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001451 "The read operation timed out");
1452 goto error;
1453 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1454 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001455 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001456 goto error;
1457 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1458 count = 0;
1459 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001460 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001461 }
1462 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001463 PySSL_BEGIN_ALLOW_THREADS
1464 count = SSL_read(self->ssl, mem, len);
1465 err = SSL_get_error(self->ssl, count);
1466 PySSL_END_ALLOW_THREADS
1467 if (PyErr_CheckSignals())
1468 goto error;
1469 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001470 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001471 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001472 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001473 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1474 (SSL_get_shutdown(self->ssl) ==
1475 SSL_RECEIVED_SHUTDOWN))
1476 {
1477 count = 0;
1478 goto done;
1479 } else {
1480 sockstate = SOCKET_OPERATION_OK;
1481 }
1482 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001483 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001484 "The read operation timed out");
1485 goto error;
1486 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1487 break;
1488 }
1489 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1490 if (count <= 0) {
1491 PySSL_SetError(self, count, __FILE__, __LINE__);
1492 goto error;
1493 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001494
1495done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001496 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001497 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001498 _PyBytes_Resize(&dest, count);
1499 return dest;
1500 }
1501 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001502 PyBuffer_Release(&buf);
1503 return PyLong_FromLong(count);
1504 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001505
1506error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001507 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001508 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001509 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001510 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001511 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001512 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001513}
1514
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001515PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001516"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001517\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001518Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001519
Antoine Pitrou152efa22010-05-16 18:19:27 +00001520static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001521{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522 int err, ssl_err, sockstate, nonblocking;
1523 int zeros = 0;
1524 PySocketSockObject *sock
1525 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001526
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001527 /* Guard against closed socket */
1528 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1529 _setSSLError("Underlying socket connection gone",
1530 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1531 return NULL;
1532 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001533 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001534
1535 /* Just in case the blocking state of the socket has been changed */
1536 nonblocking = (sock->sock_timeout >= 0.0);
1537 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1538 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1539
1540 while (1) {
1541 PySSL_BEGIN_ALLOW_THREADS
1542 /* Disable read-ahead so that unwrap can work correctly.
1543 * Otherwise OpenSSL might read in too much data,
1544 * eating clear text data that happens to be
1545 * transmitted after the SSL shutdown.
1546 * Should be safe to call repeatedly everytime this
1547 * function is used and the shutdown_seen_zero != 0
1548 * condition is met.
1549 */
1550 if (self->shutdown_seen_zero)
1551 SSL_set_read_ahead(self->ssl, 0);
1552 err = SSL_shutdown(self->ssl);
1553 PySSL_END_ALLOW_THREADS
1554 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1555 if (err > 0)
1556 break;
1557 if (err == 0) {
1558 /* Don't loop endlessly; instead preserve legacy
1559 behaviour of trying SSL_shutdown() only twice.
1560 This looks necessary for OpenSSL < 0.9.8m */
1561 if (++zeros > 1)
1562 break;
1563 /* Shutdown was sent, now try receiving */
1564 self->shutdown_seen_zero = 1;
1565 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001566 }
1567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568 /* Possibly retry shutdown until timeout or failure */
1569 ssl_err = SSL_get_error(self->ssl, err);
1570 if (ssl_err == SSL_ERROR_WANT_READ)
1571 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1572 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1573 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1574 else
1575 break;
1576 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1577 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001578 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001579 "The read operation timed out");
1580 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001581 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001582 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001583 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001584 }
1585 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1586 PyErr_SetString(PySSLErrorObject,
1587 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001588 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001589 }
1590 else if (sockstate != SOCKET_OPERATION_OK)
1591 /* Retain the SSL error code */
1592 break;
1593 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001594
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001595 if (err < 0) {
1596 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001597 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001598 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001599 else
1600 /* It's already INCREF'ed */
1601 return (PyObject *) sock;
1602
1603error:
1604 Py_DECREF(sock);
1605 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001606}
1607
1608PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1609"shutdown(s) -> socket\n\
1610\n\
1611Does the SSL shutdown handshake with the remote end, and returns\n\
1612the underlying socket object.");
1613
Antoine Pitroud6494802011-07-21 01:11:30 +02001614#if HAVE_OPENSSL_FINISHED
1615static PyObject *
1616PySSL_tls_unique_cb(PySSLSocket *self)
1617{
1618 PyObject *retval = NULL;
1619 char buf[PySSL_CB_MAXLEN];
1620 int len;
1621
1622 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1623 /* if session is resumed XOR we are the client */
1624 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1625 }
1626 else {
1627 /* if a new session XOR we are the server */
1628 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1629 }
1630
1631 /* It cannot be negative in current OpenSSL version as of July 2011 */
1632 assert(len >= 0);
1633 if (len == 0)
1634 Py_RETURN_NONE;
1635
1636 retval = PyBytes_FromStringAndSize(buf, len);
1637
1638 return retval;
1639}
1640
1641PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1642"tls_unique_cb() -> bytes\n\
1643\n\
1644Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1645\n\
1646If the TLS handshake is not yet complete, None is returned");
1647
1648#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001649
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001650static PyGetSetDef ssl_getsetlist[] = {
1651 {"context", (getter) PySSL_get_context,
1652 (setter) PySSL_set_context, PySSL_set_context_doc},
1653 {NULL}, /* sentinel */
1654};
1655
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001656static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001657 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1658 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1659 PySSL_SSLwrite_doc},
1660 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1661 PySSL_SSLread_doc},
1662 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1663 PySSL_SSLpending_doc},
1664 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1665 PySSL_peercert_doc},
1666 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001667#ifdef OPENSSL_NPN_NEGOTIATED
1668 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1669#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001670 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001671 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1672 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001673#if HAVE_OPENSSL_FINISHED
1674 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1675 PySSL_tls_unique_cb_doc},
1676#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001677 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001678};
1679
Antoine Pitrou152efa22010-05-16 18:19:27 +00001680static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001681 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001682 "_ssl._SSLSocket", /*tp_name*/
1683 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001684 0, /*tp_itemsize*/
1685 /* methods */
1686 (destructor)PySSL_dealloc, /*tp_dealloc*/
1687 0, /*tp_print*/
1688 0, /*tp_getattr*/
1689 0, /*tp_setattr*/
1690 0, /*tp_reserved*/
1691 0, /*tp_repr*/
1692 0, /*tp_as_number*/
1693 0, /*tp_as_sequence*/
1694 0, /*tp_as_mapping*/
1695 0, /*tp_hash*/
1696 0, /*tp_call*/
1697 0, /*tp_str*/
1698 0, /*tp_getattro*/
1699 0, /*tp_setattro*/
1700 0, /*tp_as_buffer*/
1701 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1702 0, /*tp_doc*/
1703 0, /*tp_traverse*/
1704 0, /*tp_clear*/
1705 0, /*tp_richcompare*/
1706 0, /*tp_weaklistoffset*/
1707 0, /*tp_iter*/
1708 0, /*tp_iternext*/
1709 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001710 0, /*tp_members*/
1711 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001712};
1713
Antoine Pitrou152efa22010-05-16 18:19:27 +00001714
1715/*
1716 * _SSLContext objects
1717 */
1718
1719static PyObject *
1720context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1721{
1722 char *kwlist[] = {"protocol", NULL};
1723 PySSLContext *self;
1724 int proto_version = PY_SSL_VERSION_SSL23;
1725 SSL_CTX *ctx = NULL;
1726
1727 if (!PyArg_ParseTupleAndKeywords(
1728 args, kwds, "i:_SSLContext", kwlist,
1729 &proto_version))
1730 return NULL;
1731
1732 PySSL_BEGIN_ALLOW_THREADS
1733 if (proto_version == PY_SSL_VERSION_TLS1)
1734 ctx = SSL_CTX_new(TLSv1_method());
1735 else if (proto_version == PY_SSL_VERSION_SSL3)
1736 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001737#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001738 else if (proto_version == PY_SSL_VERSION_SSL2)
1739 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001740#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001741 else if (proto_version == PY_SSL_VERSION_SSL23)
1742 ctx = SSL_CTX_new(SSLv23_method());
1743 else
1744 proto_version = -1;
1745 PySSL_END_ALLOW_THREADS
1746
1747 if (proto_version == -1) {
1748 PyErr_SetString(PyExc_ValueError,
1749 "invalid protocol version");
1750 return NULL;
1751 }
1752 if (ctx == NULL) {
1753 PyErr_SetString(PySSLErrorObject,
1754 "failed to allocate SSL context");
1755 return NULL;
1756 }
1757
1758 assert(type != NULL && type->tp_alloc != NULL);
1759 self = (PySSLContext *) type->tp_alloc(type, 0);
1760 if (self == NULL) {
1761 SSL_CTX_free(ctx);
1762 return NULL;
1763 }
1764 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001765#ifdef OPENSSL_NPN_NEGOTIATED
1766 self->npn_protocols = NULL;
1767#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001768#ifndef OPENSSL_NO_TLSEXT
1769 self->set_hostname = NULL;
1770#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001771 /* Defaults */
1772 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001773 SSL_CTX_set_options(self->ctx,
1774 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001775
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001776#define SID_CTX "Python"
1777 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1778 sizeof(SID_CTX));
1779#undef SID_CTX
1780
Antoine Pitrou152efa22010-05-16 18:19:27 +00001781 return (PyObject *)self;
1782}
1783
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001784static int
1785context_traverse(PySSLContext *self, visitproc visit, void *arg)
1786{
1787#ifndef OPENSSL_NO_TLSEXT
1788 Py_VISIT(self->set_hostname);
1789#endif
1790 return 0;
1791}
1792
1793static int
1794context_clear(PySSLContext *self)
1795{
1796#ifndef OPENSSL_NO_TLSEXT
1797 Py_CLEAR(self->set_hostname);
1798#endif
1799 return 0;
1800}
1801
Antoine Pitrou152efa22010-05-16 18:19:27 +00001802static void
1803context_dealloc(PySSLContext *self)
1804{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001805 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001806 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001807#ifdef OPENSSL_NPN_NEGOTIATED
1808 PyMem_Free(self->npn_protocols);
1809#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001810 Py_TYPE(self)->tp_free(self);
1811}
1812
1813static PyObject *
1814set_ciphers(PySSLContext *self, PyObject *args)
1815{
1816 int ret;
1817 const char *cipherlist;
1818
1819 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1820 return NULL;
1821 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1822 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001823 /* Clearing the error queue is necessary on some OpenSSL versions,
1824 otherwise the error will be reported again when another SSL call
1825 is done. */
1826 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001827 PyErr_SetString(PySSLErrorObject,
1828 "No cipher can be selected.");
1829 return NULL;
1830 }
1831 Py_RETURN_NONE;
1832}
1833
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001834#ifdef OPENSSL_NPN_NEGOTIATED
1835/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1836static int
1837_advertiseNPN_cb(SSL *s,
1838 const unsigned char **data, unsigned int *len,
1839 void *args)
1840{
1841 PySSLContext *ssl_ctx = (PySSLContext *) args;
1842
1843 if (ssl_ctx->npn_protocols == NULL) {
1844 *data = (unsigned char *) "";
1845 *len = 0;
1846 } else {
1847 *data = (unsigned char *) ssl_ctx->npn_protocols;
1848 *len = ssl_ctx->npn_protocols_len;
1849 }
1850
1851 return SSL_TLSEXT_ERR_OK;
1852}
1853/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1854static int
1855_selectNPN_cb(SSL *s,
1856 unsigned char **out, unsigned char *outlen,
1857 const unsigned char *server, unsigned int server_len,
1858 void *args)
1859{
1860 PySSLContext *ssl_ctx = (PySSLContext *) args;
1861
1862 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1863 int client_len;
1864
1865 if (client == NULL) {
1866 client = (unsigned char *) "";
1867 client_len = 0;
1868 } else {
1869 client_len = ssl_ctx->npn_protocols_len;
1870 }
1871
1872 SSL_select_next_proto(out, outlen,
1873 server, server_len,
1874 client, client_len);
1875
1876 return SSL_TLSEXT_ERR_OK;
1877}
1878#endif
1879
1880static PyObject *
1881_set_npn_protocols(PySSLContext *self, PyObject *args)
1882{
1883#ifdef OPENSSL_NPN_NEGOTIATED
1884 Py_buffer protos;
1885
1886 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1887 return NULL;
1888
Christian Heimes5cb31c92012-09-20 12:42:54 +02001889 if (self->npn_protocols != NULL) {
1890 PyMem_Free(self->npn_protocols);
1891 }
1892
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001893 self->npn_protocols = PyMem_Malloc(protos.len);
1894 if (self->npn_protocols == NULL) {
1895 PyBuffer_Release(&protos);
1896 return PyErr_NoMemory();
1897 }
1898 memcpy(self->npn_protocols, protos.buf, protos.len);
1899 self->npn_protocols_len = (int) protos.len;
1900
1901 /* set both server and client callbacks, because the context can
1902 * be used to create both types of sockets */
1903 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
1904 _advertiseNPN_cb,
1905 self);
1906 SSL_CTX_set_next_proto_select_cb(self->ctx,
1907 _selectNPN_cb,
1908 self);
1909
1910 PyBuffer_Release(&protos);
1911 Py_RETURN_NONE;
1912#else
1913 PyErr_SetString(PyExc_NotImplementedError,
1914 "The NPN extension requires OpenSSL 1.0.1 or later.");
1915 return NULL;
1916#endif
1917}
1918
Antoine Pitrou152efa22010-05-16 18:19:27 +00001919static PyObject *
1920get_verify_mode(PySSLContext *self, void *c)
1921{
1922 switch (SSL_CTX_get_verify_mode(self->ctx)) {
1923 case SSL_VERIFY_NONE:
1924 return PyLong_FromLong(PY_SSL_CERT_NONE);
1925 case SSL_VERIFY_PEER:
1926 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
1927 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
1928 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
1929 }
1930 PyErr_SetString(PySSLErrorObject,
1931 "invalid return value from SSL_CTX_get_verify_mode");
1932 return NULL;
1933}
1934
1935static int
1936set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
1937{
1938 int n, mode;
1939 if (!PyArg_Parse(arg, "i", &n))
1940 return -1;
1941 if (n == PY_SSL_CERT_NONE)
1942 mode = SSL_VERIFY_NONE;
1943 else if (n == PY_SSL_CERT_OPTIONAL)
1944 mode = SSL_VERIFY_PEER;
1945 else if (n == PY_SSL_CERT_REQUIRED)
1946 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
1947 else {
1948 PyErr_SetString(PyExc_ValueError,
1949 "invalid value for verify_mode");
1950 return -1;
1951 }
1952 SSL_CTX_set_verify(self->ctx, mode, NULL);
1953 return 0;
1954}
1955
1956static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00001957get_options(PySSLContext *self, void *c)
1958{
1959 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
1960}
1961
1962static int
1963set_options(PySSLContext *self, PyObject *arg, void *c)
1964{
1965 long new_opts, opts, set, clear;
1966 if (!PyArg_Parse(arg, "l", &new_opts))
1967 return -1;
1968 opts = SSL_CTX_get_options(self->ctx);
1969 clear = opts & ~new_opts;
1970 set = ~opts & new_opts;
1971 if (clear) {
1972#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
1973 SSL_CTX_clear_options(self->ctx, clear);
1974#else
1975 PyErr_SetString(PyExc_ValueError,
1976 "can't clear options before OpenSSL 0.9.8m");
1977 return -1;
1978#endif
1979 }
1980 if (set)
1981 SSL_CTX_set_options(self->ctx, set);
1982 return 0;
1983}
1984
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02001985typedef struct {
1986 PyThreadState *thread_state;
1987 PyObject *callable;
1988 char *password;
1989 Py_ssize_t size;
1990 int error;
1991} _PySSLPasswordInfo;
1992
1993static int
1994_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
1995 const char *bad_type_error)
1996{
1997 /* Set the password and size fields of a _PySSLPasswordInfo struct
1998 from a unicode, bytes, or byte array object.
1999 The password field will be dynamically allocated and must be freed
2000 by the caller */
2001 PyObject *password_bytes = NULL;
2002 const char *data = NULL;
2003 Py_ssize_t size;
2004
2005 if (PyUnicode_Check(password)) {
2006 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2007 if (!password_bytes) {
2008 goto error;
2009 }
2010 data = PyBytes_AS_STRING(password_bytes);
2011 size = PyBytes_GET_SIZE(password_bytes);
2012 } else if (PyBytes_Check(password)) {
2013 data = PyBytes_AS_STRING(password);
2014 size = PyBytes_GET_SIZE(password);
2015 } else if (PyByteArray_Check(password)) {
2016 data = PyByteArray_AS_STRING(password);
2017 size = PyByteArray_GET_SIZE(password);
2018 } else {
2019 PyErr_SetString(PyExc_TypeError, bad_type_error);
2020 goto error;
2021 }
2022
2023 free(pw_info->password);
2024 pw_info->password = malloc(size);
2025 if (!pw_info->password) {
2026 PyErr_SetString(PyExc_MemoryError,
2027 "unable to allocate password buffer");
2028 goto error;
2029 }
2030 memcpy(pw_info->password, data, size);
2031 pw_info->size = size;
2032
2033 Py_XDECREF(password_bytes);
2034 return 1;
2035
2036error:
2037 Py_XDECREF(password_bytes);
2038 return 0;
2039}
2040
2041static int
2042_password_callback(char *buf, int size, int rwflag, void *userdata)
2043{
2044 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2045 PyObject *fn_ret = NULL;
2046
2047 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2048
2049 if (pw_info->callable) {
2050 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2051 if (!fn_ret) {
2052 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2053 core python API, so we could use it to add a frame here */
2054 goto error;
2055 }
2056
2057 if (!_pwinfo_set(pw_info, fn_ret,
2058 "password callback must return a string")) {
2059 goto error;
2060 }
2061 Py_CLEAR(fn_ret);
2062 }
2063
2064 if (pw_info->size > size) {
2065 PyErr_Format(PyExc_ValueError,
2066 "password cannot be longer than %d bytes", size);
2067 goto error;
2068 }
2069
2070 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2071 memcpy(buf, pw_info->password, pw_info->size);
2072 return pw_info->size;
2073
2074error:
2075 Py_XDECREF(fn_ret);
2076 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2077 pw_info->error = 1;
2078 return -1;
2079}
2080
Antoine Pitroub5218772010-05-21 09:56:06 +00002081static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002082load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2083{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002084 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2085 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002086 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002087 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2088 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2089 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002090 int r;
2091
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002092 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002093 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002094 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002095 "O|OO:load_cert_chain", kwlist,
2096 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002097 return NULL;
2098 if (keyfile == Py_None)
2099 keyfile = NULL;
2100 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2101 PyErr_SetString(PyExc_TypeError,
2102 "certfile should be a valid filesystem path");
2103 return NULL;
2104 }
2105 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2106 PyErr_SetString(PyExc_TypeError,
2107 "keyfile should be a valid filesystem path");
2108 goto error;
2109 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002110 if (password && password != Py_None) {
2111 if (PyCallable_Check(password)) {
2112 pw_info.callable = password;
2113 } else if (!_pwinfo_set(&pw_info, password,
2114 "password should be a string or callable")) {
2115 goto error;
2116 }
2117 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2118 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2119 }
2120 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002121 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2122 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002123 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002124 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002125 if (pw_info.error) {
2126 ERR_clear_error();
2127 /* the password callback has already set the error information */
2128 }
2129 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002130 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002131 PyErr_SetFromErrno(PyExc_IOError);
2132 }
2133 else {
2134 _setSSLError(NULL, 0, __FILE__, __LINE__);
2135 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002136 goto error;
2137 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002138 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002139 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002140 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2141 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002142 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2143 Py_CLEAR(keyfile_bytes);
2144 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002145 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002146 if (pw_info.error) {
2147 ERR_clear_error();
2148 /* the password callback has already set the error information */
2149 }
2150 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002151 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002152 PyErr_SetFromErrno(PyExc_IOError);
2153 }
2154 else {
2155 _setSSLError(NULL, 0, __FILE__, __LINE__);
2156 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002157 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002158 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002159 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002160 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002161 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002162 if (r != 1) {
2163 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002164 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002165 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002166 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2167 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2168 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002169 Py_RETURN_NONE;
2170
2171error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002172 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2173 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
2174 free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002175 Py_XDECREF(keyfile_bytes);
2176 Py_XDECREF(certfile_bytes);
2177 return NULL;
2178}
2179
2180static PyObject *
2181load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2182{
2183 char *kwlist[] = {"cafile", "capath", NULL};
2184 PyObject *cafile = NULL, *capath = NULL;
2185 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2186 const char *cafile_buf = NULL, *capath_buf = NULL;
2187 int r;
2188
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002189 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002190 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2191 "|OO:load_verify_locations", kwlist,
2192 &cafile, &capath))
2193 return NULL;
2194 if (cafile == Py_None)
2195 cafile = NULL;
2196 if (capath == Py_None)
2197 capath = NULL;
2198 if (cafile == NULL && capath == NULL) {
2199 PyErr_SetString(PyExc_TypeError,
2200 "cafile and capath cannot be both omitted");
2201 return NULL;
2202 }
2203 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2204 PyErr_SetString(PyExc_TypeError,
2205 "cafile should be a valid filesystem path");
2206 return NULL;
2207 }
2208 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002209 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002210 PyErr_SetString(PyExc_TypeError,
2211 "capath should be a valid filesystem path");
2212 return NULL;
2213 }
2214 if (cafile)
2215 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2216 if (capath)
2217 capath_buf = PyBytes_AS_STRING(capath_bytes);
2218 PySSL_BEGIN_ALLOW_THREADS
2219 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2220 PySSL_END_ALLOW_THREADS
2221 Py_XDECREF(cafile_bytes);
2222 Py_XDECREF(capath_bytes);
2223 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002224 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002225 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002226 PyErr_SetFromErrno(PyExc_IOError);
2227 }
2228 else {
2229 _setSSLError(NULL, 0, __FILE__, __LINE__);
2230 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002231 return NULL;
2232 }
2233 Py_RETURN_NONE;
2234}
2235
2236static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002237load_dh_params(PySSLContext *self, PyObject *filepath)
2238{
2239 FILE *f;
2240 DH *dh;
2241
2242 f = _Py_fopen(filepath, "rb");
2243 if (f == NULL) {
2244 if (!PyErr_Occurred())
2245 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2246 return NULL;
2247 }
2248 errno = 0;
2249 PySSL_BEGIN_ALLOW_THREADS
2250 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002251 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002252 PySSL_END_ALLOW_THREADS
2253 if (dh == NULL) {
2254 if (errno != 0) {
2255 ERR_clear_error();
2256 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2257 }
2258 else {
2259 _setSSLError(NULL, 0, __FILE__, __LINE__);
2260 }
2261 return NULL;
2262 }
2263 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2264 _setSSLError(NULL, 0, __FILE__, __LINE__);
2265 DH_free(dh);
2266 Py_RETURN_NONE;
2267}
2268
2269static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002270context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2271{
Antoine Pitroud5323212010-10-22 18:19:07 +00002272 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002273 PySocketSockObject *sock;
2274 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002275 char *hostname = NULL;
2276 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002277
Antoine Pitroud5323212010-10-22 18:19:07 +00002278 /* server_hostname is either None (or absent), or to be encoded
2279 using the idna encoding. */
2280 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002281 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002282 &sock, &server_side,
2283 Py_TYPE(Py_None), &hostname_obj)) {
2284 PyErr_Clear();
2285 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2286 PySocketModule.Sock_Type,
2287 &sock, &server_side,
2288 "idna", &hostname))
2289 return NULL;
2290#ifndef SSL_CTRL_SET_TLSEXT_HOSTNAME
2291 PyMem_Free(hostname);
2292 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2293 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002294 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002295#endif
2296 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002297
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002298 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002299 hostname);
2300 if (hostname != NULL)
2301 PyMem_Free(hostname);
2302 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002303}
2304
Antoine Pitroub0182c82010-10-12 20:09:02 +00002305static PyObject *
2306session_stats(PySSLContext *self, PyObject *unused)
2307{
2308 int r;
2309 PyObject *value, *stats = PyDict_New();
2310 if (!stats)
2311 return NULL;
2312
2313#define ADD_STATS(SSL_NAME, KEY_NAME) \
2314 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2315 if (value == NULL) \
2316 goto error; \
2317 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2318 Py_DECREF(value); \
2319 if (r < 0) \
2320 goto error;
2321
2322 ADD_STATS(number, "number");
2323 ADD_STATS(connect, "connect");
2324 ADD_STATS(connect_good, "connect_good");
2325 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2326 ADD_STATS(accept, "accept");
2327 ADD_STATS(accept_good, "accept_good");
2328 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2329 ADD_STATS(accept, "accept");
2330 ADD_STATS(hits, "hits");
2331 ADD_STATS(misses, "misses");
2332 ADD_STATS(timeouts, "timeouts");
2333 ADD_STATS(cache_full, "cache_full");
2334
2335#undef ADD_STATS
2336
2337 return stats;
2338
2339error:
2340 Py_DECREF(stats);
2341 return NULL;
2342}
2343
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002344static PyObject *
2345set_default_verify_paths(PySSLContext *self, PyObject *unused)
2346{
2347 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2348 _setSSLError(NULL, 0, __FILE__, __LINE__);
2349 return NULL;
2350 }
2351 Py_RETURN_NONE;
2352}
2353
Antoine Pitrou501da612011-12-21 09:27:41 +01002354#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002355static PyObject *
2356set_ecdh_curve(PySSLContext *self, PyObject *name)
2357{
2358 PyObject *name_bytes;
2359 int nid;
2360 EC_KEY *key;
2361
2362 if (!PyUnicode_FSConverter(name, &name_bytes))
2363 return NULL;
2364 assert(PyBytes_Check(name_bytes));
2365 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2366 Py_DECREF(name_bytes);
2367 if (nid == 0) {
2368 PyErr_Format(PyExc_ValueError,
2369 "unknown elliptic curve name %R", name);
2370 return NULL;
2371 }
2372 key = EC_KEY_new_by_curve_name(nid);
2373 if (key == NULL) {
2374 _setSSLError(NULL, 0, __FILE__, __LINE__);
2375 return NULL;
2376 }
2377 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2378 EC_KEY_free(key);
2379 Py_RETURN_NONE;
2380}
Antoine Pitrou501da612011-12-21 09:27:41 +01002381#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002382
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002383#ifndef OPENSSL_NO_TLSEXT
2384static int
2385_servername_callback(SSL *s, int *al, void *args)
2386{
2387 int ret;
2388 PySSLContext *ssl_ctx = (PySSLContext *) args;
2389 PySSLSocket *ssl;
2390 PyObject *servername_o;
2391 PyObject *servername_idna;
2392 PyObject *result;
2393 /* The high-level ssl.SSLSocket object */
2394 PyObject *ssl_socket;
2395 PyGILState_STATE gstate;
2396 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
2397
2398 gstate = PyGILState_Ensure();
2399
2400 if (ssl_ctx->set_hostname == NULL) {
2401 /* remove race condition in this the call back while if removing the
2402 * callback is in progress */
2403 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002404 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002405 }
2406
2407 ssl = SSL_get_app_data(s);
2408 assert(PySSLSocket_Check(ssl));
2409 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2410 Py_INCREF(ssl_socket);
2411 if (ssl_socket == Py_None) {
2412 goto error;
2413 }
2414
2415 servername_o = PyBytes_FromString(servername);
2416 if (servername_o == NULL) {
2417 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2418 goto error;
2419 }
2420 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2421 if (servername_idna == NULL) {
2422 PyErr_WriteUnraisable(servername_o);
2423 Py_DECREF(servername_o);
2424 goto error;
2425 }
2426 Py_DECREF(servername_o);
2427 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2428 servername_idna, ssl_ctx, NULL);
2429 Py_DECREF(ssl_socket);
2430 Py_DECREF(servername_idna);
2431
2432 if (result == NULL) {
2433 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2434 *al = SSL_AD_HANDSHAKE_FAILURE;
2435 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2436 }
2437 else {
2438 if (result != Py_None) {
2439 *al = (int) PyLong_AsLong(result);
2440 if (PyErr_Occurred()) {
2441 PyErr_WriteUnraisable(result);
2442 *al = SSL_AD_INTERNAL_ERROR;
2443 }
2444 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2445 }
2446 else {
2447 ret = SSL_TLSEXT_ERR_OK;
2448 }
2449 Py_DECREF(result);
2450 }
2451
2452 PyGILState_Release(gstate);
2453 return ret;
2454
2455error:
2456 Py_DECREF(ssl_socket);
2457 *al = SSL_AD_INTERNAL_ERROR;
2458 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2459 PyGILState_Release(gstate);
2460 return ret;
2461}
2462
2463PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2464"set_servername_callback(method)\n\
2465\
2466This sets a callback that will be called when a server name is provided by\n\
2467the SSL/TLS client in the SNI extension.\n\
2468\
2469If the argument is None then the callback is disabled. The method is called\n\
2470with the SSLSocket, the server name as a string, and the SSLContext object.\n\
2471See RFC 6066 for details of the SNI");
2472#endif
2473
2474static PyObject *
2475set_servername_callback(PySSLContext *self, PyObject *args)
2476{
2477#ifndef OPENSSL_NO_TLSEXT
2478 PyObject *cb;
2479
2480 if (!PyArg_ParseTuple(args, "O", &cb))
2481 return NULL;
2482
2483 Py_CLEAR(self->set_hostname);
2484 if (cb == Py_None) {
2485 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2486 }
2487 else {
2488 if (!PyCallable_Check(cb)) {
2489 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2490 PyErr_SetString(PyExc_TypeError,
2491 "not a callable object");
2492 return NULL;
2493 }
2494 Py_INCREF(cb);
2495 self->set_hostname = cb;
2496 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
2497 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
2498 }
2499 Py_RETURN_NONE;
2500#else
2501 PyErr_SetString(PyExc_NotImplementedError,
2502 "The TLS extension servername callback, "
2503 "SSL_CTX_set_tlsext_servername_callback, "
2504 "is not in the current OpenSSL library.");
2505#endif
2506}
2507
Antoine Pitrou152efa22010-05-16 18:19:27 +00002508static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002509 {"options", (getter) get_options,
2510 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002511 {"verify_mode", (getter) get_verify_mode,
2512 (setter) set_verify_mode, NULL},
2513 {NULL}, /* sentinel */
2514};
2515
2516static struct PyMethodDef context_methods[] = {
2517 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2518 METH_VARARGS | METH_KEYWORDS, NULL},
2519 {"set_ciphers", (PyCFunction) set_ciphers,
2520 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002521 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2522 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002523 {"load_cert_chain", (PyCFunction) load_cert_chain,
2524 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002525 {"load_dh_params", (PyCFunction) load_dh_params,
2526 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002527 {"load_verify_locations", (PyCFunction) load_verify_locations,
2528 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002529 {"session_stats", (PyCFunction) session_stats,
2530 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002531 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2532 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002533#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002534 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2535 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002536#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002537 {"set_servername_callback", (PyCFunction) set_servername_callback,
2538 METH_VARARGS, PySSL_set_servername_callback_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002539 {NULL, NULL} /* sentinel */
2540};
2541
2542static PyTypeObject PySSLContext_Type = {
2543 PyVarObject_HEAD_INIT(NULL, 0)
2544 "_ssl._SSLContext", /*tp_name*/
2545 sizeof(PySSLContext), /*tp_basicsize*/
2546 0, /*tp_itemsize*/
2547 (destructor)context_dealloc, /*tp_dealloc*/
2548 0, /*tp_print*/
2549 0, /*tp_getattr*/
2550 0, /*tp_setattr*/
2551 0, /*tp_reserved*/
2552 0, /*tp_repr*/
2553 0, /*tp_as_number*/
2554 0, /*tp_as_sequence*/
2555 0, /*tp_as_mapping*/
2556 0, /*tp_hash*/
2557 0, /*tp_call*/
2558 0, /*tp_str*/
2559 0, /*tp_getattro*/
2560 0, /*tp_setattro*/
2561 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002562 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002563 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002564 (traverseproc) context_traverse, /*tp_traverse*/
2565 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002566 0, /*tp_richcompare*/
2567 0, /*tp_weaklistoffset*/
2568 0, /*tp_iter*/
2569 0, /*tp_iternext*/
2570 context_methods, /*tp_methods*/
2571 0, /*tp_members*/
2572 context_getsetlist, /*tp_getset*/
2573 0, /*tp_base*/
2574 0, /*tp_dict*/
2575 0, /*tp_descr_get*/
2576 0, /*tp_descr_set*/
2577 0, /*tp_dictoffset*/
2578 0, /*tp_init*/
2579 0, /*tp_alloc*/
2580 context_new, /*tp_new*/
2581};
2582
2583
2584
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002585#ifdef HAVE_OPENSSL_RAND
2586
2587/* helper routines for seeding the SSL PRNG */
2588static PyObject *
2589PySSL_RAND_add(PyObject *self, PyObject *args)
2590{
2591 char *buf;
2592 int len;
2593 double entropy;
2594
2595 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002596 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002597 RAND_add(buf, len, entropy);
2598 Py_INCREF(Py_None);
2599 return Py_None;
2600}
2601
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002602PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002603"RAND_add(string, entropy)\n\
2604\n\
2605Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002606bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002607
2608static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002609PySSL_RAND(int len, int pseudo)
2610{
2611 int ok;
2612 PyObject *bytes;
2613 unsigned long err;
2614 const char *errstr;
2615 PyObject *v;
2616
2617 bytes = PyBytes_FromStringAndSize(NULL, len);
2618 if (bytes == NULL)
2619 return NULL;
2620 if (pseudo) {
2621 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2622 if (ok == 0 || ok == 1)
2623 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2624 }
2625 else {
2626 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2627 if (ok == 1)
2628 return bytes;
2629 }
2630 Py_DECREF(bytes);
2631
2632 err = ERR_get_error();
2633 errstr = ERR_reason_error_string(err);
2634 v = Py_BuildValue("(ks)", err, errstr);
2635 if (v != NULL) {
2636 PyErr_SetObject(PySSLErrorObject, v);
2637 Py_DECREF(v);
2638 }
2639 return NULL;
2640}
2641
2642static PyObject *
2643PySSL_RAND_bytes(PyObject *self, PyObject *args)
2644{
2645 int len;
2646 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2647 return NULL;
2648 return PySSL_RAND(len, 0);
2649}
2650
2651PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2652"RAND_bytes(n) -> bytes\n\
2653\n\
2654Generate n cryptographically strong pseudo-random bytes.");
2655
2656static PyObject *
2657PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2658{
2659 int len;
2660 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2661 return NULL;
2662 return PySSL_RAND(len, 1);
2663}
2664
2665PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2666"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2667\n\
2668Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2669generated are cryptographically strong.");
2670
2671static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002672PySSL_RAND_status(PyObject *self)
2673{
Christian Heimes217cfd12007-12-02 14:31:20 +00002674 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002675}
2676
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002677PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002678"RAND_status() -> 0 or 1\n\
2679\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002680Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2681It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2682using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002683
2684static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002685PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002686{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002687 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002688 int bytes;
2689
Jesus Ceac8754a12012-09-11 02:00:58 +02002690 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002691 PyUnicode_FSConverter, &path))
2692 return NULL;
2693
2694 bytes = RAND_egd(PyBytes_AsString(path));
2695 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002696 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002697 PyErr_SetString(PySSLErrorObject,
2698 "EGD connection failed or EGD did not return "
2699 "enough data to seed the PRNG");
2700 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002701 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002702 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002703}
2704
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002705PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002706"RAND_egd(path) -> bytes\n\
2707\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002708Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2709Returns number of bytes read. Raises SSLError if connection to EGD\n\
2710fails or if it does provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002711
2712#endif
2713
Bill Janssen40a0f662008-08-12 16:56:25 +00002714
2715
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002716/* List of functions exported by this module. */
2717
2718static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002719 {"_test_decode_cert", PySSL_test_decode_certificate,
2720 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002721#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002722 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
2723 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02002724 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
2725 PySSL_RAND_bytes_doc},
2726 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
2727 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002728 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002729 PySSL_RAND_egd_doc},
2730 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
2731 PySSL_RAND_status_doc},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002732#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002733 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002734};
2735
2736
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002737#ifdef WITH_THREAD
2738
2739/* an implementation of OpenSSL threading operations in terms
2740 of the Python C thread library */
2741
2742static PyThread_type_lock *_ssl_locks = NULL;
2743
2744static unsigned long _ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002745 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002746}
2747
Bill Janssen6e027db2007-11-15 22:23:56 +00002748static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002749 (int mode, int n, const char *file, int line) {
2750 /* this function is needed to perform locking on shared data
2751 structures. (Note that OpenSSL uses a number of global data
2752 structures that will be implicitly shared whenever multiple
2753 threads use OpenSSL.) Multi-threaded applications will
2754 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002755
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002756 locking_function() must be able to handle up to
2757 CRYPTO_num_locks() different mutex locks. It sets the n-th
2758 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002759
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002760 file and line are the file number of the function setting the
2761 lock. They can be useful for debugging.
2762 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002763
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002764 if ((_ssl_locks == NULL) ||
2765 (n < 0) || ((unsigned)n >= _ssl_locks_count))
2766 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002767
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002768 if (mode & CRYPTO_LOCK) {
2769 PyThread_acquire_lock(_ssl_locks[n], 1);
2770 } else {
2771 PyThread_release_lock(_ssl_locks[n]);
2772 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002773}
2774
2775static int _setup_ssl_threads(void) {
2776
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002777 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002778
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002779 if (_ssl_locks == NULL) {
2780 _ssl_locks_count = CRYPTO_num_locks();
2781 _ssl_locks = (PyThread_type_lock *)
2782 malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
2783 if (_ssl_locks == NULL)
2784 return 0;
2785 memset(_ssl_locks, 0,
2786 sizeof(PyThread_type_lock) * _ssl_locks_count);
2787 for (i = 0; i < _ssl_locks_count; i++) {
2788 _ssl_locks[i] = PyThread_allocate_lock();
2789 if (_ssl_locks[i] == NULL) {
2790 unsigned int j;
2791 for (j = 0; j < i; j++) {
2792 PyThread_free_lock(_ssl_locks[j]);
2793 }
2794 free(_ssl_locks);
2795 return 0;
2796 }
2797 }
2798 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
2799 CRYPTO_set_id_callback(_ssl_thread_id_function);
2800 }
2801 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002802}
2803
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002804#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002805
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002806PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002807"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002808for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002809
Martin v. Löwis1a214512008-06-11 05:26:20 +00002810
2811static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002812 PyModuleDef_HEAD_INIT,
2813 "_ssl",
2814 module_doc,
2815 -1,
2816 PySSL_methods,
2817 NULL,
2818 NULL,
2819 NULL,
2820 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002821};
2822
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02002823
2824static void
2825parse_openssl_version(unsigned long libver,
2826 unsigned int *major, unsigned int *minor,
2827 unsigned int *fix, unsigned int *patch,
2828 unsigned int *status)
2829{
2830 *status = libver & 0xF;
2831 libver >>= 4;
2832 *patch = libver & 0xFF;
2833 libver >>= 8;
2834 *fix = libver & 0xFF;
2835 libver >>= 8;
2836 *minor = libver & 0xFF;
2837 libver >>= 8;
2838 *major = libver & 0xFF;
2839}
2840
Mark Hammondfe51c6d2002-08-02 02:27:13 +00002841PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00002842PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002843{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002844 PyObject *m, *d, *r;
2845 unsigned long libver;
2846 unsigned int major, minor, fix, patch, status;
2847 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002848 struct py_ssl_error_code *errcode;
2849 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002850
Antoine Pitrou152efa22010-05-16 18:19:27 +00002851 if (PyType_Ready(&PySSLContext_Type) < 0)
2852 return NULL;
2853 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002854 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002855
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002856 m = PyModule_Create(&_sslmodule);
2857 if (m == NULL)
2858 return NULL;
2859 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002860
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002861 /* Load _socket module and its C API */
2862 socket_api = PySocketModule_ImportModuleAndAPI();
2863 if (!socket_api)
2864 return NULL;
2865 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002866
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002867 /* Init OpenSSL */
2868 SSL_load_error_strings();
2869 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002870#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002871 /* note that this will start threading if not already started */
2872 if (!_setup_ssl_threads()) {
2873 return NULL;
2874 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002875#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002876 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002877
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002878 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002879 sslerror_type_slots[0].pfunc = PyExc_OSError;
2880 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002881 if (PySSLErrorObject == NULL)
2882 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02002883
Antoine Pitrou41032a62011-10-27 23:56:55 +02002884 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
2885 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
2886 PySSLErrorObject, NULL);
2887 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
2888 "ssl.SSLWantReadError", SSLWantReadError_doc,
2889 PySSLErrorObject, NULL);
2890 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
2891 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
2892 PySSLErrorObject, NULL);
2893 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
2894 "ssl.SSLSyscallError", SSLSyscallError_doc,
2895 PySSLErrorObject, NULL);
2896 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
2897 "ssl.SSLEOFError", SSLEOFError_doc,
2898 PySSLErrorObject, NULL);
2899 if (PySSLZeroReturnErrorObject == NULL
2900 || PySSLWantReadErrorObject == NULL
2901 || PySSLWantWriteErrorObject == NULL
2902 || PySSLSyscallErrorObject == NULL
2903 || PySSLEOFErrorObject == NULL)
2904 return NULL;
2905 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
2906 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
2907 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
2908 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
2909 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
2910 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002911 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002912 if (PyDict_SetItemString(d, "_SSLContext",
2913 (PyObject *)&PySSLContext_Type) != 0)
2914 return NULL;
2915 if (PyDict_SetItemString(d, "_SSLSocket",
2916 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002917 return NULL;
2918 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
2919 PY_SSL_ERROR_ZERO_RETURN);
2920 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
2921 PY_SSL_ERROR_WANT_READ);
2922 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
2923 PY_SSL_ERROR_WANT_WRITE);
2924 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
2925 PY_SSL_ERROR_WANT_X509_LOOKUP);
2926 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
2927 PY_SSL_ERROR_SYSCALL);
2928 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
2929 PY_SSL_ERROR_SSL);
2930 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
2931 PY_SSL_ERROR_WANT_CONNECT);
2932 /* non ssl.h errorcodes */
2933 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
2934 PY_SSL_ERROR_EOF);
2935 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
2936 PY_SSL_ERROR_INVALID_ERROR_CODE);
2937 /* cert requirements */
2938 PyModule_AddIntConstant(m, "CERT_NONE",
2939 PY_SSL_CERT_NONE);
2940 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
2941 PY_SSL_CERT_OPTIONAL);
2942 PyModule_AddIntConstant(m, "CERT_REQUIRED",
2943 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00002944
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002945 /* Alert Descriptions from ssl.h */
2946 /* note RESERVED constants no longer intended for use have been removed */
2947 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
2948
2949#define ADD_AD_CONSTANT(s) \
2950 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
2951 SSL_AD_##s)
2952
2953 ADD_AD_CONSTANT(CLOSE_NOTIFY);
2954 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
2955 ADD_AD_CONSTANT(BAD_RECORD_MAC);
2956 ADD_AD_CONSTANT(RECORD_OVERFLOW);
2957 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
2958 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
2959 ADD_AD_CONSTANT(BAD_CERTIFICATE);
2960 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
2961 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
2962 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
2963 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
2964 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
2965 ADD_AD_CONSTANT(UNKNOWN_CA);
2966 ADD_AD_CONSTANT(ACCESS_DENIED);
2967 ADD_AD_CONSTANT(DECODE_ERROR);
2968 ADD_AD_CONSTANT(DECRYPT_ERROR);
2969 ADD_AD_CONSTANT(PROTOCOL_VERSION);
2970 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
2971 ADD_AD_CONSTANT(INTERNAL_ERROR);
2972 ADD_AD_CONSTANT(USER_CANCELLED);
2973 ADD_AD_CONSTANT(NO_RENEGOTIATION);
2974 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
2975 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
2976 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
2977 /* Not all constants are in old OpenSSL versions */
2978#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
2979 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
2980#endif
2981#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
2982 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
2983#endif
2984#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
2985 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
2986#endif
2987
2988#undef ADD_AD_CONSTANT
2989
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002990 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02002991#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002992 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
2993 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02002994#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002995 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
2996 PY_SSL_VERSION_SSL3);
2997 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
2998 PY_SSL_VERSION_SSL23);
2999 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
3000 PY_SSL_VERSION_TLS1);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003001
Antoine Pitroub5218772010-05-21 09:56:06 +00003002 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01003003 PyModule_AddIntConstant(m, "OP_ALL",
3004 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00003005 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
3006 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
3007 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou6db49442011-12-19 13:27:11 +01003008 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
3009 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003010 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003011#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003012 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003013#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003014#ifdef SSL_OP_NO_COMPRESSION
3015 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
3016 SSL_OP_NO_COMPRESSION);
3017#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00003018
Antoine Pitroud5323212010-10-22 18:19:07 +00003019#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
3020 r = Py_True;
3021#else
3022 r = Py_False;
3023#endif
3024 Py_INCREF(r);
3025 PyModule_AddObject(m, "HAS_SNI", r);
3026
Antoine Pitroud6494802011-07-21 01:11:30 +02003027#if HAVE_OPENSSL_FINISHED
3028 r = Py_True;
3029#else
3030 r = Py_False;
3031#endif
3032 Py_INCREF(r);
3033 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
3034
Antoine Pitrou501da612011-12-21 09:27:41 +01003035#ifdef OPENSSL_NO_ECDH
3036 r = Py_False;
3037#else
3038 r = Py_True;
3039#endif
3040 Py_INCREF(r);
3041 PyModule_AddObject(m, "HAS_ECDH", r);
3042
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003043#ifdef OPENSSL_NPN_NEGOTIATED
3044 r = Py_True;
3045#else
3046 r = Py_False;
3047#endif
3048 Py_INCREF(r);
3049 PyModule_AddObject(m, "HAS_NPN", r);
3050
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003051 /* Mappings for error codes */
3052 err_codes_to_names = PyDict_New();
3053 err_names_to_codes = PyDict_New();
3054 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
3055 return NULL;
3056 errcode = error_codes;
3057 while (errcode->mnemonic != NULL) {
3058 PyObject *mnemo, *key;
3059 mnemo = PyUnicode_FromString(errcode->mnemonic);
3060 key = Py_BuildValue("ii", errcode->library, errcode->reason);
3061 if (mnemo == NULL || key == NULL)
3062 return NULL;
3063 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
3064 return NULL;
3065 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
3066 return NULL;
3067 Py_DECREF(key);
3068 Py_DECREF(mnemo);
3069 errcode++;
3070 }
3071 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
3072 return NULL;
3073 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
3074 return NULL;
3075
3076 lib_codes_to_names = PyDict_New();
3077 if (lib_codes_to_names == NULL)
3078 return NULL;
3079 libcode = library_codes;
3080 while (libcode->library != NULL) {
3081 PyObject *mnemo, *key;
3082 key = PyLong_FromLong(libcode->code);
3083 mnemo = PyUnicode_FromString(libcode->library);
3084 if (key == NULL || mnemo == NULL)
3085 return NULL;
3086 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
3087 return NULL;
3088 Py_DECREF(key);
3089 Py_DECREF(mnemo);
3090 libcode++;
3091 }
3092 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
3093 return NULL;
3094
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003095 /* OpenSSL version */
3096 /* SSLeay() gives us the version of the library linked against,
3097 which could be different from the headers version.
3098 */
3099 libver = SSLeay();
3100 r = PyLong_FromUnsignedLong(libver);
3101 if (r == NULL)
3102 return NULL;
3103 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
3104 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003105 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003106 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3107 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
3108 return NULL;
3109 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
3110 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
3111 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003112
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003113 libver = OPENSSL_VERSION_NUMBER;
3114 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
3115 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3116 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
3117 return NULL;
3118
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003119 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003120}