blob: 34a141bd271896bbef0e69184d9aaf570c6c95fe [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"
Christian Heimesf77b4b22013-08-21 13:26:05 +020021
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020023#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
24 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
25#define PySSL_END_ALLOW_THREADS_S(save) \
26 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000027#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000028 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020029 PySSL_BEGIN_ALLOW_THREADS_S(_save);
30#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
31#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
32#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000033
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000034#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000035
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020036#define PySSL_BEGIN_ALLOW_THREADS_S(save)
37#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000038#define PySSL_BEGIN_ALLOW_THREADS
39#define PySSL_BLOCK_THREADS
40#define PySSL_UNBLOCK_THREADS
41#define PySSL_END_ALLOW_THREADS
42
43#endif
44
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010045/* Include symbols from _socket module */
46#include "socketmodule.h"
47
48static PySocketModule_APIObject PySocketModule;
49
50#if defined(HAVE_POLL_H)
51#include <poll.h>
52#elif defined(HAVE_SYS_POLL_H)
53#include <sys/poll.h>
54#endif
55
56/* Include OpenSSL header files */
57#include "openssl/rsa.h"
58#include "openssl/crypto.h"
59#include "openssl/x509.h"
60#include "openssl/x509v3.h"
61#include "openssl/pem.h"
62#include "openssl/ssl.h"
63#include "openssl/err.h"
64#include "openssl/rand.h"
65
66/* SSL error object */
67static PyObject *PySSLErrorObject;
68static PyObject *PySSLZeroReturnErrorObject;
69static PyObject *PySSLWantReadErrorObject;
70static PyObject *PySSLWantWriteErrorObject;
71static PyObject *PySSLSyscallErrorObject;
72static PyObject *PySSLEOFErrorObject;
73
74/* Error mappings */
75static PyObject *err_codes_to_names;
76static PyObject *err_names_to_codes;
77static PyObject *lib_codes_to_names;
78
79struct py_ssl_error_code {
80 const char *mnemonic;
81 int library, reason;
82};
83struct py_ssl_library_code {
84 const char *library;
85 int code;
86};
87
88/* Include generated data (error codes) */
89#include "_ssl_data.h"
90
91/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
92 http://www.openssl.org/news/changelog.html
93 */
94#if OPENSSL_VERSION_NUMBER >= 0x10001000L
95# define HAVE_TLSv1_2 1
96#else
97# define HAVE_TLSv1_2 0
98#endif
99
Antoine Pitrouce852cb2013-03-30 16:45:04 +0100100/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0.
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100101 * This includes the SSL_set_SSL_CTX() function.
102 */
103#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
104# define HAVE_SNI 1
105#else
106# define HAVE_SNI 0
107#endif
108
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000109enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000110 /* these mirror ssl.h */
111 PY_SSL_ERROR_NONE,
112 PY_SSL_ERROR_SSL,
113 PY_SSL_ERROR_WANT_READ,
114 PY_SSL_ERROR_WANT_WRITE,
115 PY_SSL_ERROR_WANT_X509_LOOKUP,
116 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
117 PY_SSL_ERROR_ZERO_RETURN,
118 PY_SSL_ERROR_WANT_CONNECT,
119 /* start of non ssl.h errorcodes */
120 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
121 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
122 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000123};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000124
Thomas Woutersed03b412007-08-28 21:37:11 +0000125enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000126 PY_SSL_CLIENT,
127 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000128};
129
130enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000131 PY_SSL_CERT_NONE,
132 PY_SSL_CERT_OPTIONAL,
133 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000134};
135
136enum py_ssl_version {
Victor Stinner3de49192011-05-09 00:42:58 +0200137#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000138 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200139#endif
140 PY_SSL_VERSION_SSL3=1,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000141 PY_SSL_VERSION_SSL23,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100142#if HAVE_TLSv1_2
143 PY_SSL_VERSION_TLS1,
144 PY_SSL_VERSION_TLS1_1,
145 PY_SSL_VERSION_TLS1_2
146#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000147 PY_SSL_VERSION_TLS1
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000148#endif
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100149};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200150
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000151#ifdef WITH_THREAD
152
153/* serves as a flag to see whether we've initialized the SSL thread support. */
154/* 0 means no, greater than 0 means yes */
155
156static unsigned int _ssl_locks_count = 0;
157
158#endif /* def WITH_THREAD */
159
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000160/* SSL socket object */
161
162#define X509_NAME_MAXLEN 256
163
164/* RAND_* APIs got added to OpenSSL in 0.9.5 */
165#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
166# define HAVE_OPENSSL_RAND 1
167#else
168# undef HAVE_OPENSSL_RAND
169#endif
170
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000171/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
172 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
173 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
174#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000175# define HAVE_SSL_CTX_CLEAR_OPTIONS
176#else
177# undef HAVE_SSL_CTX_CLEAR_OPTIONS
178#endif
179
Antoine Pitroud6494802011-07-21 01:11:30 +0200180/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
181 * older SSL, but let's be safe */
182#define PySSL_CB_MAXLEN 128
183
184/* SSL_get_finished got added to OpenSSL in 0.9.5 */
185#if OPENSSL_VERSION_NUMBER >= 0x0090500fL
186# define HAVE_OPENSSL_FINISHED 1
187#else
188# define HAVE_OPENSSL_FINISHED 0
189#endif
190
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100191/* ECDH support got added to OpenSSL in 0.9.8 */
192#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_ECDH)
193# define OPENSSL_NO_ECDH
194#endif
195
Antoine Pitrouc135fa42012-02-19 21:22:39 +0100196/* compression support got added to OpenSSL in 0.9.8 */
197#if OPENSSL_VERSION_NUMBER < 0x0090800fL && !defined(OPENSSL_NO_COMP)
198# define OPENSSL_NO_COMP
199#endif
200
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100201
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000202typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000203 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000204 SSL_CTX *ctx;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100205#ifdef OPENSSL_NPN_NEGOTIATED
206 char *npn_protocols;
207 int npn_protocols_len;
208#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100209#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200210 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100211#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000212} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000213
Antoine Pitrou152efa22010-05-16 18:19:27 +0000214typedef struct {
215 PyObject_HEAD
216 PyObject *Socket; /* weakref to socket on which we're layered */
217 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100218 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000219 X509 *peer_cert;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200220 char shutdown_seen_zero;
221 char handshake_done;
Antoine Pitroud6494802011-07-21 01:11:30 +0200222 enum py_ssl_server_or_client socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000223} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000224
Antoine Pitrou152efa22010-05-16 18:19:27 +0000225static PyTypeObject PySSLContext_Type;
226static PyTypeObject PySSLSocket_Type;
227
228static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args);
229static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args);
Thomas Woutersed03b412007-08-28 21:37:11 +0000230static int check_socket_and_wait_for_timeout(PySocketSockObject *s,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000231 int writing);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000232static PyObject *PySSL_peercert(PySSLSocket *self, PyObject *args);
233static PyObject *PySSL_cipher(PySSLSocket *self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000234
Antoine Pitrou152efa22010-05-16 18:19:27 +0000235#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
236#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000237
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000238typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000239 SOCKET_IS_NONBLOCKING,
240 SOCKET_IS_BLOCKING,
241 SOCKET_HAS_TIMED_OUT,
242 SOCKET_HAS_BEEN_CLOSED,
243 SOCKET_TOO_LARGE_FOR_SELECT,
244 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000245} timeout_state;
246
Thomas Woutersed03b412007-08-28 21:37:11 +0000247/* Wrap error strings with filename and line # */
248#define STRINGIFY1(x) #x
249#define STRINGIFY2(x) STRINGIFY1(x)
250#define ERRSTR1(x,y,z) (x ":" y ": " z)
251#define ERRSTR(x) ERRSTR1("_ssl.c", STRINGIFY2(__LINE__), x)
252
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200253
254/*
255 * SSL errors.
256 */
257
258PyDoc_STRVAR(SSLError_doc,
259"An error occurred in the SSL implementation.");
260
261PyDoc_STRVAR(SSLZeroReturnError_doc,
262"SSL/TLS session closed cleanly.");
263
264PyDoc_STRVAR(SSLWantReadError_doc,
265"Non-blocking SSL socket needs to read more data\n"
266"before the requested operation can be completed.");
267
268PyDoc_STRVAR(SSLWantWriteError_doc,
269"Non-blocking SSL socket needs to write more data\n"
270"before the requested operation can be completed.");
271
272PyDoc_STRVAR(SSLSyscallError_doc,
273"System error when attempting SSL operation.");
274
275PyDoc_STRVAR(SSLEOFError_doc,
276"SSL/TLS connection terminated abruptly.");
277
278static PyObject *
279SSLError_str(PyOSErrorObject *self)
280{
281 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
282 Py_INCREF(self->strerror);
283 return self->strerror;
284 }
285 else
286 return PyObject_Str(self->args);
287}
288
289static PyType_Slot sslerror_type_slots[] = {
290 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
291 {Py_tp_doc, SSLError_doc},
292 {Py_tp_str, SSLError_str},
293 {0, 0},
294};
295
296static PyType_Spec sslerror_type_spec = {
297 "ssl.SSLError",
298 sizeof(PyOSErrorObject),
299 0,
300 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
301 sslerror_type_slots
302};
303
304static void
305fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
306 int lineno, unsigned long errcode)
307{
308 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
309 PyObject *init_value, *msg, *key;
310 _Py_IDENTIFIER(reason);
311 _Py_IDENTIFIER(library);
312
313 if (errcode != 0) {
314 int lib, reason;
315
316 lib = ERR_GET_LIB(errcode);
317 reason = ERR_GET_REASON(errcode);
318 key = Py_BuildValue("ii", lib, reason);
319 if (key == NULL)
320 goto fail;
321 reason_obj = PyDict_GetItem(err_codes_to_names, key);
322 Py_DECREF(key);
323 if (reason_obj == NULL) {
324 /* XXX if reason < 100, it might reflect a library number (!!) */
325 PyErr_Clear();
326 }
327 key = PyLong_FromLong(lib);
328 if (key == NULL)
329 goto fail;
330 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
331 Py_DECREF(key);
332 if (lib_obj == NULL) {
333 PyErr_Clear();
334 }
335 if (errstr == NULL)
336 errstr = ERR_reason_error_string(errcode);
337 }
338 if (errstr == NULL)
339 errstr = "unknown error";
340
341 if (reason_obj && lib_obj)
342 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
343 lib_obj, reason_obj, errstr, lineno);
344 else if (lib_obj)
345 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
346 lib_obj, errstr, lineno);
347 else
348 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
349
350 if (msg == NULL)
351 goto fail;
352 init_value = Py_BuildValue("iN", ssl_errno, msg);
353 err_value = PyObject_CallObject(type, init_value);
354 Py_DECREF(init_value);
355 if (err_value == NULL)
356 goto fail;
357 if (reason_obj == NULL)
358 reason_obj = Py_None;
359 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
360 goto fail;
361 if (lib_obj == NULL)
362 lib_obj = Py_None;
363 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
364 goto fail;
365 PyErr_SetObject(type, err_value);
366fail:
367 Py_XDECREF(err_value);
368}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000369
370static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000371PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000372{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200373 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200374 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000375 int err;
376 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200377 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000378
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000379 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200380 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000381
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000382 if (obj->ssl != NULL) {
383 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000384
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000385 switch (err) {
386 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200387 errstr = "TLS/SSL connection has been closed (EOF)";
388 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000389 p = PY_SSL_ERROR_ZERO_RETURN;
390 break;
391 case SSL_ERROR_WANT_READ:
392 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200393 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000394 p = PY_SSL_ERROR_WANT_READ;
395 break;
396 case SSL_ERROR_WANT_WRITE:
397 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200398 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000399 errstr = "The operation did not complete (write)";
400 break;
401 case SSL_ERROR_WANT_X509_LOOKUP:
402 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000403 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000404 break;
405 case SSL_ERROR_WANT_CONNECT:
406 p = PY_SSL_ERROR_WANT_CONNECT;
407 errstr = "The operation did not complete (connect)";
408 break;
409 case SSL_ERROR_SYSCALL:
410 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000411 if (e == 0) {
412 PySocketSockObject *s
413 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
414 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000415 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200416 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000417 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000418 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000419 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000420 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000421 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200422 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000423 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200424 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000425 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000426 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200427 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000428 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000429 }
430 } else {
431 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000432 }
433 break;
434 }
435 case SSL_ERROR_SSL:
436 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000437 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200438 if (e == 0)
439 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000440 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000441 break;
442 }
443 default:
444 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
445 errstr = "Invalid error code";
446 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000447 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200448 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000449 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000450 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000451}
452
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000453static PyObject *
454_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
455
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200456 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000457 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200458 else
459 errcode = 0;
460 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000461 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000462 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000463}
464
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200465/*
466 * SSL objects
467 */
468
Antoine Pitrou152efa22010-05-16 18:19:27 +0000469static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100470newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000471 enum py_ssl_server_or_client socket_type,
472 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000473{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000474 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100475 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200476 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000477
Antoine Pitrou152efa22010-05-16 18:19:27 +0000478 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000479 if (self == NULL)
480 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000481
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000482 self->peer_cert = NULL;
483 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000484 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100485 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200486 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200487 self->handshake_done = 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100488 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000489
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000490 /* Make sure the SSL error state is initialized */
491 (void) ERR_get_state();
492 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000493
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000494 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000495 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000496 PySSL_END_ALLOW_THREADS
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100497 SSL_set_app_data(self->ssl,self);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000498 SSL_set_fd(self->ssl, sock->sock_fd);
Antoine Pitrou19fef692013-05-25 13:23:03 +0200499 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000500#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200501 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000502#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200503 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000504
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100505#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000506 if (server_hostname != NULL)
507 SSL_set_tlsext_host_name(self->ssl, server_hostname);
508#endif
509
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000510 /* If the socket is in non-blocking mode or timeout mode, set the BIO
511 * to non-blocking mode (blocking is the default)
512 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000513 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000514 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
515 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
516 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 PySSL_BEGIN_ALLOW_THREADS
519 if (socket_type == PY_SSL_CLIENT)
520 SSL_set_connect_state(self->ssl);
521 else
522 SSL_set_accept_state(self->ssl);
523 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000524
Antoine Pitroud6494802011-07-21 01:11:30 +0200525 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000526 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000527 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000528}
529
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000530/* SSL object methods */
531
Antoine Pitrou152efa22010-05-16 18:19:27 +0000532static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000533{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000534 int ret;
535 int err;
536 int sockstate, nonblocking;
537 PySocketSockObject *sock
538 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000539
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000540 if (((PyObject*)sock) == Py_None) {
541 _setSSLError("Underlying socket connection gone",
542 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
543 return NULL;
544 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000545 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000546
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000547 /* just in case the blocking state of the socket has been changed */
548 nonblocking = (sock->sock_timeout >= 0.0);
549 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
550 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000551
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000552 /* Actually negotiate SSL connection */
553 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000554 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000555 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000556 ret = SSL_do_handshake(self->ssl);
557 err = SSL_get_error(self->ssl, ret);
558 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000559 if (PyErr_CheckSignals())
560 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000561 if (err == SSL_ERROR_WANT_READ) {
562 sockstate = check_socket_and_wait_for_timeout(sock, 0);
563 } else if (err == SSL_ERROR_WANT_WRITE) {
564 sockstate = check_socket_and_wait_for_timeout(sock, 1);
565 } else {
566 sockstate = SOCKET_OPERATION_OK;
567 }
568 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000569 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000570 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000571 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000572 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
573 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000574 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000575 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000576 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
577 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000578 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000579 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000580 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
581 break;
582 }
583 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000584 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000585 if (ret < 1)
586 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000587
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000588 if (self->peer_cert)
589 X509_free (self->peer_cert);
590 PySSL_BEGIN_ALLOW_THREADS
591 self->peer_cert = SSL_get_peer_certificate(self->ssl);
592 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200593 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000594
595 Py_INCREF(Py_None);
596 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000597
598error:
599 Py_DECREF(sock);
600 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000601}
602
Thomas Woutersed03b412007-08-28 21:37:11 +0000603static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000604_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000605
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000606 char namebuf[X509_NAME_MAXLEN];
607 int buflen;
608 PyObject *name_obj;
609 PyObject *value_obj;
610 PyObject *attr;
611 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000612
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000613 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
614 if (buflen < 0) {
615 _setSSLError(NULL, 0, __FILE__, __LINE__);
616 goto fail;
617 }
618 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
619 if (name_obj == NULL)
620 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000621
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000622 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
623 if (buflen < 0) {
624 _setSSLError(NULL, 0, __FILE__, __LINE__);
625 Py_DECREF(name_obj);
626 goto fail;
627 }
628 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000629 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000630 OPENSSL_free(valuebuf);
631 if (value_obj == NULL) {
632 Py_DECREF(name_obj);
633 goto fail;
634 }
635 attr = PyTuple_New(2);
636 if (attr == NULL) {
637 Py_DECREF(name_obj);
638 Py_DECREF(value_obj);
639 goto fail;
640 }
641 PyTuple_SET_ITEM(attr, 0, name_obj);
642 PyTuple_SET_ITEM(attr, 1, value_obj);
643 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000644
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000645 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000646 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000647}
648
649static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000650_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000651{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000652 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
653 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
654 PyObject *rdnt;
655 PyObject *attr = NULL; /* tuple to hold an attribute */
656 int entry_count = X509_NAME_entry_count(xname);
657 X509_NAME_ENTRY *entry;
658 ASN1_OBJECT *name;
659 ASN1_STRING *value;
660 int index_counter;
661 int rdn_level = -1;
662 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000663
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000664 dn = PyList_New(0);
665 if (dn == NULL)
666 return NULL;
667 /* now create another tuple to hold the top-level RDN */
668 rdn = PyList_New(0);
669 if (rdn == NULL)
670 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000671
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000672 for (index_counter = 0;
673 index_counter < entry_count;
674 index_counter++)
675 {
676 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000677
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000678 /* check to see if we've gotten to a new RDN */
679 if (rdn_level >= 0) {
680 if (rdn_level != entry->set) {
681 /* yes, new RDN */
682 /* add old RDN to DN */
683 rdnt = PyList_AsTuple(rdn);
684 Py_DECREF(rdn);
685 if (rdnt == NULL)
686 goto fail0;
687 retcode = PyList_Append(dn, rdnt);
688 Py_DECREF(rdnt);
689 if (retcode < 0)
690 goto fail0;
691 /* create new RDN */
692 rdn = PyList_New(0);
693 if (rdn == NULL)
694 goto fail0;
695 }
696 }
697 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000698
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000699 /* now add this attribute to the current RDN */
700 name = X509_NAME_ENTRY_get_object(entry);
701 value = X509_NAME_ENTRY_get_data(entry);
702 attr = _create_tuple_for_attribute(name, value);
703 /*
704 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
705 entry->set,
706 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
707 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
708 */
709 if (attr == NULL)
710 goto fail1;
711 retcode = PyList_Append(rdn, attr);
712 Py_DECREF(attr);
713 if (retcode < 0)
714 goto fail1;
715 }
716 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100717 if (rdn != NULL) {
718 if (PyList_GET_SIZE(rdn) > 0) {
719 rdnt = PyList_AsTuple(rdn);
720 Py_DECREF(rdn);
721 if (rdnt == NULL)
722 goto fail0;
723 retcode = PyList_Append(dn, rdnt);
724 Py_DECREF(rdnt);
725 if (retcode < 0)
726 goto fail0;
727 }
728 else {
729 Py_DECREF(rdn);
730 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000731 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000732
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000733 /* convert list to tuple */
734 rdnt = PyList_AsTuple(dn);
735 Py_DECREF(dn);
736 if (rdnt == NULL)
737 return NULL;
738 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000739
740 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000742
743 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000744 Py_XDECREF(dn);
745 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000746}
747
748static PyObject *
749_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000750
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000751 /* this code follows the procedure outlined in
752 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
753 function to extract the STACK_OF(GENERAL_NAME),
754 then iterates through the stack to add the
755 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000756
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000757 int i, j;
758 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200759 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000760 X509_EXTENSION *ext = NULL;
761 GENERAL_NAMES *names = NULL;
762 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000763 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000764 BIO *biobuf = NULL;
765 char buf[2048];
766 char *vptr;
767 int len;
768 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000769#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000771#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000772 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000773#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000774
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000775 if (certificate == NULL)
776 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000777
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000778 /* get a memory buffer */
779 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000780
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200781 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000782 while ((i = X509_get_ext_by_NID(
783 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000784
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 if (peer_alt_names == Py_None) {
786 peer_alt_names = PyList_New(0);
787 if (peer_alt_names == NULL)
788 goto fail;
789 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000790
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000791 /* now decode the altName */
792 ext = X509_get_ext(certificate, i);
793 if(!(method = X509V3_EXT_get(ext))) {
794 PyErr_SetString
795 (PySSLErrorObject,
796 ERRSTR("No method for internalizing subjectAltName!"));
797 goto fail;
798 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000799
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000800 p = ext->value->data;
801 if (method->it)
802 names = (GENERAL_NAMES*)
803 (ASN1_item_d2i(NULL,
804 &p,
805 ext->value->length,
806 ASN1_ITEM_ptr(method->it)));
807 else
808 names = (GENERAL_NAMES*)
809 (method->d2i(NULL,
810 &p,
811 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000812
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000813 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000814 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200815 int gntype;
816 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000817
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000818 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200819 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200820 switch (gntype) {
821 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000822 /* we special-case DirName as a tuple of
823 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000824
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 t = PyTuple_New(2);
826 if (t == NULL) {
827 goto fail;
828 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 v = PyUnicode_FromString("DirName");
831 if (v == NULL) {
832 Py_DECREF(t);
833 goto fail;
834 }
835 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000836
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000837 v = _create_tuple_for_X509_NAME (name->d.dirn);
838 if (v == NULL) {
839 Py_DECREF(t);
840 goto fail;
841 }
842 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200843 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000844
Christian Heimes824f7f32013-08-17 00:54:47 +0200845 case GEN_EMAIL:
846 case GEN_DNS:
847 case GEN_URI:
848 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
849 correctly, CVE-2013-4238 */
850 t = PyTuple_New(2);
851 if (t == NULL)
852 goto fail;
853 switch (gntype) {
854 case GEN_EMAIL:
855 v = PyUnicode_FromString("email");
856 as = name->d.rfc822Name;
857 break;
858 case GEN_DNS:
859 v = PyUnicode_FromString("DNS");
860 as = name->d.dNSName;
861 break;
862 case GEN_URI:
863 v = PyUnicode_FromString("URI");
864 as = name->d.uniformResourceIdentifier;
865 break;
866 }
867 if (v == NULL) {
868 Py_DECREF(t);
869 goto fail;
870 }
871 PyTuple_SET_ITEM(t, 0, v);
872 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
873 ASN1_STRING_length(as));
874 if (v == NULL) {
875 Py_DECREF(t);
876 goto fail;
877 }
878 PyTuple_SET_ITEM(t, 1, v);
879 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000880
Christian Heimes824f7f32013-08-17 00:54:47 +0200881 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000882 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200883 switch (gntype) {
884 /* check for new general name type */
885 case GEN_OTHERNAME:
886 case GEN_X400:
887 case GEN_EDIPARTY:
888 case GEN_IPADD:
889 case GEN_RID:
890 break;
891 default:
892 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
893 "Unknown general name type %d",
894 gntype) == -1) {
895 goto fail;
896 }
897 break;
898 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000899 (void) BIO_reset(biobuf);
900 GENERAL_NAME_print(biobuf, name);
901 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
902 if (len < 0) {
903 _setSSLError(NULL, 0, __FILE__, __LINE__);
904 goto fail;
905 }
906 vptr = strchr(buf, ':');
907 if (vptr == NULL)
908 goto fail;
909 t = PyTuple_New(2);
910 if (t == NULL)
911 goto fail;
912 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
913 if (v == NULL) {
914 Py_DECREF(t);
915 goto fail;
916 }
917 PyTuple_SET_ITEM(t, 0, v);
918 v = PyUnicode_FromStringAndSize((vptr + 1),
919 (len - (vptr - buf + 1)));
920 if (v == NULL) {
921 Py_DECREF(t);
922 goto fail;
923 }
924 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200925 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000926 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000927
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000928 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000929
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 if (PyList_Append(peer_alt_names, t) < 0) {
931 Py_DECREF(t);
932 goto fail;
933 }
934 Py_DECREF(t);
935 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100936 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000937 }
938 BIO_free(biobuf);
939 if (peer_alt_names != Py_None) {
940 v = PyList_AsTuple(peer_alt_names);
941 Py_DECREF(peer_alt_names);
942 return v;
943 } else {
944 return peer_alt_names;
945 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000946
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000947
948 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000949 if (biobuf != NULL)
950 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000951
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000952 if (peer_alt_names != Py_None) {
953 Py_XDECREF(peer_alt_names);
954 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000955
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000956 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000957}
958
959static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000960_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000961
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000962 PyObject *retval = NULL;
963 BIO *biobuf = NULL;
964 PyObject *peer;
965 PyObject *peer_alt_names = NULL;
966 PyObject *issuer;
967 PyObject *version;
968 PyObject *sn_obj;
969 ASN1_INTEGER *serialNumber;
970 char buf[2048];
971 int len;
972 ASN1_TIME *notBefore, *notAfter;
973 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000974
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000975 retval = PyDict_New();
976 if (retval == NULL)
977 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000978
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000979 peer = _create_tuple_for_X509_NAME(
980 X509_get_subject_name(certificate));
981 if (peer == NULL)
982 goto fail0;
983 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
984 Py_DECREF(peer);
985 goto fail0;
986 }
987 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000988
Antoine Pitroufb046912010-11-09 20:21:19 +0000989 issuer = _create_tuple_for_X509_NAME(
990 X509_get_issuer_name(certificate));
991 if (issuer == NULL)
992 goto fail0;
993 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000994 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +0000995 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000996 }
Antoine Pitroufb046912010-11-09 20:21:19 +0000997 Py_DECREF(issuer);
998
999 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001000 if (version == NULL)
1001 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001002 if (PyDict_SetItemString(retval, "version", version) < 0) {
1003 Py_DECREF(version);
1004 goto fail0;
1005 }
1006 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001007
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001008 /* get a memory buffer */
1009 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001010
Antoine Pitroufb046912010-11-09 20:21:19 +00001011 (void) BIO_reset(biobuf);
1012 serialNumber = X509_get_serialNumber(certificate);
1013 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1014 i2a_ASN1_INTEGER(biobuf, serialNumber);
1015 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1016 if (len < 0) {
1017 _setSSLError(NULL, 0, __FILE__, __LINE__);
1018 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001019 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001020 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1021 if (sn_obj == NULL)
1022 goto fail1;
1023 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1024 Py_DECREF(sn_obj);
1025 goto fail1;
1026 }
1027 Py_DECREF(sn_obj);
1028
1029 (void) BIO_reset(biobuf);
1030 notBefore = X509_get_notBefore(certificate);
1031 ASN1_TIME_print(biobuf, notBefore);
1032 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1033 if (len < 0) {
1034 _setSSLError(NULL, 0, __FILE__, __LINE__);
1035 goto fail1;
1036 }
1037 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1038 if (pnotBefore == NULL)
1039 goto fail1;
1040 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1041 Py_DECREF(pnotBefore);
1042 goto fail1;
1043 }
1044 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001045
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001046 (void) BIO_reset(biobuf);
1047 notAfter = X509_get_notAfter(certificate);
1048 ASN1_TIME_print(biobuf, notAfter);
1049 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1050 if (len < 0) {
1051 _setSSLError(NULL, 0, __FILE__, __LINE__);
1052 goto fail1;
1053 }
1054 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1055 if (pnotAfter == NULL)
1056 goto fail1;
1057 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1058 Py_DECREF(pnotAfter);
1059 goto fail1;
1060 }
1061 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001062
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001063 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001064
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001065 peer_alt_names = _get_peer_alt_names(certificate);
1066 if (peer_alt_names == NULL)
1067 goto fail1;
1068 else if (peer_alt_names != Py_None) {
1069 if (PyDict_SetItemString(retval, "subjectAltName",
1070 peer_alt_names) < 0) {
1071 Py_DECREF(peer_alt_names);
1072 goto fail1;
1073 }
1074 Py_DECREF(peer_alt_names);
1075 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001076
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001077 BIO_free(biobuf);
1078 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001079
1080 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081 if (biobuf != NULL)
1082 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001083 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001084 Py_XDECREF(retval);
1085 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001086}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001087
Christian Heimes9a5395a2013-06-17 15:44:12 +02001088static PyObject *
1089_certificate_to_der(X509 *certificate)
1090{
1091 unsigned char *bytes_buf = NULL;
1092 int len;
1093 PyObject *retval;
1094
1095 bytes_buf = NULL;
1096 len = i2d_X509(certificate, &bytes_buf);
1097 if (len < 0) {
1098 _setSSLError(NULL, 0, __FILE__, __LINE__);
1099 return NULL;
1100 }
1101 /* this is actually an immutable bytes sequence */
1102 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1103 OPENSSL_free(bytes_buf);
1104 return retval;
1105}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001106
1107static PyObject *
1108PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1109
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001111 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 X509 *x=NULL;
1113 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001114
Antoine Pitroufb046912010-11-09 20:21:19 +00001115 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1116 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001117 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001118
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001119 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1120 PyErr_SetString(PySSLErrorObject,
1121 "Can't malloc memory to read file");
1122 goto fail0;
1123 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001124
Victor Stinner3800e1e2010-05-16 21:23:48 +00001125 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001126 PyErr_SetString(PySSLErrorObject,
1127 "Can't open file");
1128 goto fail0;
1129 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001130
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1132 if (x == NULL) {
1133 PyErr_SetString(PySSLErrorObject,
1134 "Error decoding PEM-encoded file");
1135 goto fail0;
1136 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001137
Antoine Pitroufb046912010-11-09 20:21:19 +00001138 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001139 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001140
1141 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001142 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001143 if (cert != NULL) BIO_free(cert);
1144 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001145}
1146
1147
1148static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001149PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001150{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001151 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001152 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001153
Antoine Pitrou721738f2012-08-15 23:20:39 +02001154 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001155 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001156
Antoine Pitrou20b85552013-09-29 19:50:53 +02001157 if (!self->handshake_done) {
1158 PyErr_SetString(PyExc_ValueError,
1159 "handshake not done yet");
1160 return NULL;
1161 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001162 if (!self->peer_cert)
1163 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001164
Antoine Pitrou721738f2012-08-15 23:20:39 +02001165 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001166 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001167 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001168 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001169 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001170 if ((verification & SSL_VERIFY_PEER) == 0)
1171 return PyDict_New();
1172 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001173 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001175}
1176
1177PyDoc_STRVAR(PySSL_peercert_doc,
1178"peer_certificate([der=False]) -> certificate\n\
1179\n\
1180Returns the certificate for the peer. If no certificate was provided,\n\
1181returns None. If a certificate was provided, but not validated, returns\n\
1182an empty dictionary. Otherwise returns a dict containing information\n\
1183about the peer certificate.\n\
1184\n\
1185If the optional argument is True, returns a DER-encoded copy of the\n\
1186peer certificate, or None if no certificate was provided. This will\n\
1187return the certificate even if it wasn't validated.");
1188
Antoine Pitrou152efa22010-05-16 18:19:27 +00001189static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001190
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001191 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001192 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001193 char *cipher_name;
1194 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001196 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001197 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001198 current = SSL_get_current_cipher(self->ssl);
1199 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001200 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001201
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001202 retval = PyTuple_New(3);
1203 if (retval == NULL)
1204 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001205
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001206 cipher_name = (char *) SSL_CIPHER_get_name(current);
1207 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001208 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001209 PyTuple_SET_ITEM(retval, 0, Py_None);
1210 } else {
1211 v = PyUnicode_FromString(cipher_name);
1212 if (v == NULL)
1213 goto fail0;
1214 PyTuple_SET_ITEM(retval, 0, v);
1215 }
1216 cipher_protocol = SSL_CIPHER_get_version(current);
1217 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001218 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001219 PyTuple_SET_ITEM(retval, 1, Py_None);
1220 } else {
1221 v = PyUnicode_FromString(cipher_protocol);
1222 if (v == NULL)
1223 goto fail0;
1224 PyTuple_SET_ITEM(retval, 1, v);
1225 }
1226 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1227 if (v == NULL)
1228 goto fail0;
1229 PyTuple_SET_ITEM(retval, 2, v);
1230 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001231
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001232 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001233 Py_DECREF(retval);
1234 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001235}
1236
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001237#ifdef OPENSSL_NPN_NEGOTIATED
1238static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1239 const unsigned char *out;
1240 unsigned int outlen;
1241
Victor Stinner4569cd52013-06-23 14:58:43 +02001242 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001243 &out, &outlen);
1244
1245 if (out == NULL)
1246 Py_RETURN_NONE;
1247 return PyUnicode_FromStringAndSize((char *) out, outlen);
1248}
1249#endif
1250
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001251static PyObject *PySSL_compression(PySSLSocket *self) {
1252#ifdef OPENSSL_NO_COMP
1253 Py_RETURN_NONE;
1254#else
1255 const COMP_METHOD *comp_method;
1256 const char *short_name;
1257
1258 if (self->ssl == NULL)
1259 Py_RETURN_NONE;
1260 comp_method = SSL_get_current_compression(self->ssl);
1261 if (comp_method == NULL || comp_method->type == NID_undef)
1262 Py_RETURN_NONE;
1263 short_name = OBJ_nid2sn(comp_method->type);
1264 if (short_name == NULL)
1265 Py_RETURN_NONE;
1266 return PyUnicode_DecodeFSDefault(short_name);
1267#endif
1268}
1269
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001270static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1271 Py_INCREF(self->ctx);
1272 return self->ctx;
1273}
1274
1275static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1276 void *closure) {
1277
1278 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001279#if !HAVE_SNI
1280 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1281 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001282 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001283#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001284 Py_INCREF(value);
1285 Py_DECREF(self->ctx);
1286 self->ctx = (PySSLContext *) value;
1287 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001288#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001289 } else {
1290 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1291 return -1;
1292 }
1293
1294 return 0;
1295}
1296
1297PyDoc_STRVAR(PySSL_set_context_doc,
1298"_setter_context(ctx)\n\
1299\
1300This changes the context associated with the SSLSocket. This is typically\n\
1301used from within a callback function set by the set_servername_callback\n\
1302on the SSLContext to change the certificate information associated with the\n\
1303SSLSocket before the cryptographic exchange handshake messages\n");
1304
1305
1306
Antoine Pitrou152efa22010-05-16 18:19:27 +00001307static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001308{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001309 if (self->peer_cert) /* Possible not to have one? */
1310 X509_free (self->peer_cert);
1311 if (self->ssl)
1312 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001313 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001314 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001315 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001316}
1317
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001318/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001319 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001320 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001321 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001322
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001323static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001324check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001325{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001326 fd_set fds;
1327 struct timeval tv;
1328 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001329
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1331 if (s->sock_timeout < 0.0)
1332 return SOCKET_IS_BLOCKING;
1333 else if (s->sock_timeout == 0.0)
1334 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001335
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001336 /* Guard against closed socket */
1337 if (s->sock_fd < 0)
1338 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001339
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 /* Prefer poll, if available, since you can poll() any fd
1341 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001342#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001343 {
1344 struct pollfd pollfd;
1345 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001346
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001347 pollfd.fd = s->sock_fd;
1348 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001349
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001350 /* s->sock_timeout is in seconds, timeout in ms */
1351 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1352 PySSL_BEGIN_ALLOW_THREADS
1353 rc = poll(&pollfd, 1, timeout);
1354 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001355
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001356 goto normal_return;
1357 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001358#endif
1359
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001360 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001361 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001362 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001363
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 /* Construct the arguments to select */
1365 tv.tv_sec = (int)s->sock_timeout;
1366 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1367 FD_ZERO(&fds);
1368 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001369
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 /* See if the socket is ready */
1371 PySSL_BEGIN_ALLOW_THREADS
1372 if (writing)
1373 rc = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
1374 else
1375 rc = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
1376 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001377
Bill Janssen6e027db2007-11-15 22:23:56 +00001378#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001379normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001380#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001381 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1382 (when we are able to write or when there's something to read) */
1383 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001384}
1385
Antoine Pitrou152efa22010-05-16 18:19:27 +00001386static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001387{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001388 Py_buffer buf;
1389 int len;
1390 int sockstate;
1391 int err;
1392 int nonblocking;
1393 PySocketSockObject *sock
1394 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001395
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001396 if (((PyObject*)sock) == Py_None) {
1397 _setSSLError("Underlying socket connection gone",
1398 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1399 return NULL;
1400 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001401 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001402
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001403 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1404 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001405 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001406 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001407
Victor Stinner6efa9652013-06-25 00:42:31 +02001408 if (buf.len > INT_MAX) {
1409 PyErr_Format(PyExc_OverflowError,
1410 "string longer than %d bytes", INT_MAX);
1411 goto error;
1412 }
1413
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001414 /* just in case the blocking state of the socket has been changed */
1415 nonblocking = (sock->sock_timeout >= 0.0);
1416 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1417 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1418
1419 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1420 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001421 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001422 "The write operation timed out");
1423 goto error;
1424 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1425 PyErr_SetString(PySSLErrorObject,
1426 "Underlying socket has been closed.");
1427 goto error;
1428 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1429 PyErr_SetString(PySSLErrorObject,
1430 "Underlying socket too large for select().");
1431 goto error;
1432 }
1433 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001434 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001435 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001436 err = SSL_get_error(self->ssl, len);
1437 PySSL_END_ALLOW_THREADS
1438 if (PyErr_CheckSignals()) {
1439 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001440 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001441 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001442 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001443 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001444 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001445 } else {
1446 sockstate = SOCKET_OPERATION_OK;
1447 }
1448 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001449 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001450 "The write operation timed out");
1451 goto error;
1452 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1453 PyErr_SetString(PySSLErrorObject,
1454 "Underlying socket has been closed.");
1455 goto error;
1456 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1457 break;
1458 }
1459 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001460
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001461 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001462 PyBuffer_Release(&buf);
1463 if (len > 0)
1464 return PyLong_FromLong(len);
1465 else
1466 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001467
1468error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001469 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001470 PyBuffer_Release(&buf);
1471 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001472}
1473
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001474PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001475"write(s) -> len\n\
1476\n\
1477Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001478of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001479
Antoine Pitrou152efa22010-05-16 18:19:27 +00001480static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001481{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001482 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001483
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001484 PySSL_BEGIN_ALLOW_THREADS
1485 count = SSL_pending(self->ssl);
1486 PySSL_END_ALLOW_THREADS
1487 if (count < 0)
1488 return PySSL_SetError(self, count, __FILE__, __LINE__);
1489 else
1490 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001491}
1492
1493PyDoc_STRVAR(PySSL_SSLpending_doc,
1494"pending() -> count\n\
1495\n\
1496Returns the number of already decrypted bytes available for read,\n\
1497pending on the connection.\n");
1498
Antoine Pitrou152efa22010-05-16 18:19:27 +00001499static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001500{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001501 PyObject *dest = NULL;
1502 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001503 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001504 int len, count;
1505 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001506 int sockstate;
1507 int err;
1508 int nonblocking;
1509 PySocketSockObject *sock
1510 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001511
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001512 if (((PyObject*)sock) == Py_None) {
1513 _setSSLError("Underlying socket connection gone",
1514 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1515 return NULL;
1516 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001517 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001518
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001519 buf.obj = NULL;
1520 buf.buf = NULL;
1521 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001522 goto error;
1523
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001524 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1525 dest = PyBytes_FromStringAndSize(NULL, len);
1526 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001527 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001528 mem = PyBytes_AS_STRING(dest);
1529 }
1530 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001531 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001532 mem = buf.buf;
1533 if (len <= 0 || len > buf.len) {
1534 len = (int) buf.len;
1535 if (buf.len != len) {
1536 PyErr_SetString(PyExc_OverflowError,
1537 "maximum length can't fit in a C 'int'");
1538 goto error;
1539 }
1540 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001541 }
1542
1543 /* just in case the blocking state of the socket has been changed */
1544 nonblocking = (sock->sock_timeout >= 0.0);
1545 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1546 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1547
1548 /* first check if there are bytes ready to be read */
1549 PySSL_BEGIN_ALLOW_THREADS
1550 count = SSL_pending(self->ssl);
1551 PySSL_END_ALLOW_THREADS
1552
1553 if (!count) {
1554 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1555 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001556 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001557 "The read operation timed out");
1558 goto error;
1559 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1560 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001561 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001562 goto error;
1563 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1564 count = 0;
1565 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001566 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001567 }
1568 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001569 PySSL_BEGIN_ALLOW_THREADS
1570 count = SSL_read(self->ssl, mem, len);
1571 err = SSL_get_error(self->ssl, count);
1572 PySSL_END_ALLOW_THREADS
1573 if (PyErr_CheckSignals())
1574 goto error;
1575 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001576 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001577 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001578 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001579 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1580 (SSL_get_shutdown(self->ssl) ==
1581 SSL_RECEIVED_SHUTDOWN))
1582 {
1583 count = 0;
1584 goto done;
1585 } else {
1586 sockstate = SOCKET_OPERATION_OK;
1587 }
1588 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001589 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001590 "The read operation timed out");
1591 goto error;
1592 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1593 break;
1594 }
1595 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1596 if (count <= 0) {
1597 PySSL_SetError(self, count, __FILE__, __LINE__);
1598 goto error;
1599 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001600
1601done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001602 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001603 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001604 _PyBytes_Resize(&dest, count);
1605 return dest;
1606 }
1607 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001608 PyBuffer_Release(&buf);
1609 return PyLong_FromLong(count);
1610 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001611
1612error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001613 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001614 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001615 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001616 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001617 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001618 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001619}
1620
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001621PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001622"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001623\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001624Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001625
Antoine Pitrou152efa22010-05-16 18:19:27 +00001626static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001627{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001628 int err, ssl_err, sockstate, nonblocking;
1629 int zeros = 0;
1630 PySocketSockObject *sock
1631 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001632
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001633 /* Guard against closed socket */
1634 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1635 _setSSLError("Underlying socket connection gone",
1636 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1637 return NULL;
1638 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001639 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001640
1641 /* Just in case the blocking state of the socket has been changed */
1642 nonblocking = (sock->sock_timeout >= 0.0);
1643 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1644 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1645
1646 while (1) {
1647 PySSL_BEGIN_ALLOW_THREADS
1648 /* Disable read-ahead so that unwrap can work correctly.
1649 * Otherwise OpenSSL might read in too much data,
1650 * eating clear text data that happens to be
1651 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001652 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001653 * function is used and the shutdown_seen_zero != 0
1654 * condition is met.
1655 */
1656 if (self->shutdown_seen_zero)
1657 SSL_set_read_ahead(self->ssl, 0);
1658 err = SSL_shutdown(self->ssl);
1659 PySSL_END_ALLOW_THREADS
1660 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1661 if (err > 0)
1662 break;
1663 if (err == 0) {
1664 /* Don't loop endlessly; instead preserve legacy
1665 behaviour of trying SSL_shutdown() only twice.
1666 This looks necessary for OpenSSL < 0.9.8m */
1667 if (++zeros > 1)
1668 break;
1669 /* Shutdown was sent, now try receiving */
1670 self->shutdown_seen_zero = 1;
1671 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001672 }
1673
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001674 /* Possibly retry shutdown until timeout or failure */
1675 ssl_err = SSL_get_error(self->ssl, err);
1676 if (ssl_err == SSL_ERROR_WANT_READ)
1677 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1678 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1679 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1680 else
1681 break;
1682 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1683 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001684 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001685 "The read operation timed out");
1686 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001687 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001688 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001689 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001690 }
1691 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1692 PyErr_SetString(PySSLErrorObject,
1693 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001694 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001695 }
1696 else if (sockstate != SOCKET_OPERATION_OK)
1697 /* Retain the SSL error code */
1698 break;
1699 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001700
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001701 if (err < 0) {
1702 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001703 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001704 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001705 else
1706 /* It's already INCREF'ed */
1707 return (PyObject *) sock;
1708
1709error:
1710 Py_DECREF(sock);
1711 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001712}
1713
1714PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1715"shutdown(s) -> socket\n\
1716\n\
1717Does the SSL shutdown handshake with the remote end, and returns\n\
1718the underlying socket object.");
1719
Antoine Pitroud6494802011-07-21 01:11:30 +02001720#if HAVE_OPENSSL_FINISHED
1721static PyObject *
1722PySSL_tls_unique_cb(PySSLSocket *self)
1723{
1724 PyObject *retval = NULL;
1725 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001726 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001727
1728 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1729 /* if session is resumed XOR we are the client */
1730 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1731 }
1732 else {
1733 /* if a new session XOR we are the server */
1734 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1735 }
1736
1737 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001738 if (len == 0)
1739 Py_RETURN_NONE;
1740
1741 retval = PyBytes_FromStringAndSize(buf, len);
1742
1743 return retval;
1744}
1745
1746PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1747"tls_unique_cb() -> bytes\n\
1748\n\
1749Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1750\n\
1751If the TLS handshake is not yet complete, None is returned");
1752
1753#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001754
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001755static PyGetSetDef ssl_getsetlist[] = {
1756 {"context", (getter) PySSL_get_context,
1757 (setter) PySSL_set_context, PySSL_set_context_doc},
1758 {NULL}, /* sentinel */
1759};
1760
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001761static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001762 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1763 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1764 PySSL_SSLwrite_doc},
1765 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1766 PySSL_SSLread_doc},
1767 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1768 PySSL_SSLpending_doc},
1769 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1770 PySSL_peercert_doc},
1771 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001772#ifdef OPENSSL_NPN_NEGOTIATED
1773 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1774#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001775 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001776 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1777 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001778#if HAVE_OPENSSL_FINISHED
1779 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1780 PySSL_tls_unique_cb_doc},
1781#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001782 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001783};
1784
Antoine Pitrou152efa22010-05-16 18:19:27 +00001785static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001786 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001787 "_ssl._SSLSocket", /*tp_name*/
1788 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001789 0, /*tp_itemsize*/
1790 /* methods */
1791 (destructor)PySSL_dealloc, /*tp_dealloc*/
1792 0, /*tp_print*/
1793 0, /*tp_getattr*/
1794 0, /*tp_setattr*/
1795 0, /*tp_reserved*/
1796 0, /*tp_repr*/
1797 0, /*tp_as_number*/
1798 0, /*tp_as_sequence*/
1799 0, /*tp_as_mapping*/
1800 0, /*tp_hash*/
1801 0, /*tp_call*/
1802 0, /*tp_str*/
1803 0, /*tp_getattro*/
1804 0, /*tp_setattro*/
1805 0, /*tp_as_buffer*/
1806 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1807 0, /*tp_doc*/
1808 0, /*tp_traverse*/
1809 0, /*tp_clear*/
1810 0, /*tp_richcompare*/
1811 0, /*tp_weaklistoffset*/
1812 0, /*tp_iter*/
1813 0, /*tp_iternext*/
1814 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001815 0, /*tp_members*/
1816 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001817};
1818
Antoine Pitrou152efa22010-05-16 18:19:27 +00001819
1820/*
1821 * _SSLContext objects
1822 */
1823
1824static PyObject *
1825context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1826{
1827 char *kwlist[] = {"protocol", NULL};
1828 PySSLContext *self;
1829 int proto_version = PY_SSL_VERSION_SSL23;
1830 SSL_CTX *ctx = NULL;
1831
1832 if (!PyArg_ParseTupleAndKeywords(
1833 args, kwds, "i:_SSLContext", kwlist,
1834 &proto_version))
1835 return NULL;
1836
1837 PySSL_BEGIN_ALLOW_THREADS
1838 if (proto_version == PY_SSL_VERSION_TLS1)
1839 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01001840#if HAVE_TLSv1_2
1841 else if (proto_version == PY_SSL_VERSION_TLS1_1)
1842 ctx = SSL_CTX_new(TLSv1_1_method());
1843 else if (proto_version == PY_SSL_VERSION_TLS1_2)
1844 ctx = SSL_CTX_new(TLSv1_2_method());
1845#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001846 else if (proto_version == PY_SSL_VERSION_SSL3)
1847 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001848#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001849 else if (proto_version == PY_SSL_VERSION_SSL2)
1850 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001851#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001852 else if (proto_version == PY_SSL_VERSION_SSL23)
1853 ctx = SSL_CTX_new(SSLv23_method());
1854 else
1855 proto_version = -1;
1856 PySSL_END_ALLOW_THREADS
1857
1858 if (proto_version == -1) {
1859 PyErr_SetString(PyExc_ValueError,
1860 "invalid protocol version");
1861 return NULL;
1862 }
1863 if (ctx == NULL) {
1864 PyErr_SetString(PySSLErrorObject,
1865 "failed to allocate SSL context");
1866 return NULL;
1867 }
1868
1869 assert(type != NULL && type->tp_alloc != NULL);
1870 self = (PySSLContext *) type->tp_alloc(type, 0);
1871 if (self == NULL) {
1872 SSL_CTX_free(ctx);
1873 return NULL;
1874 }
1875 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001876#ifdef OPENSSL_NPN_NEGOTIATED
1877 self->npn_protocols = NULL;
1878#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001879#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02001880 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001881#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001882 /* Defaults */
1883 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001884 SSL_CTX_set_options(self->ctx,
1885 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001886
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001887#define SID_CTX "Python"
1888 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1889 sizeof(SID_CTX));
1890#undef SID_CTX
1891
Antoine Pitrou152efa22010-05-16 18:19:27 +00001892 return (PyObject *)self;
1893}
1894
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001895static int
1896context_traverse(PySSLContext *self, visitproc visit, void *arg)
1897{
1898#ifndef OPENSSL_NO_TLSEXT
1899 Py_VISIT(self->set_hostname);
1900#endif
1901 return 0;
1902}
1903
1904static int
1905context_clear(PySSLContext *self)
1906{
1907#ifndef OPENSSL_NO_TLSEXT
1908 Py_CLEAR(self->set_hostname);
1909#endif
1910 return 0;
1911}
1912
Antoine Pitrou152efa22010-05-16 18:19:27 +00001913static void
1914context_dealloc(PySSLContext *self)
1915{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001916 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001917 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001918#ifdef OPENSSL_NPN_NEGOTIATED
1919 PyMem_Free(self->npn_protocols);
1920#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001921 Py_TYPE(self)->tp_free(self);
1922}
1923
1924static PyObject *
1925set_ciphers(PySSLContext *self, PyObject *args)
1926{
1927 int ret;
1928 const char *cipherlist;
1929
1930 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1931 return NULL;
1932 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1933 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001934 /* Clearing the error queue is necessary on some OpenSSL versions,
1935 otherwise the error will be reported again when another SSL call
1936 is done. */
1937 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001938 PyErr_SetString(PySSLErrorObject,
1939 "No cipher can be selected.");
1940 return NULL;
1941 }
1942 Py_RETURN_NONE;
1943}
1944
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001945#ifdef OPENSSL_NPN_NEGOTIATED
1946/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1947static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001948_advertiseNPN_cb(SSL *s,
1949 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001950 void *args)
1951{
1952 PySSLContext *ssl_ctx = (PySSLContext *) args;
1953
1954 if (ssl_ctx->npn_protocols == NULL) {
1955 *data = (unsigned char *) "";
1956 *len = 0;
1957 } else {
1958 *data = (unsigned char *) ssl_ctx->npn_protocols;
1959 *len = ssl_ctx->npn_protocols_len;
1960 }
1961
1962 return SSL_TLSEXT_ERR_OK;
1963}
1964/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1965static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001966_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001967 unsigned char **out, unsigned char *outlen,
1968 const unsigned char *server, unsigned int server_len,
1969 void *args)
1970{
1971 PySSLContext *ssl_ctx = (PySSLContext *) args;
1972
1973 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1974 int client_len;
1975
1976 if (client == NULL) {
1977 client = (unsigned char *) "";
1978 client_len = 0;
1979 } else {
1980 client_len = ssl_ctx->npn_protocols_len;
1981 }
1982
1983 SSL_select_next_proto(out, outlen,
1984 server, server_len,
1985 client, client_len);
1986
1987 return SSL_TLSEXT_ERR_OK;
1988}
1989#endif
1990
1991static PyObject *
1992_set_npn_protocols(PySSLContext *self, PyObject *args)
1993{
1994#ifdef OPENSSL_NPN_NEGOTIATED
1995 Py_buffer protos;
1996
1997 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
1998 return NULL;
1999
Christian Heimes5cb31c92012-09-20 12:42:54 +02002000 if (self->npn_protocols != NULL) {
2001 PyMem_Free(self->npn_protocols);
2002 }
2003
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002004 self->npn_protocols = PyMem_Malloc(protos.len);
2005 if (self->npn_protocols == NULL) {
2006 PyBuffer_Release(&protos);
2007 return PyErr_NoMemory();
2008 }
2009 memcpy(self->npn_protocols, protos.buf, protos.len);
2010 self->npn_protocols_len = (int) protos.len;
2011
2012 /* set both server and client callbacks, because the context can
2013 * be used to create both types of sockets */
2014 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2015 _advertiseNPN_cb,
2016 self);
2017 SSL_CTX_set_next_proto_select_cb(self->ctx,
2018 _selectNPN_cb,
2019 self);
2020
2021 PyBuffer_Release(&protos);
2022 Py_RETURN_NONE;
2023#else
2024 PyErr_SetString(PyExc_NotImplementedError,
2025 "The NPN extension requires OpenSSL 1.0.1 or later.");
2026 return NULL;
2027#endif
2028}
2029
Antoine Pitrou152efa22010-05-16 18:19:27 +00002030static PyObject *
2031get_verify_mode(PySSLContext *self, void *c)
2032{
2033 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2034 case SSL_VERIFY_NONE:
2035 return PyLong_FromLong(PY_SSL_CERT_NONE);
2036 case SSL_VERIFY_PEER:
2037 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2038 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2039 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2040 }
2041 PyErr_SetString(PySSLErrorObject,
2042 "invalid return value from SSL_CTX_get_verify_mode");
2043 return NULL;
2044}
2045
2046static int
2047set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2048{
2049 int n, mode;
2050 if (!PyArg_Parse(arg, "i", &n))
2051 return -1;
2052 if (n == PY_SSL_CERT_NONE)
2053 mode = SSL_VERIFY_NONE;
2054 else if (n == PY_SSL_CERT_OPTIONAL)
2055 mode = SSL_VERIFY_PEER;
2056 else if (n == PY_SSL_CERT_REQUIRED)
2057 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2058 else {
2059 PyErr_SetString(PyExc_ValueError,
2060 "invalid value for verify_mode");
2061 return -1;
2062 }
2063 SSL_CTX_set_verify(self->ctx, mode, NULL);
2064 return 0;
2065}
2066
2067static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002068get_options(PySSLContext *self, void *c)
2069{
2070 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2071}
2072
2073static int
2074set_options(PySSLContext *self, PyObject *arg, void *c)
2075{
2076 long new_opts, opts, set, clear;
2077 if (!PyArg_Parse(arg, "l", &new_opts))
2078 return -1;
2079 opts = SSL_CTX_get_options(self->ctx);
2080 clear = opts & ~new_opts;
2081 set = ~opts & new_opts;
2082 if (clear) {
2083#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2084 SSL_CTX_clear_options(self->ctx, clear);
2085#else
2086 PyErr_SetString(PyExc_ValueError,
2087 "can't clear options before OpenSSL 0.9.8m");
2088 return -1;
2089#endif
2090 }
2091 if (set)
2092 SSL_CTX_set_options(self->ctx, set);
2093 return 0;
2094}
2095
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002096typedef struct {
2097 PyThreadState *thread_state;
2098 PyObject *callable;
2099 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002100 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002101 int error;
2102} _PySSLPasswordInfo;
2103
2104static int
2105_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2106 const char *bad_type_error)
2107{
2108 /* Set the password and size fields of a _PySSLPasswordInfo struct
2109 from a unicode, bytes, or byte array object.
2110 The password field will be dynamically allocated and must be freed
2111 by the caller */
2112 PyObject *password_bytes = NULL;
2113 const char *data = NULL;
2114 Py_ssize_t size;
2115
2116 if (PyUnicode_Check(password)) {
2117 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2118 if (!password_bytes) {
2119 goto error;
2120 }
2121 data = PyBytes_AS_STRING(password_bytes);
2122 size = PyBytes_GET_SIZE(password_bytes);
2123 } else if (PyBytes_Check(password)) {
2124 data = PyBytes_AS_STRING(password);
2125 size = PyBytes_GET_SIZE(password);
2126 } else if (PyByteArray_Check(password)) {
2127 data = PyByteArray_AS_STRING(password);
2128 size = PyByteArray_GET_SIZE(password);
2129 } else {
2130 PyErr_SetString(PyExc_TypeError, bad_type_error);
2131 goto error;
2132 }
2133
Victor Stinner9ee02032013-06-23 15:08:23 +02002134 if (size > (Py_ssize_t)INT_MAX) {
2135 PyErr_Format(PyExc_ValueError,
2136 "password cannot be longer than %d bytes", INT_MAX);
2137 goto error;
2138 }
2139
Victor Stinner11ebff22013-07-07 17:07:52 +02002140 PyMem_Free(pw_info->password);
2141 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002142 if (!pw_info->password) {
2143 PyErr_SetString(PyExc_MemoryError,
2144 "unable to allocate password buffer");
2145 goto error;
2146 }
2147 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002148 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002149
2150 Py_XDECREF(password_bytes);
2151 return 1;
2152
2153error:
2154 Py_XDECREF(password_bytes);
2155 return 0;
2156}
2157
2158static int
2159_password_callback(char *buf, int size, int rwflag, void *userdata)
2160{
2161 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2162 PyObject *fn_ret = NULL;
2163
2164 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2165
2166 if (pw_info->callable) {
2167 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2168 if (!fn_ret) {
2169 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2170 core python API, so we could use it to add a frame here */
2171 goto error;
2172 }
2173
2174 if (!_pwinfo_set(pw_info, fn_ret,
2175 "password callback must return a string")) {
2176 goto error;
2177 }
2178 Py_CLEAR(fn_ret);
2179 }
2180
2181 if (pw_info->size > size) {
2182 PyErr_Format(PyExc_ValueError,
2183 "password cannot be longer than %d bytes", size);
2184 goto error;
2185 }
2186
2187 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2188 memcpy(buf, pw_info->password, pw_info->size);
2189 return pw_info->size;
2190
2191error:
2192 Py_XDECREF(fn_ret);
2193 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2194 pw_info->error = 1;
2195 return -1;
2196}
2197
Antoine Pitroub5218772010-05-21 09:56:06 +00002198static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002199load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2200{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002201 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2202 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002203 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002204 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2205 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2206 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002207 int r;
2208
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002209 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002210 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002211 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002212 "O|OO:load_cert_chain", kwlist,
2213 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002214 return NULL;
2215 if (keyfile == Py_None)
2216 keyfile = NULL;
2217 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2218 PyErr_SetString(PyExc_TypeError,
2219 "certfile should be a valid filesystem path");
2220 return NULL;
2221 }
2222 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2223 PyErr_SetString(PyExc_TypeError,
2224 "keyfile should be a valid filesystem path");
2225 goto error;
2226 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002227 if (password && password != Py_None) {
2228 if (PyCallable_Check(password)) {
2229 pw_info.callable = password;
2230 } else if (!_pwinfo_set(&pw_info, password,
2231 "password should be a string or callable")) {
2232 goto error;
2233 }
2234 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2235 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2236 }
2237 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002238 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2239 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002240 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002241 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002242 if (pw_info.error) {
2243 ERR_clear_error();
2244 /* the password callback has already set the error information */
2245 }
2246 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002247 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002248 PyErr_SetFromErrno(PyExc_IOError);
2249 }
2250 else {
2251 _setSSLError(NULL, 0, __FILE__, __LINE__);
2252 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002253 goto error;
2254 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002255 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002256 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002257 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2258 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002259 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2260 Py_CLEAR(keyfile_bytes);
2261 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002262 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002263 if (pw_info.error) {
2264 ERR_clear_error();
2265 /* the password callback has already set the error information */
2266 }
2267 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002268 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002269 PyErr_SetFromErrno(PyExc_IOError);
2270 }
2271 else {
2272 _setSSLError(NULL, 0, __FILE__, __LINE__);
2273 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002274 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002275 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002276 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002277 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002278 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002279 if (r != 1) {
2280 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002281 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002282 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002283 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2284 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002285 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002286 Py_RETURN_NONE;
2287
2288error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002289 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2290 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002291 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002292 Py_XDECREF(keyfile_bytes);
2293 Py_XDECREF(certfile_bytes);
2294 return NULL;
2295}
2296
2297static PyObject *
2298load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2299{
2300 char *kwlist[] = {"cafile", "capath", NULL};
2301 PyObject *cafile = NULL, *capath = NULL;
2302 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2303 const char *cafile_buf = NULL, *capath_buf = NULL;
2304 int r;
2305
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002306 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002307 if (!PyArg_ParseTupleAndKeywords(args, kwds,
2308 "|OO:load_verify_locations", kwlist,
2309 &cafile, &capath))
2310 return NULL;
2311 if (cafile == Py_None)
2312 cafile = NULL;
2313 if (capath == Py_None)
2314 capath = NULL;
2315 if (cafile == NULL && capath == NULL) {
2316 PyErr_SetString(PyExc_TypeError,
2317 "cafile and capath cannot be both omitted");
2318 return NULL;
2319 }
2320 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2321 PyErr_SetString(PyExc_TypeError,
2322 "cafile should be a valid filesystem path");
2323 return NULL;
2324 }
2325 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Victor Stinner80f75e62011-01-29 11:31:20 +00002326 Py_XDECREF(cafile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002327 PyErr_SetString(PyExc_TypeError,
2328 "capath should be a valid filesystem path");
2329 return NULL;
2330 }
2331 if (cafile)
2332 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2333 if (capath)
2334 capath_buf = PyBytes_AS_STRING(capath_bytes);
2335 PySSL_BEGIN_ALLOW_THREADS
2336 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2337 PySSL_END_ALLOW_THREADS
2338 Py_XDECREF(cafile_bytes);
2339 Py_XDECREF(capath_bytes);
2340 if (r != 1) {
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002341 if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002342 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002343 PyErr_SetFromErrno(PyExc_IOError);
2344 }
2345 else {
2346 _setSSLError(NULL, 0, __FILE__, __LINE__);
2347 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002348 return NULL;
2349 }
2350 Py_RETURN_NONE;
2351}
2352
2353static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002354load_dh_params(PySSLContext *self, PyObject *filepath)
2355{
2356 FILE *f;
2357 DH *dh;
2358
Victor Stinnerdaf45552013-08-28 00:53:59 +02002359 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002360 if (f == NULL) {
2361 if (!PyErr_Occurred())
2362 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2363 return NULL;
2364 }
2365 errno = 0;
2366 PySSL_BEGIN_ALLOW_THREADS
2367 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002368 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002369 PySSL_END_ALLOW_THREADS
2370 if (dh == NULL) {
2371 if (errno != 0) {
2372 ERR_clear_error();
2373 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2374 }
2375 else {
2376 _setSSLError(NULL, 0, __FILE__, __LINE__);
2377 }
2378 return NULL;
2379 }
2380 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2381 _setSSLError(NULL, 0, __FILE__, __LINE__);
2382 DH_free(dh);
2383 Py_RETURN_NONE;
2384}
2385
2386static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002387context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2388{
Antoine Pitroud5323212010-10-22 18:19:07 +00002389 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002390 PySocketSockObject *sock;
2391 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002392 char *hostname = NULL;
2393 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002394
Antoine Pitroud5323212010-10-22 18:19:07 +00002395 /* server_hostname is either None (or absent), or to be encoded
2396 using the idna encoding. */
2397 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002398 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002399 &sock, &server_side,
2400 Py_TYPE(Py_None), &hostname_obj)) {
2401 PyErr_Clear();
2402 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2403 PySocketModule.Sock_Type,
2404 &sock, &server_side,
2405 "idna", &hostname))
2406 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002407#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002408 PyMem_Free(hostname);
2409 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2410 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002411 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002412#endif
2413 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002414
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002415 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002416 hostname);
2417 if (hostname != NULL)
2418 PyMem_Free(hostname);
2419 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002420}
2421
Antoine Pitroub0182c82010-10-12 20:09:02 +00002422static PyObject *
2423session_stats(PySSLContext *self, PyObject *unused)
2424{
2425 int r;
2426 PyObject *value, *stats = PyDict_New();
2427 if (!stats)
2428 return NULL;
2429
2430#define ADD_STATS(SSL_NAME, KEY_NAME) \
2431 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2432 if (value == NULL) \
2433 goto error; \
2434 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2435 Py_DECREF(value); \
2436 if (r < 0) \
2437 goto error;
2438
2439 ADD_STATS(number, "number");
2440 ADD_STATS(connect, "connect");
2441 ADD_STATS(connect_good, "connect_good");
2442 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2443 ADD_STATS(accept, "accept");
2444 ADD_STATS(accept_good, "accept_good");
2445 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2446 ADD_STATS(accept, "accept");
2447 ADD_STATS(hits, "hits");
2448 ADD_STATS(misses, "misses");
2449 ADD_STATS(timeouts, "timeouts");
2450 ADD_STATS(cache_full, "cache_full");
2451
2452#undef ADD_STATS
2453
2454 return stats;
2455
2456error:
2457 Py_DECREF(stats);
2458 return NULL;
2459}
2460
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002461static PyObject *
2462set_default_verify_paths(PySSLContext *self, PyObject *unused)
2463{
2464 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2465 _setSSLError(NULL, 0, __FILE__, __LINE__);
2466 return NULL;
2467 }
2468 Py_RETURN_NONE;
2469}
2470
Antoine Pitrou501da612011-12-21 09:27:41 +01002471#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002472static PyObject *
2473set_ecdh_curve(PySSLContext *self, PyObject *name)
2474{
2475 PyObject *name_bytes;
2476 int nid;
2477 EC_KEY *key;
2478
2479 if (!PyUnicode_FSConverter(name, &name_bytes))
2480 return NULL;
2481 assert(PyBytes_Check(name_bytes));
2482 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2483 Py_DECREF(name_bytes);
2484 if (nid == 0) {
2485 PyErr_Format(PyExc_ValueError,
2486 "unknown elliptic curve name %R", name);
2487 return NULL;
2488 }
2489 key = EC_KEY_new_by_curve_name(nid);
2490 if (key == NULL) {
2491 _setSSLError(NULL, 0, __FILE__, __LINE__);
2492 return NULL;
2493 }
2494 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2495 EC_KEY_free(key);
2496 Py_RETURN_NONE;
2497}
Antoine Pitrou501da612011-12-21 09:27:41 +01002498#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002499
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002500#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002501static int
2502_servername_callback(SSL *s, int *al, void *args)
2503{
2504 int ret;
2505 PySSLContext *ssl_ctx = (PySSLContext *) args;
2506 PySSLSocket *ssl;
2507 PyObject *servername_o;
2508 PyObject *servername_idna;
2509 PyObject *result;
2510 /* The high-level ssl.SSLSocket object */
2511 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002512 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002513#ifdef WITH_THREAD
2514 PyGILState_STATE gstate = PyGILState_Ensure();
2515#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002516
2517 if (ssl_ctx->set_hostname == NULL) {
2518 /* remove race condition in this the call back while if removing the
2519 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002520#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002521 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002522#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002523 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002524 }
2525
2526 ssl = SSL_get_app_data(s);
2527 assert(PySSLSocket_Check(ssl));
2528 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2529 Py_INCREF(ssl_socket);
2530 if (ssl_socket == Py_None) {
2531 goto error;
2532 }
Victor Stinner7e001512013-06-25 00:44:31 +02002533
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002534 if (servername == NULL) {
2535 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2536 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002537 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002538 else {
2539 servername_o = PyBytes_FromString(servername);
2540 if (servername_o == NULL) {
2541 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2542 goto error;
2543 }
2544 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2545 if (servername_idna == NULL) {
2546 PyErr_WriteUnraisable(servername_o);
2547 Py_DECREF(servername_o);
2548 goto error;
2549 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002550 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002551 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2552 servername_idna, ssl_ctx, NULL);
2553 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002554 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002555 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002556
2557 if (result == NULL) {
2558 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2559 *al = SSL_AD_HANDSHAKE_FAILURE;
2560 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2561 }
2562 else {
2563 if (result != Py_None) {
2564 *al = (int) PyLong_AsLong(result);
2565 if (PyErr_Occurred()) {
2566 PyErr_WriteUnraisable(result);
2567 *al = SSL_AD_INTERNAL_ERROR;
2568 }
2569 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2570 }
2571 else {
2572 ret = SSL_TLSEXT_ERR_OK;
2573 }
2574 Py_DECREF(result);
2575 }
2576
Stefan Krah20d60802013-01-17 17:07:17 +01002577#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002578 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002579#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002580 return ret;
2581
2582error:
2583 Py_DECREF(ssl_socket);
2584 *al = SSL_AD_INTERNAL_ERROR;
2585 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002586#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002587 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002588#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002589 return ret;
2590}
Antoine Pitroua5963382013-03-30 16:39:00 +01002591#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002592
2593PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2594"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002595\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002596This sets a callback that will be called when a server name is provided by\n\
2597the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002598\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002599If the argument is None then the callback is disabled. The method is called\n\
2600with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002601See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002602
2603static PyObject *
2604set_servername_callback(PySSLContext *self, PyObject *args)
2605{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002606#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002607 PyObject *cb;
2608
2609 if (!PyArg_ParseTuple(args, "O", &cb))
2610 return NULL;
2611
2612 Py_CLEAR(self->set_hostname);
2613 if (cb == Py_None) {
2614 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2615 }
2616 else {
2617 if (!PyCallable_Check(cb)) {
2618 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2619 PyErr_SetString(PyExc_TypeError,
2620 "not a callable object");
2621 return NULL;
2622 }
2623 Py_INCREF(cb);
2624 self->set_hostname = cb;
2625 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
2626 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
2627 }
2628 Py_RETURN_NONE;
2629#else
2630 PyErr_SetString(PyExc_NotImplementedError,
2631 "The TLS extension servername callback, "
2632 "SSL_CTX_set_tlsext_servername_callback, "
2633 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002634 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002635#endif
2636}
2637
Christian Heimes9a5395a2013-06-17 15:44:12 +02002638PyDoc_STRVAR(PySSL_get_stats_doc,
2639"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
2640\n\
2641Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
2642CA extension and certificate revocation lists inside the context's cert\n\
2643store.\n\
2644NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2645been used at least once.");
2646
2647static PyObject *
2648cert_store_stats(PySSLContext *self)
2649{
2650 X509_STORE *store;
2651 X509_OBJECT *obj;
2652 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
2653
2654 store = SSL_CTX_get_cert_store(self->ctx);
2655 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2656 obj = sk_X509_OBJECT_value(store->objs, i);
2657 switch (obj->type) {
2658 case X509_LU_X509:
2659 x509++;
2660 if (X509_check_ca(obj->data.x509)) {
2661 ca++;
2662 }
2663 break;
2664 case X509_LU_CRL:
2665 crl++;
2666 break;
2667 case X509_LU_PKEY:
2668 pkey++;
2669 break;
2670 default:
2671 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
2672 * As far as I can tell they are internal states and never
2673 * stored in a cert store */
2674 break;
2675 }
2676 }
2677 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
2678 "x509_ca", ca);
2679}
2680
2681PyDoc_STRVAR(PySSL_get_ca_certs_doc,
2682"get_ca_certs([der=False]) -> list of loaded certificate\n\
2683\n\
2684Returns a list of dicts with information of loaded CA certs. If the\n\
2685optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
2686NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2687been used at least once.");
2688
2689static PyObject *
2690get_ca_certs(PySSLContext *self, PyObject *args)
2691{
2692 X509_STORE *store;
2693 PyObject *ci = NULL, *rlist = NULL;
2694 int i;
2695 int binary_mode = 0;
2696
2697 if (!PyArg_ParseTuple(args, "|p:get_ca_certs", &binary_mode)) {
2698 return NULL;
2699 }
2700
2701 if ((rlist = PyList_New(0)) == NULL) {
2702 return NULL;
2703 }
2704
2705 store = SSL_CTX_get_cert_store(self->ctx);
2706 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2707 X509_OBJECT *obj;
2708 X509 *cert;
2709
2710 obj = sk_X509_OBJECT_value(store->objs, i);
2711 if (obj->type != X509_LU_X509) {
2712 /* not a x509 cert */
2713 continue;
2714 }
2715 /* CA for any purpose */
2716 cert = obj->data.x509;
2717 if (!X509_check_ca(cert)) {
2718 continue;
2719 }
2720 if (binary_mode) {
2721 ci = _certificate_to_der(cert);
2722 } else {
2723 ci = _decode_certificate(cert);
2724 }
2725 if (ci == NULL) {
2726 goto error;
2727 }
2728 if (PyList_Append(rlist, ci) == -1) {
2729 goto error;
2730 }
2731 Py_CLEAR(ci);
2732 }
2733 return rlist;
2734
2735 error:
2736 Py_XDECREF(ci);
2737 Py_XDECREF(rlist);
2738 return NULL;
2739}
2740
2741
Antoine Pitrou152efa22010-05-16 18:19:27 +00002742static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002743 {"options", (getter) get_options,
2744 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002745 {"verify_mode", (getter) get_verify_mode,
2746 (setter) set_verify_mode, NULL},
2747 {NULL}, /* sentinel */
2748};
2749
2750static struct PyMethodDef context_methods[] = {
2751 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2752 METH_VARARGS | METH_KEYWORDS, NULL},
2753 {"set_ciphers", (PyCFunction) set_ciphers,
2754 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002755 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2756 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002757 {"load_cert_chain", (PyCFunction) load_cert_chain,
2758 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002759 {"load_dh_params", (PyCFunction) load_dh_params,
2760 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002761 {"load_verify_locations", (PyCFunction) load_verify_locations,
2762 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002763 {"session_stats", (PyCFunction) session_stats,
2764 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002765 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2766 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002767#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002768 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2769 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002770#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002771 {"set_servername_callback", (PyCFunction) set_servername_callback,
2772 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02002773 {"cert_store_stats", (PyCFunction) cert_store_stats,
2774 METH_NOARGS, PySSL_get_stats_doc},
2775 {"get_ca_certs", (PyCFunction) get_ca_certs,
2776 METH_VARARGS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002777 {NULL, NULL} /* sentinel */
2778};
2779
2780static PyTypeObject PySSLContext_Type = {
2781 PyVarObject_HEAD_INIT(NULL, 0)
2782 "_ssl._SSLContext", /*tp_name*/
2783 sizeof(PySSLContext), /*tp_basicsize*/
2784 0, /*tp_itemsize*/
2785 (destructor)context_dealloc, /*tp_dealloc*/
2786 0, /*tp_print*/
2787 0, /*tp_getattr*/
2788 0, /*tp_setattr*/
2789 0, /*tp_reserved*/
2790 0, /*tp_repr*/
2791 0, /*tp_as_number*/
2792 0, /*tp_as_sequence*/
2793 0, /*tp_as_mapping*/
2794 0, /*tp_hash*/
2795 0, /*tp_call*/
2796 0, /*tp_str*/
2797 0, /*tp_getattro*/
2798 0, /*tp_setattro*/
2799 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002800 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002801 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002802 (traverseproc) context_traverse, /*tp_traverse*/
2803 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002804 0, /*tp_richcompare*/
2805 0, /*tp_weaklistoffset*/
2806 0, /*tp_iter*/
2807 0, /*tp_iternext*/
2808 context_methods, /*tp_methods*/
2809 0, /*tp_members*/
2810 context_getsetlist, /*tp_getset*/
2811 0, /*tp_base*/
2812 0, /*tp_dict*/
2813 0, /*tp_descr_get*/
2814 0, /*tp_descr_set*/
2815 0, /*tp_dictoffset*/
2816 0, /*tp_init*/
2817 0, /*tp_alloc*/
2818 context_new, /*tp_new*/
2819};
2820
2821
2822
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002823#ifdef HAVE_OPENSSL_RAND
2824
2825/* helper routines for seeding the SSL PRNG */
2826static PyObject *
2827PySSL_RAND_add(PyObject *self, PyObject *args)
2828{
2829 char *buf;
2830 int len;
2831 double entropy;
2832
2833 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002834 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002835 RAND_add(buf, len, entropy);
2836 Py_INCREF(Py_None);
2837 return Py_None;
2838}
2839
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002840PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002841"RAND_add(string, entropy)\n\
2842\n\
2843Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002844bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002845
2846static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002847PySSL_RAND(int len, int pseudo)
2848{
2849 int ok;
2850 PyObject *bytes;
2851 unsigned long err;
2852 const char *errstr;
2853 PyObject *v;
2854
2855 bytes = PyBytes_FromStringAndSize(NULL, len);
2856 if (bytes == NULL)
2857 return NULL;
2858 if (pseudo) {
2859 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2860 if (ok == 0 || ok == 1)
2861 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
2862 }
2863 else {
2864 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
2865 if (ok == 1)
2866 return bytes;
2867 }
2868 Py_DECREF(bytes);
2869
2870 err = ERR_get_error();
2871 errstr = ERR_reason_error_string(err);
2872 v = Py_BuildValue("(ks)", err, errstr);
2873 if (v != NULL) {
2874 PyErr_SetObject(PySSLErrorObject, v);
2875 Py_DECREF(v);
2876 }
2877 return NULL;
2878}
2879
2880static PyObject *
2881PySSL_RAND_bytes(PyObject *self, PyObject *args)
2882{
2883 int len;
2884 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
2885 return NULL;
2886 return PySSL_RAND(len, 0);
2887}
2888
2889PyDoc_STRVAR(PySSL_RAND_bytes_doc,
2890"RAND_bytes(n) -> bytes\n\
2891\n\
2892Generate n cryptographically strong pseudo-random bytes.");
2893
2894static PyObject *
2895PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
2896{
2897 int len;
2898 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
2899 return NULL;
2900 return PySSL_RAND(len, 1);
2901}
2902
2903PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
2904"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
2905\n\
2906Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
2907generated are cryptographically strong.");
2908
2909static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002910PySSL_RAND_status(PyObject *self)
2911{
Christian Heimes217cfd12007-12-02 14:31:20 +00002912 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002913}
2914
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002915PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002916"RAND_status() -> 0 or 1\n\
2917\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00002918Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
2919It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
2920using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002921
2922static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002923PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002924{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002925 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002926 int bytes;
2927
Jesus Ceac8754a12012-09-11 02:00:58 +02002928 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00002929 PyUnicode_FSConverter, &path))
2930 return NULL;
2931
2932 bytes = RAND_egd(PyBytes_AsString(path));
2933 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002934 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00002935 PyErr_SetString(PySSLErrorObject,
2936 "EGD connection failed or EGD did not return "
2937 "enough data to seed the PRNG");
2938 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002939 }
Christian Heimes217cfd12007-12-02 14:31:20 +00002940 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002941}
2942
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002943PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002944"RAND_egd(path) -> bytes\n\
2945\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002946Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
2947Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02002948fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002949
Christian Heimesf77b4b22013-08-21 13:26:05 +02002950#endif /* HAVE_OPENSSL_RAND */
2951
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002952
Christian Heimes6d7ad132013-06-09 18:02:55 +02002953PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
2954"get_default_verify_paths() -> tuple\n\
2955\n\
2956Return search paths and environment vars that are used by SSLContext's\n\
2957set_default_verify_paths() to load default CAs. The values are\n\
2958'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
2959
2960static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02002961PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02002962{
2963 PyObject *ofile_env = NULL;
2964 PyObject *ofile = NULL;
2965 PyObject *odir_env = NULL;
2966 PyObject *odir = NULL;
2967
2968#define convert(info, target) { \
2969 const char *tmp = (info); \
2970 target = NULL; \
2971 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
2972 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
2973 target = PyBytes_FromString(tmp); } \
2974 if (!target) goto error; \
2975 } while(0)
2976
2977 convert(X509_get_default_cert_file_env(), ofile_env);
2978 convert(X509_get_default_cert_file(), ofile);
2979 convert(X509_get_default_cert_dir_env(), odir_env);
2980 convert(X509_get_default_cert_dir(), odir);
2981#undef convert
2982
Christian Heimes200bb1b2013-06-14 15:14:29 +02002983 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02002984
2985 error:
2986 Py_XDECREF(ofile_env);
2987 Py_XDECREF(ofile);
2988 Py_XDECREF(odir_env);
2989 Py_XDECREF(odir);
2990 return NULL;
2991}
2992
Christian Heimes46bebee2013-06-09 19:03:31 +02002993#ifdef _MSC_VER
2994PyDoc_STRVAR(PySSL_enum_cert_store_doc,
2995"enum_cert_store(store_name, cert_type='certificate') -> []\n\
2996\n\
2997Retrieve certificates from Windows' cert store. store_name may be one of\n\
2998'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
2999cert_type must be either 'certificate' or 'crl'.\n\
3000The function returns a list of (bytes, encoding_type) tuples. The\n\
3001encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3002PKCS_7_ASN_ENCODING.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003003
Christian Heimes46bebee2013-06-09 19:03:31 +02003004static PyObject *
3005PySSL_enum_cert_store(PyObject *self, PyObject *args, PyObject *kwds)
3006{
3007 char *kwlist[] = {"store_name", "cert_type", NULL};
3008 char *store_name;
3009 char *cert_type = "certificate";
3010 HCERTSTORE hStore = NULL;
3011 PyObject *result = NULL;
3012 PyObject *tup = NULL, *cert = NULL, *enc = NULL;
3013 int ok = 1;
3014
3015 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_cert_store",
3016 kwlist, &store_name, &cert_type)) {
3017 return NULL;
3018 }
3019
3020 if ((strcmp(cert_type, "certificate") != 0) &&
3021 (strcmp(cert_type, "crl") != 0)) {
3022 return PyErr_Format(PyExc_ValueError,
3023 "cert_type must be 'certificate' or 'crl', "
3024 "not %.100s", cert_type);
3025 }
3026
3027 if ((result = PyList_New(0)) == NULL) {
3028 return NULL;
3029 }
3030
Richard Oudkerkcabbde92013-08-24 23:46:27 +01003031 if ((hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name)) == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003032 Py_DECREF(result);
3033 return PyErr_SetFromWindowsErr(GetLastError());
3034 }
3035
3036 if (strcmp(cert_type, "certificate") == 0) {
3037 PCCERT_CONTEXT pCertCtx = NULL;
3038 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3039 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3040 pCertCtx->cbCertEncoded);
3041 if (!cert) {
3042 ok = 0;
3043 break;
3044 }
3045 if ((enc = PyLong_FromLong(pCertCtx->dwCertEncodingType)) == NULL) {
3046 ok = 0;
3047 break;
3048 }
3049 if ((tup = PyTuple_New(2)) == NULL) {
3050 ok = 0;
3051 break;
3052 }
3053 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3054 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3055
3056 if (PyList_Append(result, tup) < 0) {
3057 ok = 0;
3058 break;
3059 }
3060 Py_CLEAR(tup);
3061 }
3062 if (pCertCtx) {
3063 /* loop ended with an error, need to clean up context manually */
3064 CertFreeCertificateContext(pCertCtx);
3065 }
3066 } else {
3067 PCCRL_CONTEXT pCrlCtx = NULL;
3068 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3069 cert = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3070 pCrlCtx->cbCrlEncoded);
3071 if (!cert) {
3072 ok = 0;
3073 break;
3074 }
3075 if ((enc = PyLong_FromLong(pCrlCtx->dwCertEncodingType)) == NULL) {
3076 ok = 0;
3077 break;
3078 }
3079 if ((tup = PyTuple_New(2)) == NULL) {
3080 ok = 0;
3081 break;
3082 }
3083 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3084 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3085
3086 if (PyList_Append(result, tup) < 0) {
3087 ok = 0;
3088 break;
3089 }
3090 Py_CLEAR(tup);
3091 }
3092 if (pCrlCtx) {
3093 /* loop ended with an error, need to clean up context manually */
3094 CertFreeCRLContext(pCrlCtx);
3095 }
3096 }
3097
3098 /* In error cases cert, enc and tup may not be NULL */
3099 Py_XDECREF(cert);
3100 Py_XDECREF(enc);
3101 Py_XDECREF(tup);
3102
3103 if (!CertCloseStore(hStore, 0)) {
3104 /* This error case might shadow another exception.*/
3105 Py_DECREF(result);
3106 return PyErr_SetFromWindowsErr(GetLastError());
3107 }
3108 if (ok) {
3109 return result;
3110 } else {
3111 Py_DECREF(result);
3112 return NULL;
3113 }
3114}
3115#endif
Bill Janssen40a0f662008-08-12 16:56:25 +00003116
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003117/* List of functions exported by this module. */
3118
3119static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003120 {"_test_decode_cert", PySSL_test_decode_certificate,
3121 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003122#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003123 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3124 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003125 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3126 PySSL_RAND_bytes_doc},
3127 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3128 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003129 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003130 PySSL_RAND_egd_doc},
3131 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3132 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003133#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003134 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003135 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003136#ifdef _MSC_VER
3137 {"enum_cert_store", (PyCFunction)PySSL_enum_cert_store,
3138 METH_VARARGS | METH_KEYWORDS, PySSL_enum_cert_store_doc},
3139#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003140 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003141};
3142
3143
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003144#ifdef WITH_THREAD
3145
3146/* an implementation of OpenSSL threading operations in terms
3147 of the Python C thread library */
3148
3149static PyThread_type_lock *_ssl_locks = NULL;
3150
Christian Heimes4d98ca92013-08-19 17:36:29 +02003151#if OPENSSL_VERSION_NUMBER >= 0x10000000
3152/* use new CRYPTO_THREADID API. */
3153static void
3154_ssl_threadid_callback(CRYPTO_THREADID *id)
3155{
3156 CRYPTO_THREADID_set_numeric(id,
3157 (unsigned long)PyThread_get_thread_ident());
3158}
3159#else
3160/* deprecated CRYPTO_set_id_callback() API. */
3161static unsigned long
3162_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003163 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003164}
Christian Heimes4d98ca92013-08-19 17:36:29 +02003165#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003166
Bill Janssen6e027db2007-11-15 22:23:56 +00003167static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003168 (int mode, int n, const char *file, int line) {
3169 /* this function is needed to perform locking on shared data
3170 structures. (Note that OpenSSL uses a number of global data
3171 structures that will be implicitly shared whenever multiple
3172 threads use OpenSSL.) Multi-threaded applications will
3173 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003174
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003175 locking_function() must be able to handle up to
3176 CRYPTO_num_locks() different mutex locks. It sets the n-th
3177 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003178
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003179 file and line are the file number of the function setting the
3180 lock. They can be useful for debugging.
3181 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003182
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003183 if ((_ssl_locks == NULL) ||
3184 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3185 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003186
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003187 if (mode & CRYPTO_LOCK) {
3188 PyThread_acquire_lock(_ssl_locks[n], 1);
3189 } else {
3190 PyThread_release_lock(_ssl_locks[n]);
3191 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003192}
3193
3194static int _setup_ssl_threads(void) {
3195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003196 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003197
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003198 if (_ssl_locks == NULL) {
3199 _ssl_locks_count = CRYPTO_num_locks();
3200 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02003201 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003202 if (_ssl_locks == NULL)
3203 return 0;
3204 memset(_ssl_locks, 0,
3205 sizeof(PyThread_type_lock) * _ssl_locks_count);
3206 for (i = 0; i < _ssl_locks_count; i++) {
3207 _ssl_locks[i] = PyThread_allocate_lock();
3208 if (_ssl_locks[i] == NULL) {
3209 unsigned int j;
3210 for (j = 0; j < i; j++) {
3211 PyThread_free_lock(_ssl_locks[j]);
3212 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003213 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003214 return 0;
3215 }
3216 }
3217 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003218#if OPENSSL_VERSION_NUMBER >= 0x10000000
3219 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3220#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003221 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003222#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003223 }
3224 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003225}
3226
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003227#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003228
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003229PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003230"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003231for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003232
Martin v. Löwis1a214512008-06-11 05:26:20 +00003233
3234static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003235 PyModuleDef_HEAD_INIT,
3236 "_ssl",
3237 module_doc,
3238 -1,
3239 PySSL_methods,
3240 NULL,
3241 NULL,
3242 NULL,
3243 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003244};
3245
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003246
3247static void
3248parse_openssl_version(unsigned long libver,
3249 unsigned int *major, unsigned int *minor,
3250 unsigned int *fix, unsigned int *patch,
3251 unsigned int *status)
3252{
3253 *status = libver & 0xF;
3254 libver >>= 4;
3255 *patch = libver & 0xFF;
3256 libver >>= 8;
3257 *fix = libver & 0xFF;
3258 libver >>= 8;
3259 *minor = libver & 0xFF;
3260 libver >>= 8;
3261 *major = libver & 0xFF;
3262}
3263
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003264PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003265PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003266{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003267 PyObject *m, *d, *r;
3268 unsigned long libver;
3269 unsigned int major, minor, fix, patch, status;
3270 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003271 struct py_ssl_error_code *errcode;
3272 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003273
Antoine Pitrou152efa22010-05-16 18:19:27 +00003274 if (PyType_Ready(&PySSLContext_Type) < 0)
3275 return NULL;
3276 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003277 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003278
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003279 m = PyModule_Create(&_sslmodule);
3280 if (m == NULL)
3281 return NULL;
3282 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003283
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003284 /* Load _socket module and its C API */
3285 socket_api = PySocketModule_ImportModuleAndAPI();
3286 if (!socket_api)
3287 return NULL;
3288 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003289
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003290 /* Init OpenSSL */
3291 SSL_load_error_strings();
3292 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003293#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003294 /* note that this will start threading if not already started */
3295 if (!_setup_ssl_threads()) {
3296 return NULL;
3297 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003298#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003299 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003300
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003301 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003302 sslerror_type_slots[0].pfunc = PyExc_OSError;
3303 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003304 if (PySSLErrorObject == NULL)
3305 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003306
Antoine Pitrou41032a62011-10-27 23:56:55 +02003307 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3308 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3309 PySSLErrorObject, NULL);
3310 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3311 "ssl.SSLWantReadError", SSLWantReadError_doc,
3312 PySSLErrorObject, NULL);
3313 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3314 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3315 PySSLErrorObject, NULL);
3316 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3317 "ssl.SSLSyscallError", SSLSyscallError_doc,
3318 PySSLErrorObject, NULL);
3319 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3320 "ssl.SSLEOFError", SSLEOFError_doc,
3321 PySSLErrorObject, NULL);
3322 if (PySSLZeroReturnErrorObject == NULL
3323 || PySSLWantReadErrorObject == NULL
3324 || PySSLWantWriteErrorObject == NULL
3325 || PySSLSyscallErrorObject == NULL
3326 || PySSLEOFErrorObject == NULL)
3327 return NULL;
3328 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3329 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3330 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3331 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3332 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3333 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003334 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003335 if (PyDict_SetItemString(d, "_SSLContext",
3336 (PyObject *)&PySSLContext_Type) != 0)
3337 return NULL;
3338 if (PyDict_SetItemString(d, "_SSLSocket",
3339 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003340 return NULL;
3341 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3342 PY_SSL_ERROR_ZERO_RETURN);
3343 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3344 PY_SSL_ERROR_WANT_READ);
3345 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3346 PY_SSL_ERROR_WANT_WRITE);
3347 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3348 PY_SSL_ERROR_WANT_X509_LOOKUP);
3349 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3350 PY_SSL_ERROR_SYSCALL);
3351 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3352 PY_SSL_ERROR_SSL);
3353 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3354 PY_SSL_ERROR_WANT_CONNECT);
3355 /* non ssl.h errorcodes */
3356 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3357 PY_SSL_ERROR_EOF);
3358 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3359 PY_SSL_ERROR_INVALID_ERROR_CODE);
3360 /* cert requirements */
3361 PyModule_AddIntConstant(m, "CERT_NONE",
3362 PY_SSL_CERT_NONE);
3363 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3364 PY_SSL_CERT_OPTIONAL);
3365 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3366 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00003367
Christian Heimes46bebee2013-06-09 19:03:31 +02003368#ifdef _MSC_VER
3369 /* Windows dwCertEncodingType */
3370 PyModule_AddIntMacro(m, X509_ASN_ENCODING);
3371 PyModule_AddIntMacro(m, PKCS_7_ASN_ENCODING);
3372#endif
3373
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003374 /* Alert Descriptions from ssl.h */
3375 /* note RESERVED constants no longer intended for use have been removed */
3376 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
3377
3378#define ADD_AD_CONSTANT(s) \
3379 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
3380 SSL_AD_##s)
3381
3382 ADD_AD_CONSTANT(CLOSE_NOTIFY);
3383 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
3384 ADD_AD_CONSTANT(BAD_RECORD_MAC);
3385 ADD_AD_CONSTANT(RECORD_OVERFLOW);
3386 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
3387 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
3388 ADD_AD_CONSTANT(BAD_CERTIFICATE);
3389 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
3390 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
3391 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
3392 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
3393 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
3394 ADD_AD_CONSTANT(UNKNOWN_CA);
3395 ADD_AD_CONSTANT(ACCESS_DENIED);
3396 ADD_AD_CONSTANT(DECODE_ERROR);
3397 ADD_AD_CONSTANT(DECRYPT_ERROR);
3398 ADD_AD_CONSTANT(PROTOCOL_VERSION);
3399 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
3400 ADD_AD_CONSTANT(INTERNAL_ERROR);
3401 ADD_AD_CONSTANT(USER_CANCELLED);
3402 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003403 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003404#ifdef SSL_AD_UNSUPPORTED_EXTENSION
3405 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
3406#endif
3407#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
3408 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
3409#endif
3410#ifdef SSL_AD_UNRECOGNIZED_NAME
3411 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
3412#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003413#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
3414 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
3415#endif
3416#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
3417 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
3418#endif
3419#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
3420 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
3421#endif
3422
3423#undef ADD_AD_CONSTANT
3424
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003425 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02003426#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003427 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
3428 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02003429#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003430 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
3431 PY_SSL_VERSION_SSL3);
3432 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
3433 PY_SSL_VERSION_SSL23);
3434 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
3435 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003436#if HAVE_TLSv1_2
3437 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
3438 PY_SSL_VERSION_TLS1_1);
3439 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
3440 PY_SSL_VERSION_TLS1_2);
3441#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003442
Antoine Pitroub5218772010-05-21 09:56:06 +00003443 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01003444 PyModule_AddIntConstant(m, "OP_ALL",
3445 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00003446 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
3447 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
3448 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003449#if HAVE_TLSv1_2
3450 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
3451 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
3452#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01003453 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
3454 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003455 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003456#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003457 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003458#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003459#ifdef SSL_OP_NO_COMPRESSION
3460 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
3461 SSL_OP_NO_COMPRESSION);
3462#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00003463
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003464#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00003465 r = Py_True;
3466#else
3467 r = Py_False;
3468#endif
3469 Py_INCREF(r);
3470 PyModule_AddObject(m, "HAS_SNI", r);
3471
Antoine Pitroud6494802011-07-21 01:11:30 +02003472#if HAVE_OPENSSL_FINISHED
3473 r = Py_True;
3474#else
3475 r = Py_False;
3476#endif
3477 Py_INCREF(r);
3478 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
3479
Antoine Pitrou501da612011-12-21 09:27:41 +01003480#ifdef OPENSSL_NO_ECDH
3481 r = Py_False;
3482#else
3483 r = Py_True;
3484#endif
3485 Py_INCREF(r);
3486 PyModule_AddObject(m, "HAS_ECDH", r);
3487
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003488#ifdef OPENSSL_NPN_NEGOTIATED
3489 r = Py_True;
3490#else
3491 r = Py_False;
3492#endif
3493 Py_INCREF(r);
3494 PyModule_AddObject(m, "HAS_NPN", r);
3495
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003496 /* Mappings for error codes */
3497 err_codes_to_names = PyDict_New();
3498 err_names_to_codes = PyDict_New();
3499 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
3500 return NULL;
3501 errcode = error_codes;
3502 while (errcode->mnemonic != NULL) {
3503 PyObject *mnemo, *key;
3504 mnemo = PyUnicode_FromString(errcode->mnemonic);
3505 key = Py_BuildValue("ii", errcode->library, errcode->reason);
3506 if (mnemo == NULL || key == NULL)
3507 return NULL;
3508 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
3509 return NULL;
3510 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
3511 return NULL;
3512 Py_DECREF(key);
3513 Py_DECREF(mnemo);
3514 errcode++;
3515 }
3516 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
3517 return NULL;
3518 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
3519 return NULL;
3520
3521 lib_codes_to_names = PyDict_New();
3522 if (lib_codes_to_names == NULL)
3523 return NULL;
3524 libcode = library_codes;
3525 while (libcode->library != NULL) {
3526 PyObject *mnemo, *key;
3527 key = PyLong_FromLong(libcode->code);
3528 mnemo = PyUnicode_FromString(libcode->library);
3529 if (key == NULL || mnemo == NULL)
3530 return NULL;
3531 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
3532 return NULL;
3533 Py_DECREF(key);
3534 Py_DECREF(mnemo);
3535 libcode++;
3536 }
3537 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
3538 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02003539
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003540 /* OpenSSL version */
3541 /* SSLeay() gives us the version of the library linked against,
3542 which could be different from the headers version.
3543 */
3544 libver = SSLeay();
3545 r = PyLong_FromUnsignedLong(libver);
3546 if (r == NULL)
3547 return NULL;
3548 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
3549 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003550 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003551 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3552 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
3553 return NULL;
3554 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
3555 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
3556 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003557
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003558 libver = OPENSSL_VERSION_NUMBER;
3559 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
3560 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3561 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
3562 return NULL;
3563
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003564 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003565}