blob: c61c38b19b44db43cb259abb0f31d5f312829e54 [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);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200349 if (msg == NULL)
350 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100351
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200352 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100353 if (init_value == NULL)
354 goto fail;
355
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200356 err_value = PyObject_CallObject(type, init_value);
357 Py_DECREF(init_value);
358 if (err_value == NULL)
359 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100360
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200361 if (reason_obj == NULL)
362 reason_obj = Py_None;
363 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
364 goto fail;
365 if (lib_obj == NULL)
366 lib_obj = Py_None;
367 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
368 goto fail;
369 PyErr_SetObject(type, err_value);
370fail:
371 Py_XDECREF(err_value);
372}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000373
374static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +0000375PySSL_SetError(PySSLSocket *obj, int ret, char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000376{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200377 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200378 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000379 int err;
380 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200381 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000382
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000383 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200384 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000385
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000386 if (obj->ssl != NULL) {
387 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000388
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000389 switch (err) {
390 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200391 errstr = "TLS/SSL connection has been closed (EOF)";
392 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000393 p = PY_SSL_ERROR_ZERO_RETURN;
394 break;
395 case SSL_ERROR_WANT_READ:
396 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200397 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000398 p = PY_SSL_ERROR_WANT_READ;
399 break;
400 case SSL_ERROR_WANT_WRITE:
401 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200402 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000403 errstr = "The operation did not complete (write)";
404 break;
405 case SSL_ERROR_WANT_X509_LOOKUP:
406 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000407 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000408 break;
409 case SSL_ERROR_WANT_CONNECT:
410 p = PY_SSL_ERROR_WANT_CONNECT;
411 errstr = "The operation did not complete (connect)";
412 break;
413 case SSL_ERROR_SYSCALL:
414 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000415 if (e == 0) {
416 PySocketSockObject *s
417 = (PySocketSockObject *) PyWeakref_GetObject(obj->Socket);
418 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000419 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200420 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000421 errstr = "EOF occurred in violation of protocol";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000422 } else if (ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000423 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000424 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000425 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200426 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000427 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200428 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000429 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000430 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200431 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000432 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000433 }
434 } else {
435 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000436 }
437 break;
438 }
439 case SSL_ERROR_SSL:
440 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000441 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200442 if (e == 0)
443 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000444 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000445 break;
446 }
447 default:
448 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
449 errstr = "Invalid error code";
450 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000451 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200452 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000453 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000454 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000455}
456
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000457static PyObject *
458_setSSLError (char *errstr, int errcode, char *filename, int lineno) {
459
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200460 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000461 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200462 else
463 errcode = 0;
464 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000465 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000466 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000467}
468
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200469/*
470 * SSL objects
471 */
472
Antoine Pitrou152efa22010-05-16 18:19:27 +0000473static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100474newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000475 enum py_ssl_server_or_client socket_type,
476 char *server_hostname)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000477{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000478 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100479 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200480 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000481
Antoine Pitrou152efa22010-05-16 18:19:27 +0000482 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000483 if (self == NULL)
484 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000485
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000486 self->peer_cert = NULL;
487 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000488 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100489 self->ctx = sslctx;
Antoine Pitrou860aee72013-09-29 19:52:45 +0200490 self->shutdown_seen_zero = 0;
Antoine Pitrou20b85552013-09-29 19:50:53 +0200491 self->handshake_done = 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100492 Py_INCREF(sslctx);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000493
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000494 /* Make sure the SSL error state is initialized */
495 (void) ERR_get_state();
496 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000497
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000498 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000499 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000500 PySSL_END_ALLOW_THREADS
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100501 SSL_set_app_data(self->ssl,self);
Christian Heimesb08ff7d2013-11-18 10:04:07 +0100502 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
Antoine Pitrou19fef692013-05-25 13:23:03 +0200503 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000504#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200505 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000506#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200507 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000508
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100509#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000510 if (server_hostname != NULL)
511 SSL_set_tlsext_host_name(self->ssl, server_hostname);
512#endif
513
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000514 /* If the socket is in non-blocking mode or timeout mode, set the BIO
515 * to non-blocking mode (blocking is the default)
516 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000517 if (sock->sock_timeout >= 0.0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
519 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
520 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000521
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000522 PySSL_BEGIN_ALLOW_THREADS
523 if (socket_type == PY_SSL_CLIENT)
524 SSL_set_connect_state(self->ssl);
525 else
526 SSL_set_accept_state(self->ssl);
527 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000528
Antoine Pitroud6494802011-07-21 01:11:30 +0200529 self->socket_type = socket_type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000530 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100531 if (self->Socket == NULL) {
532 Py_DECREF(self);
533 return NULL;
534 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000535 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000536}
537
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000538/* SSL object methods */
539
Antoine Pitrou152efa22010-05-16 18:19:27 +0000540static PyObject *PySSL_SSLdo_handshake(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000541{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000542 int ret;
543 int err;
544 int sockstate, nonblocking;
545 PySocketSockObject *sock
546 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000547
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000548 if (((PyObject*)sock) == Py_None) {
549 _setSSLError("Underlying socket connection gone",
550 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
551 return NULL;
552 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000553 Py_INCREF(sock);
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000554
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000555 /* just in case the blocking state of the socket has been changed */
556 nonblocking = (sock->sock_timeout >= 0.0);
557 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
558 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000559
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000560 /* Actually negotiate SSL connection */
561 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000562 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000563 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000564 ret = SSL_do_handshake(self->ssl);
565 err = SSL_get_error(self->ssl, ret);
566 PySSL_END_ALLOW_THREADS
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000567 if (PyErr_CheckSignals())
568 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000569 if (err == SSL_ERROR_WANT_READ) {
570 sockstate = check_socket_and_wait_for_timeout(sock, 0);
571 } else if (err == SSL_ERROR_WANT_WRITE) {
572 sockstate = check_socket_and_wait_for_timeout(sock, 1);
573 } else {
574 sockstate = SOCKET_OPERATION_OK;
575 }
576 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000577 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000578 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000579 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000580 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
581 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000582 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000583 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000584 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
585 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000586 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000587 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000588 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
589 break;
590 }
591 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000592 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000593 if (ret < 1)
594 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000596 if (self->peer_cert)
597 X509_free (self->peer_cert);
598 PySSL_BEGIN_ALLOW_THREADS
599 self->peer_cert = SSL_get_peer_certificate(self->ssl);
600 PySSL_END_ALLOW_THREADS
Antoine Pitrou20b85552013-09-29 19:50:53 +0200601 self->handshake_done = 1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000602
603 Py_INCREF(Py_None);
604 return Py_None;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000605
606error:
607 Py_DECREF(sock);
608 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000609}
610
Thomas Woutersed03b412007-08-28 21:37:11 +0000611static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000612_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000613
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000614 char namebuf[X509_NAME_MAXLEN];
615 int buflen;
616 PyObject *name_obj;
617 PyObject *value_obj;
618 PyObject *attr;
619 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000620
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000621 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
622 if (buflen < 0) {
623 _setSSLError(NULL, 0, __FILE__, __LINE__);
624 goto fail;
625 }
626 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
627 if (name_obj == NULL)
628 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000629
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000630 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
631 if (buflen < 0) {
632 _setSSLError(NULL, 0, __FILE__, __LINE__);
633 Py_DECREF(name_obj);
634 goto fail;
635 }
636 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000637 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000638 OPENSSL_free(valuebuf);
639 if (value_obj == NULL) {
640 Py_DECREF(name_obj);
641 goto fail;
642 }
643 attr = PyTuple_New(2);
644 if (attr == NULL) {
645 Py_DECREF(name_obj);
646 Py_DECREF(value_obj);
647 goto fail;
648 }
649 PyTuple_SET_ITEM(attr, 0, name_obj);
650 PyTuple_SET_ITEM(attr, 1, value_obj);
651 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000652
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000653 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000654 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000655}
656
657static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000658_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000659{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000660 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
661 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
662 PyObject *rdnt;
663 PyObject *attr = NULL; /* tuple to hold an attribute */
664 int entry_count = X509_NAME_entry_count(xname);
665 X509_NAME_ENTRY *entry;
666 ASN1_OBJECT *name;
667 ASN1_STRING *value;
668 int index_counter;
669 int rdn_level = -1;
670 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000671
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000672 dn = PyList_New(0);
673 if (dn == NULL)
674 return NULL;
675 /* now create another tuple to hold the top-level RDN */
676 rdn = PyList_New(0);
677 if (rdn == NULL)
678 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000679
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000680 for (index_counter = 0;
681 index_counter < entry_count;
682 index_counter++)
683 {
684 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000685
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000686 /* check to see if we've gotten to a new RDN */
687 if (rdn_level >= 0) {
688 if (rdn_level != entry->set) {
689 /* yes, new RDN */
690 /* add old RDN to DN */
691 rdnt = PyList_AsTuple(rdn);
692 Py_DECREF(rdn);
693 if (rdnt == NULL)
694 goto fail0;
695 retcode = PyList_Append(dn, rdnt);
696 Py_DECREF(rdnt);
697 if (retcode < 0)
698 goto fail0;
699 /* create new RDN */
700 rdn = PyList_New(0);
701 if (rdn == NULL)
702 goto fail0;
703 }
704 }
705 rdn_level = entry->set;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000706
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 /* now add this attribute to the current RDN */
708 name = X509_NAME_ENTRY_get_object(entry);
709 value = X509_NAME_ENTRY_get_data(entry);
710 attr = _create_tuple_for_attribute(name, value);
711 /*
712 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
713 entry->set,
714 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
715 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
716 */
717 if (attr == NULL)
718 goto fail1;
719 retcode = PyList_Append(rdn, attr);
720 Py_DECREF(attr);
721 if (retcode < 0)
722 goto fail1;
723 }
724 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100725 if (rdn != NULL) {
726 if (PyList_GET_SIZE(rdn) > 0) {
727 rdnt = PyList_AsTuple(rdn);
728 Py_DECREF(rdn);
729 if (rdnt == NULL)
730 goto fail0;
731 retcode = PyList_Append(dn, rdnt);
732 Py_DECREF(rdnt);
733 if (retcode < 0)
734 goto fail0;
735 }
736 else {
737 Py_DECREF(rdn);
738 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000739 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000740
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 /* convert list to tuple */
742 rdnt = PyList_AsTuple(dn);
743 Py_DECREF(dn);
744 if (rdnt == NULL)
745 return NULL;
746 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000747
748 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000749 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000750
751 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000752 Py_XDECREF(dn);
753 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000754}
755
756static PyObject *
757_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000758
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000759 /* this code follows the procedure outlined in
760 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
761 function to extract the STACK_OF(GENERAL_NAME),
762 then iterates through the stack to add the
763 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000764
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000765 int i, j;
766 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200767 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000768 X509_EXTENSION *ext = NULL;
769 GENERAL_NAMES *names = NULL;
770 GENERAL_NAME *name;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +0000771 const X509V3_EXT_METHOD *method;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000772 BIO *biobuf = NULL;
773 char buf[2048];
774 char *vptr;
775 int len;
776 /* Issue #2973: ASN1_item_d2i() API changed in OpenSSL 0.9.6m */
Victor Stinner7124a412010-03-02 22:48:17 +0000777#if OPENSSL_VERSION_NUMBER >= 0x009060dfL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000778 const unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000779#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000780 unsigned char *p;
Victor Stinner7124a412010-03-02 22:48:17 +0000781#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000782
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 if (certificate == NULL)
784 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000785
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000786 /* get a memory buffer */
787 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000788
Antoine Pitroud8c347a2011-10-01 19:20:25 +0200789 i = -1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 while ((i = X509_get_ext_by_NID(
791 certificate, NID_subject_alt_name, i)) >= 0) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000792
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000793 if (peer_alt_names == Py_None) {
794 peer_alt_names = PyList_New(0);
795 if (peer_alt_names == NULL)
796 goto fail;
797 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000798
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000799 /* now decode the altName */
800 ext = X509_get_ext(certificate, i);
801 if(!(method = X509V3_EXT_get(ext))) {
802 PyErr_SetString
803 (PySSLErrorObject,
804 ERRSTR("No method for internalizing subjectAltName!"));
805 goto fail;
806 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000807
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000808 p = ext->value->data;
809 if (method->it)
810 names = (GENERAL_NAMES*)
811 (ASN1_item_d2i(NULL,
812 &p,
813 ext->value->length,
814 ASN1_ITEM_ptr(method->it)));
815 else
816 names = (GENERAL_NAMES*)
817 (method->d2i(NULL,
818 &p,
819 ext->value->length));
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000820
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000821 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000822 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200823 int gntype;
824 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000825
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200827 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200828 switch (gntype) {
829 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 /* we special-case DirName as a tuple of
831 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000832
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000833 t = PyTuple_New(2);
834 if (t == NULL) {
835 goto fail;
836 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000837
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 v = PyUnicode_FromString("DirName");
839 if (v == NULL) {
840 Py_DECREF(t);
841 goto fail;
842 }
843 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000844
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000845 v = _create_tuple_for_X509_NAME (name->d.dirn);
846 if (v == NULL) {
847 Py_DECREF(t);
848 goto fail;
849 }
850 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200851 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000852
Christian Heimes824f7f32013-08-17 00:54:47 +0200853 case GEN_EMAIL:
854 case GEN_DNS:
855 case GEN_URI:
856 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
857 correctly, CVE-2013-4238 */
858 t = PyTuple_New(2);
859 if (t == NULL)
860 goto fail;
861 switch (gntype) {
862 case GEN_EMAIL:
863 v = PyUnicode_FromString("email");
864 as = name->d.rfc822Name;
865 break;
866 case GEN_DNS:
867 v = PyUnicode_FromString("DNS");
868 as = name->d.dNSName;
869 break;
870 case GEN_URI:
871 v = PyUnicode_FromString("URI");
872 as = name->d.uniformResourceIdentifier;
873 break;
874 }
875 if (v == NULL) {
876 Py_DECREF(t);
877 goto fail;
878 }
879 PyTuple_SET_ITEM(t, 0, v);
880 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
881 ASN1_STRING_length(as));
882 if (v == NULL) {
883 Py_DECREF(t);
884 goto fail;
885 }
886 PyTuple_SET_ITEM(t, 1, v);
887 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000888
Christian Heimes824f7f32013-08-17 00:54:47 +0200889 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000890 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +0200891 switch (gntype) {
892 /* check for new general name type */
893 case GEN_OTHERNAME:
894 case GEN_X400:
895 case GEN_EDIPARTY:
896 case GEN_IPADD:
897 case GEN_RID:
898 break;
899 default:
900 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
901 "Unknown general name type %d",
902 gntype) == -1) {
903 goto fail;
904 }
905 break;
906 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000907 (void) BIO_reset(biobuf);
908 GENERAL_NAME_print(biobuf, name);
909 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
910 if (len < 0) {
911 _setSSLError(NULL, 0, __FILE__, __LINE__);
912 goto fail;
913 }
914 vptr = strchr(buf, ':');
915 if (vptr == NULL)
916 goto fail;
917 t = PyTuple_New(2);
918 if (t == NULL)
919 goto fail;
920 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
921 if (v == NULL) {
922 Py_DECREF(t);
923 goto fail;
924 }
925 PyTuple_SET_ITEM(t, 0, v);
926 v = PyUnicode_FromStringAndSize((vptr + 1),
927 (len - (vptr - buf + 1)));
928 if (v == NULL) {
929 Py_DECREF(t);
930 goto fail;
931 }
932 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200933 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000935
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000937
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 if (PyList_Append(peer_alt_names, t) < 0) {
939 Py_DECREF(t);
940 goto fail;
941 }
942 Py_DECREF(t);
943 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +0100944 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 }
946 BIO_free(biobuf);
947 if (peer_alt_names != Py_None) {
948 v = PyList_AsTuple(peer_alt_names);
949 Py_DECREF(peer_alt_names);
950 return v;
951 } else {
952 return peer_alt_names;
953 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000954
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000955
956 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 if (biobuf != NULL)
958 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000959
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000960 if (peer_alt_names != Py_None) {
961 Py_XDECREF(peer_alt_names);
962 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000963
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000964 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000965}
966
967static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +0000968_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000969
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 PyObject *retval = NULL;
971 BIO *biobuf = NULL;
972 PyObject *peer;
973 PyObject *peer_alt_names = NULL;
974 PyObject *issuer;
975 PyObject *version;
976 PyObject *sn_obj;
977 ASN1_INTEGER *serialNumber;
978 char buf[2048];
979 int len;
980 ASN1_TIME *notBefore, *notAfter;
981 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +0000982
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000983 retval = PyDict_New();
984 if (retval == NULL)
985 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000986
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000987 peer = _create_tuple_for_X509_NAME(
988 X509_get_subject_name(certificate));
989 if (peer == NULL)
990 goto fail0;
991 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
992 Py_DECREF(peer);
993 goto fail0;
994 }
995 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +0000996
Antoine Pitroufb046912010-11-09 20:21:19 +0000997 issuer = _create_tuple_for_X509_NAME(
998 X509_get_issuer_name(certificate));
999 if (issuer == NULL)
1000 goto fail0;
1001 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001002 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001003 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001004 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001005 Py_DECREF(issuer);
1006
1007 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001008 if (version == NULL)
1009 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001010 if (PyDict_SetItemString(retval, "version", version) < 0) {
1011 Py_DECREF(version);
1012 goto fail0;
1013 }
1014 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001015
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001016 /* get a memory buffer */
1017 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001018
Antoine Pitroufb046912010-11-09 20:21:19 +00001019 (void) BIO_reset(biobuf);
1020 serialNumber = X509_get_serialNumber(certificate);
1021 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1022 i2a_ASN1_INTEGER(biobuf, serialNumber);
1023 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1024 if (len < 0) {
1025 _setSSLError(NULL, 0, __FILE__, __LINE__);
1026 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001027 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001028 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1029 if (sn_obj == NULL)
1030 goto fail1;
1031 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1032 Py_DECREF(sn_obj);
1033 goto fail1;
1034 }
1035 Py_DECREF(sn_obj);
1036
1037 (void) BIO_reset(biobuf);
1038 notBefore = X509_get_notBefore(certificate);
1039 ASN1_TIME_print(biobuf, notBefore);
1040 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1041 if (len < 0) {
1042 _setSSLError(NULL, 0, __FILE__, __LINE__);
1043 goto fail1;
1044 }
1045 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1046 if (pnotBefore == NULL)
1047 goto fail1;
1048 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1049 Py_DECREF(pnotBefore);
1050 goto fail1;
1051 }
1052 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001053
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001054 (void) BIO_reset(biobuf);
1055 notAfter = X509_get_notAfter(certificate);
1056 ASN1_TIME_print(biobuf, notAfter);
1057 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1058 if (len < 0) {
1059 _setSSLError(NULL, 0, __FILE__, __LINE__);
1060 goto fail1;
1061 }
1062 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1063 if (pnotAfter == NULL)
1064 goto fail1;
1065 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1066 Py_DECREF(pnotAfter);
1067 goto fail1;
1068 }
1069 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001070
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001071 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001072
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001073 peer_alt_names = _get_peer_alt_names(certificate);
1074 if (peer_alt_names == NULL)
1075 goto fail1;
1076 else if (peer_alt_names != Py_None) {
1077 if (PyDict_SetItemString(retval, "subjectAltName",
1078 peer_alt_names) < 0) {
1079 Py_DECREF(peer_alt_names);
1080 goto fail1;
1081 }
1082 Py_DECREF(peer_alt_names);
1083 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001084
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001085 BIO_free(biobuf);
1086 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001087
1088 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001089 if (biobuf != NULL)
1090 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001091 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001092 Py_XDECREF(retval);
1093 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001094}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001095
Christian Heimes9a5395a2013-06-17 15:44:12 +02001096static PyObject *
1097_certificate_to_der(X509 *certificate)
1098{
1099 unsigned char *bytes_buf = NULL;
1100 int len;
1101 PyObject *retval;
1102
1103 bytes_buf = NULL;
1104 len = i2d_X509(certificate, &bytes_buf);
1105 if (len < 0) {
1106 _setSSLError(NULL, 0, __FILE__, __LINE__);
1107 return NULL;
1108 }
1109 /* this is actually an immutable bytes sequence */
1110 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1111 OPENSSL_free(bytes_buf);
1112 return retval;
1113}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001114
1115static PyObject *
1116PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1117
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001119 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 X509 *x=NULL;
1121 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001122
Antoine Pitroufb046912010-11-09 20:21:19 +00001123 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1124 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001125 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001126
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1128 PyErr_SetString(PySSLErrorObject,
1129 "Can't malloc memory to read file");
1130 goto fail0;
1131 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001132
Victor Stinner3800e1e2010-05-16 21:23:48 +00001133 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001134 PyErr_SetString(PySSLErrorObject,
1135 "Can't open file");
1136 goto fail0;
1137 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001138
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001139 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1140 if (x == NULL) {
1141 PyErr_SetString(PySSLErrorObject,
1142 "Error decoding PEM-encoded file");
1143 goto fail0;
1144 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001145
Antoine Pitroufb046912010-11-09 20:21:19 +00001146 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001147 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001148
1149 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001150 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001151 if (cert != NULL) BIO_free(cert);
1152 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001153}
1154
1155
1156static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001157PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001158{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001159 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001160 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001161
Antoine Pitrou721738f2012-08-15 23:20:39 +02001162 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001163 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001164
Antoine Pitrou20b85552013-09-29 19:50:53 +02001165 if (!self->handshake_done) {
1166 PyErr_SetString(PyExc_ValueError,
1167 "handshake not done yet");
1168 return NULL;
1169 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001170 if (!self->peer_cert)
1171 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001172
Antoine Pitrou721738f2012-08-15 23:20:39 +02001173 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001175 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001176 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001177 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001178 if ((verification & SSL_VERIFY_PEER) == 0)
1179 return PyDict_New();
1180 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001181 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001183}
1184
1185PyDoc_STRVAR(PySSL_peercert_doc,
1186"peer_certificate([der=False]) -> certificate\n\
1187\n\
1188Returns the certificate for the peer. If no certificate was provided,\n\
1189returns None. If a certificate was provided, but not validated, returns\n\
1190an empty dictionary. Otherwise returns a dict containing information\n\
1191about the peer certificate.\n\
1192\n\
1193If the optional argument is True, returns a DER-encoded copy of the\n\
1194peer certificate, or None if no certificate was provided. This will\n\
1195return the certificate even if it wasn't validated.");
1196
Antoine Pitrou152efa22010-05-16 18:19:27 +00001197static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001199 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001200 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001201 char *cipher_name;
1202 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001203
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001204 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001205 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001206 current = SSL_get_current_cipher(self->ssl);
1207 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001208 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001209
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001210 retval = PyTuple_New(3);
1211 if (retval == NULL)
1212 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001213
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001214 cipher_name = (char *) SSL_CIPHER_get_name(current);
1215 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001216 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001217 PyTuple_SET_ITEM(retval, 0, Py_None);
1218 } else {
1219 v = PyUnicode_FromString(cipher_name);
1220 if (v == NULL)
1221 goto fail0;
1222 PyTuple_SET_ITEM(retval, 0, v);
1223 }
1224 cipher_protocol = SSL_CIPHER_get_version(current);
1225 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001226 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001227 PyTuple_SET_ITEM(retval, 1, Py_None);
1228 } else {
1229 v = PyUnicode_FromString(cipher_protocol);
1230 if (v == NULL)
1231 goto fail0;
1232 PyTuple_SET_ITEM(retval, 1, v);
1233 }
1234 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1235 if (v == NULL)
1236 goto fail0;
1237 PyTuple_SET_ITEM(retval, 2, v);
1238 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001239
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001240 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241 Py_DECREF(retval);
1242 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001243}
1244
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001245#ifdef OPENSSL_NPN_NEGOTIATED
1246static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1247 const unsigned char *out;
1248 unsigned int outlen;
1249
Victor Stinner4569cd52013-06-23 14:58:43 +02001250 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001251 &out, &outlen);
1252
1253 if (out == NULL)
1254 Py_RETURN_NONE;
1255 return PyUnicode_FromStringAndSize((char *) out, outlen);
1256}
1257#endif
1258
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001259static PyObject *PySSL_compression(PySSLSocket *self) {
1260#ifdef OPENSSL_NO_COMP
1261 Py_RETURN_NONE;
1262#else
1263 const COMP_METHOD *comp_method;
1264 const char *short_name;
1265
1266 if (self->ssl == NULL)
1267 Py_RETURN_NONE;
1268 comp_method = SSL_get_current_compression(self->ssl);
1269 if (comp_method == NULL || comp_method->type == NID_undef)
1270 Py_RETURN_NONE;
1271 short_name = OBJ_nid2sn(comp_method->type);
1272 if (short_name == NULL)
1273 Py_RETURN_NONE;
1274 return PyUnicode_DecodeFSDefault(short_name);
1275#endif
1276}
1277
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001278static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1279 Py_INCREF(self->ctx);
1280 return self->ctx;
1281}
1282
1283static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1284 void *closure) {
1285
1286 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001287#if !HAVE_SNI
1288 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1289 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001290 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001291#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001292 Py_INCREF(value);
1293 Py_DECREF(self->ctx);
1294 self->ctx = (PySSLContext *) value;
1295 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001296#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001297 } else {
1298 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1299 return -1;
1300 }
1301
1302 return 0;
1303}
1304
1305PyDoc_STRVAR(PySSL_set_context_doc,
1306"_setter_context(ctx)\n\
1307\
1308This changes the context associated with the SSLSocket. This is typically\n\
1309used from within a callback function set by the set_servername_callback\n\
1310on the SSLContext to change the certificate information associated with the\n\
1311SSLSocket before the cryptographic exchange handshake messages\n");
1312
1313
1314
Antoine Pitrou152efa22010-05-16 18:19:27 +00001315static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001316{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001317 if (self->peer_cert) /* Possible not to have one? */
1318 X509_free (self->peer_cert);
1319 if (self->ssl)
1320 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001321 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001322 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001323 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001324}
1325
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001326/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001327 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001328 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001329 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001330
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001331static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001332check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001333{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 fd_set fds;
1335 struct timeval tv;
1336 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001337
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1339 if (s->sock_timeout < 0.0)
1340 return SOCKET_IS_BLOCKING;
1341 else if (s->sock_timeout == 0.0)
1342 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001343
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001344 /* Guard against closed socket */
1345 if (s->sock_fd < 0)
1346 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001347
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001348 /* Prefer poll, if available, since you can poll() any fd
1349 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001350#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001351 {
1352 struct pollfd pollfd;
1353 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001354
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001355 pollfd.fd = s->sock_fd;
1356 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001357
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001358 /* s->sock_timeout is in seconds, timeout in ms */
1359 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1360 PySSL_BEGIN_ALLOW_THREADS
1361 rc = poll(&pollfd, 1, timeout);
1362 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001363
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 goto normal_return;
1365 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001366#endif
1367
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001369 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001371
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001372 /* Construct the arguments to select */
1373 tv.tv_sec = (int)s->sock_timeout;
1374 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1375 FD_ZERO(&fds);
1376 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001377
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 /* See if the socket is ready */
1379 PySSL_BEGIN_ALLOW_THREADS
1380 if (writing)
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001381 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1382 NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001383 else
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001384 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1385 &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001386 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001387
Bill Janssen6e027db2007-11-15 22:23:56 +00001388#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001389normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001390#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001391 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1392 (when we are able to write or when there's something to read) */
1393 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001394}
1395
Antoine Pitrou152efa22010-05-16 18:19:27 +00001396static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001397{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001398 Py_buffer buf;
1399 int len;
1400 int sockstate;
1401 int err;
1402 int nonblocking;
1403 PySocketSockObject *sock
1404 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001405
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001406 if (((PyObject*)sock) == Py_None) {
1407 _setSSLError("Underlying socket connection gone",
1408 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1409 return NULL;
1410 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001411 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001412
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001413 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1414 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001415 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001416 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001417
Victor Stinner6efa9652013-06-25 00:42:31 +02001418 if (buf.len > INT_MAX) {
1419 PyErr_Format(PyExc_OverflowError,
1420 "string longer than %d bytes", INT_MAX);
1421 goto error;
1422 }
1423
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001424 /* just in case the blocking state of the socket has been changed */
1425 nonblocking = (sock->sock_timeout >= 0.0);
1426 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1427 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1428
1429 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1430 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001431 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001432 "The write operation timed out");
1433 goto error;
1434 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1435 PyErr_SetString(PySSLErrorObject,
1436 "Underlying socket has been closed.");
1437 goto error;
1438 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1439 PyErr_SetString(PySSLErrorObject,
1440 "Underlying socket too large for select().");
1441 goto error;
1442 }
1443 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001444 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001445 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001446 err = SSL_get_error(self->ssl, len);
1447 PySSL_END_ALLOW_THREADS
1448 if (PyErr_CheckSignals()) {
1449 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001450 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001451 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001452 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001453 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001454 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001455 } else {
1456 sockstate = SOCKET_OPERATION_OK;
1457 }
1458 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001459 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001460 "The write operation timed out");
1461 goto error;
1462 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1463 PyErr_SetString(PySSLErrorObject,
1464 "Underlying socket has been closed.");
1465 goto error;
1466 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1467 break;
1468 }
1469 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001470
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001471 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001472 PyBuffer_Release(&buf);
1473 if (len > 0)
1474 return PyLong_FromLong(len);
1475 else
1476 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001477
1478error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001479 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001480 PyBuffer_Release(&buf);
1481 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001482}
1483
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001484PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001485"write(s) -> len\n\
1486\n\
1487Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001488of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001489
Antoine Pitrou152efa22010-05-16 18:19:27 +00001490static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001491{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001492 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001493
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001494 PySSL_BEGIN_ALLOW_THREADS
1495 count = SSL_pending(self->ssl);
1496 PySSL_END_ALLOW_THREADS
1497 if (count < 0)
1498 return PySSL_SetError(self, count, __FILE__, __LINE__);
1499 else
1500 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001501}
1502
1503PyDoc_STRVAR(PySSL_SSLpending_doc,
1504"pending() -> count\n\
1505\n\
1506Returns the number of already decrypted bytes available for read,\n\
1507pending on the connection.\n");
1508
Antoine Pitrou152efa22010-05-16 18:19:27 +00001509static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001510{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001511 PyObject *dest = NULL;
1512 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001513 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001514 int len, count;
1515 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001516 int sockstate;
1517 int err;
1518 int nonblocking;
1519 PySocketSockObject *sock
1520 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001521
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522 if (((PyObject*)sock) == Py_None) {
1523 _setSSLError("Underlying socket connection gone",
1524 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1525 return NULL;
1526 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001527 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001529 buf.obj = NULL;
1530 buf.buf = NULL;
1531 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001532 goto error;
1533
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001534 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1535 dest = PyBytes_FromStringAndSize(NULL, len);
1536 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001537 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001538 mem = PyBytes_AS_STRING(dest);
1539 }
1540 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001541 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001542 mem = buf.buf;
1543 if (len <= 0 || len > buf.len) {
1544 len = (int) buf.len;
1545 if (buf.len != len) {
1546 PyErr_SetString(PyExc_OverflowError,
1547 "maximum length can't fit in a C 'int'");
1548 goto error;
1549 }
1550 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001551 }
1552
1553 /* just in case the blocking state of the socket has been changed */
1554 nonblocking = (sock->sock_timeout >= 0.0);
1555 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1556 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1557
1558 /* first check if there are bytes ready to be read */
1559 PySSL_BEGIN_ALLOW_THREADS
1560 count = SSL_pending(self->ssl);
1561 PySSL_END_ALLOW_THREADS
1562
1563 if (!count) {
1564 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1565 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001566 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001567 "The read operation timed out");
1568 goto error;
1569 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1570 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001571 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001572 goto error;
1573 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1574 count = 0;
1575 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001576 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001577 }
1578 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001579 PySSL_BEGIN_ALLOW_THREADS
1580 count = SSL_read(self->ssl, mem, len);
1581 err = SSL_get_error(self->ssl, count);
1582 PySSL_END_ALLOW_THREADS
1583 if (PyErr_CheckSignals())
1584 goto error;
1585 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001586 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001587 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001588 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001589 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1590 (SSL_get_shutdown(self->ssl) ==
1591 SSL_RECEIVED_SHUTDOWN))
1592 {
1593 count = 0;
1594 goto done;
1595 } else {
1596 sockstate = SOCKET_OPERATION_OK;
1597 }
1598 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001599 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001600 "The read operation timed out");
1601 goto error;
1602 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1603 break;
1604 }
1605 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1606 if (count <= 0) {
1607 PySSL_SetError(self, count, __FILE__, __LINE__);
1608 goto error;
1609 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001610
1611done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001612 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001613 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001614 _PyBytes_Resize(&dest, count);
1615 return dest;
1616 }
1617 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001618 PyBuffer_Release(&buf);
1619 return PyLong_FromLong(count);
1620 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001621
1622error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001623 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001624 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001625 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001626 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001627 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001628 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001629}
1630
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001631PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001632"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001633\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001634Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001635
Antoine Pitrou152efa22010-05-16 18:19:27 +00001636static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001637{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001638 int err, ssl_err, sockstate, nonblocking;
1639 int zeros = 0;
1640 PySocketSockObject *sock
1641 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001642
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001643 /* Guard against closed socket */
1644 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1645 _setSSLError("Underlying socket connection gone",
1646 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1647 return NULL;
1648 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001649 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001650
1651 /* Just in case the blocking state of the socket has been changed */
1652 nonblocking = (sock->sock_timeout >= 0.0);
1653 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1654 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1655
1656 while (1) {
1657 PySSL_BEGIN_ALLOW_THREADS
1658 /* Disable read-ahead so that unwrap can work correctly.
1659 * Otherwise OpenSSL might read in too much data,
1660 * eating clear text data that happens to be
1661 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001662 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001663 * function is used and the shutdown_seen_zero != 0
1664 * condition is met.
1665 */
1666 if (self->shutdown_seen_zero)
1667 SSL_set_read_ahead(self->ssl, 0);
1668 err = SSL_shutdown(self->ssl);
1669 PySSL_END_ALLOW_THREADS
1670 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1671 if (err > 0)
1672 break;
1673 if (err == 0) {
1674 /* Don't loop endlessly; instead preserve legacy
1675 behaviour of trying SSL_shutdown() only twice.
1676 This looks necessary for OpenSSL < 0.9.8m */
1677 if (++zeros > 1)
1678 break;
1679 /* Shutdown was sent, now try receiving */
1680 self->shutdown_seen_zero = 1;
1681 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001682 }
1683
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001684 /* Possibly retry shutdown until timeout or failure */
1685 ssl_err = SSL_get_error(self->ssl, err);
1686 if (ssl_err == SSL_ERROR_WANT_READ)
1687 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1688 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1689 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1690 else
1691 break;
1692 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1693 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001694 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001695 "The read operation timed out");
1696 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001697 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001698 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001699 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001700 }
1701 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1702 PyErr_SetString(PySSLErrorObject,
1703 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001704 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001705 }
1706 else if (sockstate != SOCKET_OPERATION_OK)
1707 /* Retain the SSL error code */
1708 break;
1709 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001710
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001711 if (err < 0) {
1712 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001713 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001714 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001715 else
1716 /* It's already INCREF'ed */
1717 return (PyObject *) sock;
1718
1719error:
1720 Py_DECREF(sock);
1721 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001722}
1723
1724PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1725"shutdown(s) -> socket\n\
1726\n\
1727Does the SSL shutdown handshake with the remote end, and returns\n\
1728the underlying socket object.");
1729
Antoine Pitroud6494802011-07-21 01:11:30 +02001730#if HAVE_OPENSSL_FINISHED
1731static PyObject *
1732PySSL_tls_unique_cb(PySSLSocket *self)
1733{
1734 PyObject *retval = NULL;
1735 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001736 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001737
1738 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1739 /* if session is resumed XOR we are the client */
1740 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1741 }
1742 else {
1743 /* if a new session XOR we are the server */
1744 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1745 }
1746
1747 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001748 if (len == 0)
1749 Py_RETURN_NONE;
1750
1751 retval = PyBytes_FromStringAndSize(buf, len);
1752
1753 return retval;
1754}
1755
1756PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1757"tls_unique_cb() -> bytes\n\
1758\n\
1759Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1760\n\
1761If the TLS handshake is not yet complete, None is returned");
1762
1763#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001764
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001765static PyGetSetDef ssl_getsetlist[] = {
1766 {"context", (getter) PySSL_get_context,
1767 (setter) PySSL_set_context, PySSL_set_context_doc},
1768 {NULL}, /* sentinel */
1769};
1770
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001771static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001772 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1773 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1774 PySSL_SSLwrite_doc},
1775 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1776 PySSL_SSLread_doc},
1777 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1778 PySSL_SSLpending_doc},
1779 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1780 PySSL_peercert_doc},
1781 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001782#ifdef OPENSSL_NPN_NEGOTIATED
1783 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1784#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001785 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001786 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1787 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001788#if HAVE_OPENSSL_FINISHED
1789 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1790 PySSL_tls_unique_cb_doc},
1791#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001792 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001793};
1794
Antoine Pitrou152efa22010-05-16 18:19:27 +00001795static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001796 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001797 "_ssl._SSLSocket", /*tp_name*/
1798 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001799 0, /*tp_itemsize*/
1800 /* methods */
1801 (destructor)PySSL_dealloc, /*tp_dealloc*/
1802 0, /*tp_print*/
1803 0, /*tp_getattr*/
1804 0, /*tp_setattr*/
1805 0, /*tp_reserved*/
1806 0, /*tp_repr*/
1807 0, /*tp_as_number*/
1808 0, /*tp_as_sequence*/
1809 0, /*tp_as_mapping*/
1810 0, /*tp_hash*/
1811 0, /*tp_call*/
1812 0, /*tp_str*/
1813 0, /*tp_getattro*/
1814 0, /*tp_setattro*/
1815 0, /*tp_as_buffer*/
1816 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1817 0, /*tp_doc*/
1818 0, /*tp_traverse*/
1819 0, /*tp_clear*/
1820 0, /*tp_richcompare*/
1821 0, /*tp_weaklistoffset*/
1822 0, /*tp_iter*/
1823 0, /*tp_iternext*/
1824 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001825 0, /*tp_members*/
1826 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001827};
1828
Antoine Pitrou152efa22010-05-16 18:19:27 +00001829
1830/*
1831 * _SSLContext objects
1832 */
1833
1834static PyObject *
1835context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1836{
1837 char *kwlist[] = {"protocol", NULL};
1838 PySSLContext *self;
1839 int proto_version = PY_SSL_VERSION_SSL23;
1840 SSL_CTX *ctx = NULL;
1841
1842 if (!PyArg_ParseTupleAndKeywords(
1843 args, kwds, "i:_SSLContext", kwlist,
1844 &proto_version))
1845 return NULL;
1846
1847 PySSL_BEGIN_ALLOW_THREADS
1848 if (proto_version == PY_SSL_VERSION_TLS1)
1849 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01001850#if HAVE_TLSv1_2
1851 else if (proto_version == PY_SSL_VERSION_TLS1_1)
1852 ctx = SSL_CTX_new(TLSv1_1_method());
1853 else if (proto_version == PY_SSL_VERSION_TLS1_2)
1854 ctx = SSL_CTX_new(TLSv1_2_method());
1855#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001856 else if (proto_version == PY_SSL_VERSION_SSL3)
1857 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001858#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00001859 else if (proto_version == PY_SSL_VERSION_SSL2)
1860 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02001861#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001862 else if (proto_version == PY_SSL_VERSION_SSL23)
1863 ctx = SSL_CTX_new(SSLv23_method());
1864 else
1865 proto_version = -1;
1866 PySSL_END_ALLOW_THREADS
1867
1868 if (proto_version == -1) {
1869 PyErr_SetString(PyExc_ValueError,
1870 "invalid protocol version");
1871 return NULL;
1872 }
1873 if (ctx == NULL) {
1874 PyErr_SetString(PySSLErrorObject,
1875 "failed to allocate SSL context");
1876 return NULL;
1877 }
1878
1879 assert(type != NULL && type->tp_alloc != NULL);
1880 self = (PySSLContext *) type->tp_alloc(type, 0);
1881 if (self == NULL) {
1882 SSL_CTX_free(ctx);
1883 return NULL;
1884 }
1885 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02001886#ifdef OPENSSL_NPN_NEGOTIATED
1887 self->npn_protocols = NULL;
1888#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001889#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02001890 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001891#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001892 /* Defaults */
1893 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01001894 SSL_CTX_set_options(self->ctx,
1895 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001896
Antoine Pitroufc113ee2010-10-13 12:46:13 +00001897#define SID_CTX "Python"
1898 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
1899 sizeof(SID_CTX));
1900#undef SID_CTX
1901
Antoine Pitrou152efa22010-05-16 18:19:27 +00001902 return (PyObject *)self;
1903}
1904
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001905static int
1906context_traverse(PySSLContext *self, visitproc visit, void *arg)
1907{
1908#ifndef OPENSSL_NO_TLSEXT
1909 Py_VISIT(self->set_hostname);
1910#endif
1911 return 0;
1912}
1913
1914static int
1915context_clear(PySSLContext *self)
1916{
1917#ifndef OPENSSL_NO_TLSEXT
1918 Py_CLEAR(self->set_hostname);
1919#endif
1920 return 0;
1921}
1922
Antoine Pitrou152efa22010-05-16 18:19:27 +00001923static void
1924context_dealloc(PySSLContext *self)
1925{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001926 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00001927 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001928#ifdef OPENSSL_NPN_NEGOTIATED
1929 PyMem_Free(self->npn_protocols);
1930#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00001931 Py_TYPE(self)->tp_free(self);
1932}
1933
1934static PyObject *
1935set_ciphers(PySSLContext *self, PyObject *args)
1936{
1937 int ret;
1938 const char *cipherlist;
1939
1940 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
1941 return NULL;
1942 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
1943 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00001944 /* Clearing the error queue is necessary on some OpenSSL versions,
1945 otherwise the error will be reported again when another SSL call
1946 is done. */
1947 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00001948 PyErr_SetString(PySSLErrorObject,
1949 "No cipher can be selected.");
1950 return NULL;
1951 }
1952 Py_RETURN_NONE;
1953}
1954
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001955#ifdef OPENSSL_NPN_NEGOTIATED
1956/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
1957static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001958_advertiseNPN_cb(SSL *s,
1959 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001960 void *args)
1961{
1962 PySSLContext *ssl_ctx = (PySSLContext *) args;
1963
1964 if (ssl_ctx->npn_protocols == NULL) {
1965 *data = (unsigned char *) "";
1966 *len = 0;
1967 } else {
1968 *data = (unsigned char *) ssl_ctx->npn_protocols;
1969 *len = ssl_ctx->npn_protocols_len;
1970 }
1971
1972 return SSL_TLSEXT_ERR_OK;
1973}
1974/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
1975static int
Victor Stinner4569cd52013-06-23 14:58:43 +02001976_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001977 unsigned char **out, unsigned char *outlen,
1978 const unsigned char *server, unsigned int server_len,
1979 void *args)
1980{
1981 PySSLContext *ssl_ctx = (PySSLContext *) args;
1982
1983 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
1984 int client_len;
1985
1986 if (client == NULL) {
1987 client = (unsigned char *) "";
1988 client_len = 0;
1989 } else {
1990 client_len = ssl_ctx->npn_protocols_len;
1991 }
1992
1993 SSL_select_next_proto(out, outlen,
1994 server, server_len,
1995 client, client_len);
1996
1997 return SSL_TLSEXT_ERR_OK;
1998}
1999#endif
2000
2001static PyObject *
2002_set_npn_protocols(PySSLContext *self, PyObject *args)
2003{
2004#ifdef OPENSSL_NPN_NEGOTIATED
2005 Py_buffer protos;
2006
2007 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2008 return NULL;
2009
Christian Heimes5cb31c92012-09-20 12:42:54 +02002010 if (self->npn_protocols != NULL) {
2011 PyMem_Free(self->npn_protocols);
2012 }
2013
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002014 self->npn_protocols = PyMem_Malloc(protos.len);
2015 if (self->npn_protocols == NULL) {
2016 PyBuffer_Release(&protos);
2017 return PyErr_NoMemory();
2018 }
2019 memcpy(self->npn_protocols, protos.buf, protos.len);
2020 self->npn_protocols_len = (int) protos.len;
2021
2022 /* set both server and client callbacks, because the context can
2023 * be used to create both types of sockets */
2024 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2025 _advertiseNPN_cb,
2026 self);
2027 SSL_CTX_set_next_proto_select_cb(self->ctx,
2028 _selectNPN_cb,
2029 self);
2030
2031 PyBuffer_Release(&protos);
2032 Py_RETURN_NONE;
2033#else
2034 PyErr_SetString(PyExc_NotImplementedError,
2035 "The NPN extension requires OpenSSL 1.0.1 or later.");
2036 return NULL;
2037#endif
2038}
2039
Antoine Pitrou152efa22010-05-16 18:19:27 +00002040static PyObject *
2041get_verify_mode(PySSLContext *self, void *c)
2042{
2043 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2044 case SSL_VERIFY_NONE:
2045 return PyLong_FromLong(PY_SSL_CERT_NONE);
2046 case SSL_VERIFY_PEER:
2047 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2048 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2049 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2050 }
2051 PyErr_SetString(PySSLErrorObject,
2052 "invalid return value from SSL_CTX_get_verify_mode");
2053 return NULL;
2054}
2055
2056static int
2057set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2058{
2059 int n, mode;
2060 if (!PyArg_Parse(arg, "i", &n))
2061 return -1;
2062 if (n == PY_SSL_CERT_NONE)
2063 mode = SSL_VERIFY_NONE;
2064 else if (n == PY_SSL_CERT_OPTIONAL)
2065 mode = SSL_VERIFY_PEER;
2066 else if (n == PY_SSL_CERT_REQUIRED)
2067 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2068 else {
2069 PyErr_SetString(PyExc_ValueError,
2070 "invalid value for verify_mode");
2071 return -1;
2072 }
2073 SSL_CTX_set_verify(self->ctx, mode, NULL);
2074 return 0;
2075}
2076
2077static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002078get_options(PySSLContext *self, void *c)
2079{
2080 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2081}
2082
2083static int
2084set_options(PySSLContext *self, PyObject *arg, void *c)
2085{
2086 long new_opts, opts, set, clear;
2087 if (!PyArg_Parse(arg, "l", &new_opts))
2088 return -1;
2089 opts = SSL_CTX_get_options(self->ctx);
2090 clear = opts & ~new_opts;
2091 set = ~opts & new_opts;
2092 if (clear) {
2093#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2094 SSL_CTX_clear_options(self->ctx, clear);
2095#else
2096 PyErr_SetString(PyExc_ValueError,
2097 "can't clear options before OpenSSL 0.9.8m");
2098 return -1;
2099#endif
2100 }
2101 if (set)
2102 SSL_CTX_set_options(self->ctx, set);
2103 return 0;
2104}
2105
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002106typedef struct {
2107 PyThreadState *thread_state;
2108 PyObject *callable;
2109 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002110 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002111 int error;
2112} _PySSLPasswordInfo;
2113
2114static int
2115_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2116 const char *bad_type_error)
2117{
2118 /* Set the password and size fields of a _PySSLPasswordInfo struct
2119 from a unicode, bytes, or byte array object.
2120 The password field will be dynamically allocated and must be freed
2121 by the caller */
2122 PyObject *password_bytes = NULL;
2123 const char *data = NULL;
2124 Py_ssize_t size;
2125
2126 if (PyUnicode_Check(password)) {
2127 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2128 if (!password_bytes) {
2129 goto error;
2130 }
2131 data = PyBytes_AS_STRING(password_bytes);
2132 size = PyBytes_GET_SIZE(password_bytes);
2133 } else if (PyBytes_Check(password)) {
2134 data = PyBytes_AS_STRING(password);
2135 size = PyBytes_GET_SIZE(password);
2136 } else if (PyByteArray_Check(password)) {
2137 data = PyByteArray_AS_STRING(password);
2138 size = PyByteArray_GET_SIZE(password);
2139 } else {
2140 PyErr_SetString(PyExc_TypeError, bad_type_error);
2141 goto error;
2142 }
2143
Victor Stinner9ee02032013-06-23 15:08:23 +02002144 if (size > (Py_ssize_t)INT_MAX) {
2145 PyErr_Format(PyExc_ValueError,
2146 "password cannot be longer than %d bytes", INT_MAX);
2147 goto error;
2148 }
2149
Victor Stinner11ebff22013-07-07 17:07:52 +02002150 PyMem_Free(pw_info->password);
2151 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002152 if (!pw_info->password) {
2153 PyErr_SetString(PyExc_MemoryError,
2154 "unable to allocate password buffer");
2155 goto error;
2156 }
2157 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002158 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002159
2160 Py_XDECREF(password_bytes);
2161 return 1;
2162
2163error:
2164 Py_XDECREF(password_bytes);
2165 return 0;
2166}
2167
2168static int
2169_password_callback(char *buf, int size, int rwflag, void *userdata)
2170{
2171 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2172 PyObject *fn_ret = NULL;
2173
2174 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2175
2176 if (pw_info->callable) {
2177 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2178 if (!fn_ret) {
2179 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2180 core python API, so we could use it to add a frame here */
2181 goto error;
2182 }
2183
2184 if (!_pwinfo_set(pw_info, fn_ret,
2185 "password callback must return a string")) {
2186 goto error;
2187 }
2188 Py_CLEAR(fn_ret);
2189 }
2190
2191 if (pw_info->size > size) {
2192 PyErr_Format(PyExc_ValueError,
2193 "password cannot be longer than %d bytes", size);
2194 goto error;
2195 }
2196
2197 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2198 memcpy(buf, pw_info->password, pw_info->size);
2199 return pw_info->size;
2200
2201error:
2202 Py_XDECREF(fn_ret);
2203 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2204 pw_info->error = 1;
2205 return -1;
2206}
2207
Antoine Pitroub5218772010-05-21 09:56:06 +00002208static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002209load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2210{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002211 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2212 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002213 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002214 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2215 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2216 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002217 int r;
2218
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002219 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002220 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002221 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002222 "O|OO:load_cert_chain", kwlist,
2223 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002224 return NULL;
2225 if (keyfile == Py_None)
2226 keyfile = NULL;
2227 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2228 PyErr_SetString(PyExc_TypeError,
2229 "certfile should be a valid filesystem path");
2230 return NULL;
2231 }
2232 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2233 PyErr_SetString(PyExc_TypeError,
2234 "keyfile should be a valid filesystem path");
2235 goto error;
2236 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002237 if (password && password != Py_None) {
2238 if (PyCallable_Check(password)) {
2239 pw_info.callable = password;
2240 } else if (!_pwinfo_set(&pw_info, password,
2241 "password should be a string or callable")) {
2242 goto error;
2243 }
2244 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2245 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2246 }
2247 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002248 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2249 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002250 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002251 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002252 if (pw_info.error) {
2253 ERR_clear_error();
2254 /* the password callback has already set the error information */
2255 }
2256 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002257 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002258 PyErr_SetFromErrno(PyExc_IOError);
2259 }
2260 else {
2261 _setSSLError(NULL, 0, __FILE__, __LINE__);
2262 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002263 goto error;
2264 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002265 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002266 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002267 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2268 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002269 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2270 Py_CLEAR(keyfile_bytes);
2271 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002272 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002273 if (pw_info.error) {
2274 ERR_clear_error();
2275 /* the password callback has already set the error information */
2276 }
2277 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002278 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002279 PyErr_SetFromErrno(PyExc_IOError);
2280 }
2281 else {
2282 _setSSLError(NULL, 0, __FILE__, __LINE__);
2283 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002284 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002285 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002286 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002287 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002288 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002289 if (r != 1) {
2290 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002291 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002292 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002293 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2294 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002295 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002296 Py_RETURN_NONE;
2297
2298error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002299 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2300 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002301 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002302 Py_XDECREF(keyfile_bytes);
2303 Py_XDECREF(certfile_bytes);
2304 return NULL;
2305}
2306
Christian Heimesefff7062013-11-21 03:35:02 +01002307/* internal helper function, returns -1 on error
2308 */
2309static int
2310_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2311 int filetype)
2312{
2313 BIO *biobuf = NULL;
2314 X509_STORE *store;
2315 int retval = 0, err, loaded = 0;
2316
2317 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2318
2319 if (len <= 0) {
2320 PyErr_SetString(PyExc_ValueError,
2321 "Empty certificate data");
2322 return -1;
2323 } else if (len > INT_MAX) {
2324 PyErr_SetString(PyExc_OverflowError,
2325 "Certificate data is too long.");
2326 return -1;
2327 }
2328
2329 biobuf = BIO_new_mem_buf(data, len);
2330 if (biobuf == NULL) {
2331 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2332 return -1;
2333 }
2334
2335 store = SSL_CTX_get_cert_store(self->ctx);
2336 assert(store != NULL);
2337
2338 while (1) {
2339 X509 *cert = NULL;
2340 int r;
2341
2342 if (filetype == SSL_FILETYPE_ASN1) {
2343 cert = d2i_X509_bio(biobuf, NULL);
2344 } else {
2345 cert = PEM_read_bio_X509(biobuf, NULL,
2346 self->ctx->default_passwd_callback,
2347 self->ctx->default_passwd_callback_userdata);
2348 }
2349 if (cert == NULL) {
2350 break;
2351 }
2352 r = X509_STORE_add_cert(store, cert);
2353 X509_free(cert);
2354 if (!r) {
2355 err = ERR_peek_last_error();
2356 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2357 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2358 /* cert already in hash table, not an error */
2359 ERR_clear_error();
2360 } else {
2361 break;
2362 }
2363 }
2364 loaded++;
2365 }
2366
2367 err = ERR_peek_last_error();
2368 if ((filetype == SSL_FILETYPE_ASN1) &&
2369 (loaded > 0) &&
2370 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2371 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2372 /* EOF ASN1 file, not an error */
2373 ERR_clear_error();
2374 retval = 0;
2375 } else if ((filetype == SSL_FILETYPE_PEM) &&
2376 (loaded > 0) &&
2377 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2378 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2379 /* EOF PEM file, not an error */
2380 ERR_clear_error();
2381 retval = 0;
2382 } else {
2383 _setSSLError(NULL, 0, __FILE__, __LINE__);
2384 retval = -1;
2385 }
2386
2387 BIO_free(biobuf);
2388 return retval;
2389}
2390
2391
Antoine Pitrou152efa22010-05-16 18:19:27 +00002392static PyObject *
2393load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2394{
Christian Heimesefff7062013-11-21 03:35:02 +01002395 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2396 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002397 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2398 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002399 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002400
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002401 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002402 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002403 "|OOO:load_verify_locations", kwlist,
2404 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002405 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002406
Antoine Pitrou152efa22010-05-16 18:19:27 +00002407 if (cafile == Py_None)
2408 cafile = NULL;
2409 if (capath == Py_None)
2410 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002411 if (cadata == Py_None)
2412 cadata = NULL;
2413
2414 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002415 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002416 "cafile, capath and cadata cannot be all omitted");
2417 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002418 }
2419 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2420 PyErr_SetString(PyExc_TypeError,
2421 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002422 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002423 }
2424 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002425 PyErr_SetString(PyExc_TypeError,
2426 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002427 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002428 }
Christian Heimesefff7062013-11-21 03:35:02 +01002429
2430 /* validata cadata type and load cadata */
2431 if (cadata) {
2432 Py_buffer buf;
2433 PyObject *cadata_ascii = NULL;
2434
2435 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2436 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2437 PyBuffer_Release(&buf);
2438 PyErr_SetString(PyExc_TypeError,
2439 "cadata should be a contiguous buffer with "
2440 "a single dimension");
2441 goto error;
2442 }
2443 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2444 PyBuffer_Release(&buf);
2445 if (r == -1) {
2446 goto error;
2447 }
2448 } else {
2449 PyErr_Clear();
2450 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2451 if (cadata_ascii == NULL) {
2452 PyErr_SetString(PyExc_TypeError,
2453 "cadata should be a ASCII string or a "
2454 "bytes-like object");
2455 goto error;
2456 }
2457 r = _add_ca_certs(self,
2458 PyBytes_AS_STRING(cadata_ascii),
2459 PyBytes_GET_SIZE(cadata_ascii),
2460 SSL_FILETYPE_PEM);
2461 Py_DECREF(cadata_ascii);
2462 if (r == -1) {
2463 goto error;
2464 }
2465 }
2466 }
2467
2468 /* load cafile or capath */
2469 if (cafile || capath) {
2470 if (cafile)
2471 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2472 if (capath)
2473 capath_buf = PyBytes_AS_STRING(capath_bytes);
2474 PySSL_BEGIN_ALLOW_THREADS
2475 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2476 PySSL_END_ALLOW_THREADS
2477 if (r != 1) {
2478 ok = 0;
2479 if (errno != 0) {
2480 ERR_clear_error();
2481 PyErr_SetFromErrno(PyExc_IOError);
2482 }
2483 else {
2484 _setSSLError(NULL, 0, __FILE__, __LINE__);
2485 }
2486 goto error;
2487 }
2488 }
2489 goto end;
2490
2491 error:
2492 ok = 0;
2493 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002494 Py_XDECREF(cafile_bytes);
2495 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002496 if (ok) {
2497 Py_RETURN_NONE;
2498 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002499 return NULL;
2500 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002501}
2502
2503static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002504load_dh_params(PySSLContext *self, PyObject *filepath)
2505{
2506 FILE *f;
2507 DH *dh;
2508
Victor Stinnerdaf45552013-08-28 00:53:59 +02002509 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002510 if (f == NULL) {
2511 if (!PyErr_Occurred())
2512 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2513 return NULL;
2514 }
2515 errno = 0;
2516 PySSL_BEGIN_ALLOW_THREADS
2517 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002518 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002519 PySSL_END_ALLOW_THREADS
2520 if (dh == NULL) {
2521 if (errno != 0) {
2522 ERR_clear_error();
2523 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2524 }
2525 else {
2526 _setSSLError(NULL, 0, __FILE__, __LINE__);
2527 }
2528 return NULL;
2529 }
2530 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2531 _setSSLError(NULL, 0, __FILE__, __LINE__);
2532 DH_free(dh);
2533 Py_RETURN_NONE;
2534}
2535
2536static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002537context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2538{
Antoine Pitroud5323212010-10-22 18:19:07 +00002539 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002540 PySocketSockObject *sock;
2541 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002542 char *hostname = NULL;
2543 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002544
Antoine Pitroud5323212010-10-22 18:19:07 +00002545 /* server_hostname is either None (or absent), or to be encoded
2546 using the idna encoding. */
2547 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002548 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002549 &sock, &server_side,
2550 Py_TYPE(Py_None), &hostname_obj)) {
2551 PyErr_Clear();
2552 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2553 PySocketModule.Sock_Type,
2554 &sock, &server_side,
2555 "idna", &hostname))
2556 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002557#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002558 PyMem_Free(hostname);
2559 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2560 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002561 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002562#endif
2563 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002564
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002565 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002566 hostname);
2567 if (hostname != NULL)
2568 PyMem_Free(hostname);
2569 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002570}
2571
Antoine Pitroub0182c82010-10-12 20:09:02 +00002572static PyObject *
2573session_stats(PySSLContext *self, PyObject *unused)
2574{
2575 int r;
2576 PyObject *value, *stats = PyDict_New();
2577 if (!stats)
2578 return NULL;
2579
2580#define ADD_STATS(SSL_NAME, KEY_NAME) \
2581 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2582 if (value == NULL) \
2583 goto error; \
2584 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2585 Py_DECREF(value); \
2586 if (r < 0) \
2587 goto error;
2588
2589 ADD_STATS(number, "number");
2590 ADD_STATS(connect, "connect");
2591 ADD_STATS(connect_good, "connect_good");
2592 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2593 ADD_STATS(accept, "accept");
2594 ADD_STATS(accept_good, "accept_good");
2595 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2596 ADD_STATS(accept, "accept");
2597 ADD_STATS(hits, "hits");
2598 ADD_STATS(misses, "misses");
2599 ADD_STATS(timeouts, "timeouts");
2600 ADD_STATS(cache_full, "cache_full");
2601
2602#undef ADD_STATS
2603
2604 return stats;
2605
2606error:
2607 Py_DECREF(stats);
2608 return NULL;
2609}
2610
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002611static PyObject *
2612set_default_verify_paths(PySSLContext *self, PyObject *unused)
2613{
2614 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2615 _setSSLError(NULL, 0, __FILE__, __LINE__);
2616 return NULL;
2617 }
2618 Py_RETURN_NONE;
2619}
2620
Antoine Pitrou501da612011-12-21 09:27:41 +01002621#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002622static PyObject *
2623set_ecdh_curve(PySSLContext *self, PyObject *name)
2624{
2625 PyObject *name_bytes;
2626 int nid;
2627 EC_KEY *key;
2628
2629 if (!PyUnicode_FSConverter(name, &name_bytes))
2630 return NULL;
2631 assert(PyBytes_Check(name_bytes));
2632 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2633 Py_DECREF(name_bytes);
2634 if (nid == 0) {
2635 PyErr_Format(PyExc_ValueError,
2636 "unknown elliptic curve name %R", name);
2637 return NULL;
2638 }
2639 key = EC_KEY_new_by_curve_name(nid);
2640 if (key == NULL) {
2641 _setSSLError(NULL, 0, __FILE__, __LINE__);
2642 return NULL;
2643 }
2644 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2645 EC_KEY_free(key);
2646 Py_RETURN_NONE;
2647}
Antoine Pitrou501da612011-12-21 09:27:41 +01002648#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002649
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002650#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002651static int
2652_servername_callback(SSL *s, int *al, void *args)
2653{
2654 int ret;
2655 PySSLContext *ssl_ctx = (PySSLContext *) args;
2656 PySSLSocket *ssl;
2657 PyObject *servername_o;
2658 PyObject *servername_idna;
2659 PyObject *result;
2660 /* The high-level ssl.SSLSocket object */
2661 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002662 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002663#ifdef WITH_THREAD
2664 PyGILState_STATE gstate = PyGILState_Ensure();
2665#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002666
2667 if (ssl_ctx->set_hostname == NULL) {
2668 /* remove race condition in this the call back while if removing the
2669 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002670#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002671 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002672#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002673 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002674 }
2675
2676 ssl = SSL_get_app_data(s);
2677 assert(PySSLSocket_Check(ssl));
2678 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2679 Py_INCREF(ssl_socket);
2680 if (ssl_socket == Py_None) {
2681 goto error;
2682 }
Victor Stinner7e001512013-06-25 00:44:31 +02002683
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002684 if (servername == NULL) {
2685 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2686 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002687 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002688 else {
2689 servername_o = PyBytes_FromString(servername);
2690 if (servername_o == NULL) {
2691 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2692 goto error;
2693 }
2694 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2695 if (servername_idna == NULL) {
2696 PyErr_WriteUnraisable(servername_o);
2697 Py_DECREF(servername_o);
2698 goto error;
2699 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002700 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002701 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2702 servername_idna, ssl_ctx, NULL);
2703 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002704 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002705 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002706
2707 if (result == NULL) {
2708 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2709 *al = SSL_AD_HANDSHAKE_FAILURE;
2710 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2711 }
2712 else {
2713 if (result != Py_None) {
2714 *al = (int) PyLong_AsLong(result);
2715 if (PyErr_Occurred()) {
2716 PyErr_WriteUnraisable(result);
2717 *al = SSL_AD_INTERNAL_ERROR;
2718 }
2719 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2720 }
2721 else {
2722 ret = SSL_TLSEXT_ERR_OK;
2723 }
2724 Py_DECREF(result);
2725 }
2726
Stefan Krah20d60802013-01-17 17:07:17 +01002727#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002728 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002729#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002730 return ret;
2731
2732error:
2733 Py_DECREF(ssl_socket);
2734 *al = SSL_AD_INTERNAL_ERROR;
2735 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002736#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002737 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002738#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002739 return ret;
2740}
Antoine Pitroua5963382013-03-30 16:39:00 +01002741#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002742
2743PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2744"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002745\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002746This sets a callback that will be called when a server name is provided by\n\
2747the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002748\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002749If the argument is None then the callback is disabled. The method is called\n\
2750with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002751See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002752
2753static PyObject *
2754set_servername_callback(PySSLContext *self, PyObject *args)
2755{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002756#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002757 PyObject *cb;
2758
2759 if (!PyArg_ParseTuple(args, "O", &cb))
2760 return NULL;
2761
2762 Py_CLEAR(self->set_hostname);
2763 if (cb == Py_None) {
2764 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2765 }
2766 else {
2767 if (!PyCallable_Check(cb)) {
2768 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2769 PyErr_SetString(PyExc_TypeError,
2770 "not a callable object");
2771 return NULL;
2772 }
2773 Py_INCREF(cb);
2774 self->set_hostname = cb;
2775 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
2776 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
2777 }
2778 Py_RETURN_NONE;
2779#else
2780 PyErr_SetString(PyExc_NotImplementedError,
2781 "The TLS extension servername callback, "
2782 "SSL_CTX_set_tlsext_servername_callback, "
2783 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002784 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002785#endif
2786}
2787
Christian Heimes9a5395a2013-06-17 15:44:12 +02002788PyDoc_STRVAR(PySSL_get_stats_doc,
2789"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
2790\n\
2791Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
2792CA extension and certificate revocation lists inside the context's cert\n\
2793store.\n\
2794NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2795been used at least once.");
2796
2797static PyObject *
2798cert_store_stats(PySSLContext *self)
2799{
2800 X509_STORE *store;
2801 X509_OBJECT *obj;
2802 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
2803
2804 store = SSL_CTX_get_cert_store(self->ctx);
2805 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2806 obj = sk_X509_OBJECT_value(store->objs, i);
2807 switch (obj->type) {
2808 case X509_LU_X509:
2809 x509++;
2810 if (X509_check_ca(obj->data.x509)) {
2811 ca++;
2812 }
2813 break;
2814 case X509_LU_CRL:
2815 crl++;
2816 break;
2817 case X509_LU_PKEY:
2818 pkey++;
2819 break;
2820 default:
2821 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
2822 * As far as I can tell they are internal states and never
2823 * stored in a cert store */
2824 break;
2825 }
2826 }
2827 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
2828 "x509_ca", ca);
2829}
2830
2831PyDoc_STRVAR(PySSL_get_ca_certs_doc,
2832"get_ca_certs([der=False]) -> list of loaded certificate\n\
2833\n\
2834Returns a list of dicts with information of loaded CA certs. If the\n\
2835optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
2836NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2837been used at least once.");
2838
2839static PyObject *
2840get_ca_certs(PySSLContext *self, PyObject *args)
2841{
2842 X509_STORE *store;
2843 PyObject *ci = NULL, *rlist = NULL;
2844 int i;
2845 int binary_mode = 0;
2846
2847 if (!PyArg_ParseTuple(args, "|p:get_ca_certs", &binary_mode)) {
2848 return NULL;
2849 }
2850
2851 if ((rlist = PyList_New(0)) == NULL) {
2852 return NULL;
2853 }
2854
2855 store = SSL_CTX_get_cert_store(self->ctx);
2856 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2857 X509_OBJECT *obj;
2858 X509 *cert;
2859
2860 obj = sk_X509_OBJECT_value(store->objs, i);
2861 if (obj->type != X509_LU_X509) {
2862 /* not a x509 cert */
2863 continue;
2864 }
2865 /* CA for any purpose */
2866 cert = obj->data.x509;
2867 if (!X509_check_ca(cert)) {
2868 continue;
2869 }
2870 if (binary_mode) {
2871 ci = _certificate_to_der(cert);
2872 } else {
2873 ci = _decode_certificate(cert);
2874 }
2875 if (ci == NULL) {
2876 goto error;
2877 }
2878 if (PyList_Append(rlist, ci) == -1) {
2879 goto error;
2880 }
2881 Py_CLEAR(ci);
2882 }
2883 return rlist;
2884
2885 error:
2886 Py_XDECREF(ci);
2887 Py_XDECREF(rlist);
2888 return NULL;
2889}
2890
2891
Antoine Pitrou152efa22010-05-16 18:19:27 +00002892static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00002893 {"options", (getter) get_options,
2894 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002895 {"verify_mode", (getter) get_verify_mode,
2896 (setter) set_verify_mode, NULL},
2897 {NULL}, /* sentinel */
2898};
2899
2900static struct PyMethodDef context_methods[] = {
2901 {"_wrap_socket", (PyCFunction) context_wrap_socket,
2902 METH_VARARGS | METH_KEYWORDS, NULL},
2903 {"set_ciphers", (PyCFunction) set_ciphers,
2904 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002905 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
2906 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002907 {"load_cert_chain", (PyCFunction) load_cert_chain,
2908 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002909 {"load_dh_params", (PyCFunction) load_dh_params,
2910 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002911 {"load_verify_locations", (PyCFunction) load_verify_locations,
2912 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00002913 {"session_stats", (PyCFunction) session_stats,
2914 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002915 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
2916 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002917#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002918 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
2919 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01002920#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002921 {"set_servername_callback", (PyCFunction) set_servername_callback,
2922 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02002923 {"cert_store_stats", (PyCFunction) cert_store_stats,
2924 METH_NOARGS, PySSL_get_stats_doc},
2925 {"get_ca_certs", (PyCFunction) get_ca_certs,
2926 METH_VARARGS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00002927 {NULL, NULL} /* sentinel */
2928};
2929
2930static PyTypeObject PySSLContext_Type = {
2931 PyVarObject_HEAD_INIT(NULL, 0)
2932 "_ssl._SSLContext", /*tp_name*/
2933 sizeof(PySSLContext), /*tp_basicsize*/
2934 0, /*tp_itemsize*/
2935 (destructor)context_dealloc, /*tp_dealloc*/
2936 0, /*tp_print*/
2937 0, /*tp_getattr*/
2938 0, /*tp_setattr*/
2939 0, /*tp_reserved*/
2940 0, /*tp_repr*/
2941 0, /*tp_as_number*/
2942 0, /*tp_as_sequence*/
2943 0, /*tp_as_mapping*/
2944 0, /*tp_hash*/
2945 0, /*tp_call*/
2946 0, /*tp_str*/
2947 0, /*tp_getattro*/
2948 0, /*tp_setattro*/
2949 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002950 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002951 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002952 (traverseproc) context_traverse, /*tp_traverse*/
2953 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002954 0, /*tp_richcompare*/
2955 0, /*tp_weaklistoffset*/
2956 0, /*tp_iter*/
2957 0, /*tp_iternext*/
2958 context_methods, /*tp_methods*/
2959 0, /*tp_members*/
2960 context_getsetlist, /*tp_getset*/
2961 0, /*tp_base*/
2962 0, /*tp_dict*/
2963 0, /*tp_descr_get*/
2964 0, /*tp_descr_set*/
2965 0, /*tp_dictoffset*/
2966 0, /*tp_init*/
2967 0, /*tp_alloc*/
2968 context_new, /*tp_new*/
2969};
2970
2971
2972
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002973#ifdef HAVE_OPENSSL_RAND
2974
2975/* helper routines for seeding the SSL PRNG */
2976static PyObject *
2977PySSL_RAND_add(PyObject *self, PyObject *args)
2978{
2979 char *buf;
2980 int len;
2981 double entropy;
2982
2983 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00002984 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002985 RAND_add(buf, len, entropy);
2986 Py_INCREF(Py_None);
2987 return Py_None;
2988}
2989
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002990PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002991"RAND_add(string, entropy)\n\
2992\n\
2993Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00002994bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002995
2996static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02002997PySSL_RAND(int len, int pseudo)
2998{
2999 int ok;
3000 PyObject *bytes;
3001 unsigned long err;
3002 const char *errstr;
3003 PyObject *v;
3004
3005 bytes = PyBytes_FromStringAndSize(NULL, len);
3006 if (bytes == NULL)
3007 return NULL;
3008 if (pseudo) {
3009 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3010 if (ok == 0 || ok == 1)
3011 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3012 }
3013 else {
3014 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3015 if (ok == 1)
3016 return bytes;
3017 }
3018 Py_DECREF(bytes);
3019
3020 err = ERR_get_error();
3021 errstr = ERR_reason_error_string(err);
3022 v = Py_BuildValue("(ks)", err, errstr);
3023 if (v != NULL) {
3024 PyErr_SetObject(PySSLErrorObject, v);
3025 Py_DECREF(v);
3026 }
3027 return NULL;
3028}
3029
3030static PyObject *
3031PySSL_RAND_bytes(PyObject *self, PyObject *args)
3032{
3033 int len;
3034 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3035 return NULL;
3036 return PySSL_RAND(len, 0);
3037}
3038
3039PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3040"RAND_bytes(n) -> bytes\n\
3041\n\
3042Generate n cryptographically strong pseudo-random bytes.");
3043
3044static PyObject *
3045PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3046{
3047 int len;
3048 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3049 return NULL;
3050 return PySSL_RAND(len, 1);
3051}
3052
3053PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3054"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3055\n\
3056Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3057generated are cryptographically strong.");
3058
3059static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003060PySSL_RAND_status(PyObject *self)
3061{
Christian Heimes217cfd12007-12-02 14:31:20 +00003062 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003063}
3064
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003065PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003066"RAND_status() -> 0 or 1\n\
3067\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003068Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3069It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3070using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003071
3072static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003073PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003074{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003075 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003076 int bytes;
3077
Jesus Ceac8754a12012-09-11 02:00:58 +02003078 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003079 PyUnicode_FSConverter, &path))
3080 return NULL;
3081
3082 bytes = RAND_egd(PyBytes_AsString(path));
3083 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003084 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003085 PyErr_SetString(PySSLErrorObject,
3086 "EGD connection failed or EGD did not return "
3087 "enough data to seed the PRNG");
3088 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003089 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003090 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003091}
3092
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003093PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003094"RAND_egd(path) -> bytes\n\
3095\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003096Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3097Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003098fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003099
Christian Heimesf77b4b22013-08-21 13:26:05 +02003100#endif /* HAVE_OPENSSL_RAND */
3101
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003102
Christian Heimes6d7ad132013-06-09 18:02:55 +02003103PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3104"get_default_verify_paths() -> tuple\n\
3105\n\
3106Return search paths and environment vars that are used by SSLContext's\n\
3107set_default_verify_paths() to load default CAs. The values are\n\
3108'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3109
3110static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003111PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003112{
3113 PyObject *ofile_env = NULL;
3114 PyObject *ofile = NULL;
3115 PyObject *odir_env = NULL;
3116 PyObject *odir = NULL;
3117
3118#define convert(info, target) { \
3119 const char *tmp = (info); \
3120 target = NULL; \
3121 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3122 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3123 target = PyBytes_FromString(tmp); } \
3124 if (!target) goto error; \
3125 } while(0)
3126
3127 convert(X509_get_default_cert_file_env(), ofile_env);
3128 convert(X509_get_default_cert_file(), ofile);
3129 convert(X509_get_default_cert_dir_env(), odir_env);
3130 convert(X509_get_default_cert_dir(), odir);
3131#undef convert
3132
Christian Heimes200bb1b2013-06-14 15:14:29 +02003133 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003134
3135 error:
3136 Py_XDECREF(ofile_env);
3137 Py_XDECREF(ofile);
3138 Py_XDECREF(odir_env);
3139 Py_XDECREF(odir);
3140 return NULL;
3141}
3142
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003143static PyObject*
3144asn1obj2py(ASN1_OBJECT *obj)
3145{
3146 int nid;
3147 const char *ln, *sn;
3148 char buf[100];
3149 int buflen;
3150
3151 nid = OBJ_obj2nid(obj);
3152 if (nid == NID_undef) {
3153 PyErr_Format(PyExc_ValueError, "Unknown object");
3154 return NULL;
3155 }
3156 sn = OBJ_nid2sn(nid);
3157 ln = OBJ_nid2ln(nid);
3158 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3159 if (buflen < 0) {
3160 _setSSLError(NULL, 0, __FILE__, __LINE__);
3161 return NULL;
3162 }
3163 if (buflen) {
3164 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3165 } else {
3166 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3167 }
3168}
3169
3170PyDoc_STRVAR(PySSL_txt2obj_doc,
3171"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3172\n\
3173Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3174objects are looked up by OID. With name=True short and long name are also\n\
3175matched.");
3176
3177static PyObject*
3178PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3179{
3180 char *kwlist[] = {"txt", "name", NULL};
3181 PyObject *result = NULL;
3182 char *txt;
3183 int name = 0;
3184 ASN1_OBJECT *obj;
3185
3186 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3187 kwlist, &txt, &name)) {
3188 return NULL;
3189 }
3190 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3191 if (obj == NULL) {
3192 PyErr_Format(PyExc_ValueError, "Unknown object");
3193 return NULL;
3194 }
3195 result = asn1obj2py(obj);
3196 ASN1_OBJECT_free(obj);
3197 return result;
3198}
3199
3200PyDoc_STRVAR(PySSL_nid2obj_doc,
3201"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3202\n\
3203Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3204
3205static PyObject*
3206PySSL_nid2obj(PyObject *self, PyObject *args)
3207{
3208 PyObject *result = NULL;
3209 int nid;
3210 ASN1_OBJECT *obj;
3211
3212 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3213 return NULL;
3214 }
3215 if (nid < NID_undef) {
3216 PyErr_Format(PyExc_ValueError, "NID must be positive.");
3217 return NULL;
3218 }
3219 obj = OBJ_nid2obj(nid);
3220 if (obj == NULL) {
3221 PyErr_Format(PyExc_ValueError, "Unknown NID");
3222 return NULL;
3223 }
3224 result = asn1obj2py(obj);
3225 ASN1_OBJECT_free(obj);
3226 return result;
3227}
3228
3229
Christian Heimes46bebee2013-06-09 19:03:31 +02003230#ifdef _MSC_VER
3231PyDoc_STRVAR(PySSL_enum_cert_store_doc,
3232"enum_cert_store(store_name, cert_type='certificate') -> []\n\
3233\n\
3234Retrieve certificates from Windows' cert store. store_name may be one of\n\
3235'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3236cert_type must be either 'certificate' or 'crl'.\n\
3237The function returns a list of (bytes, encoding_type) tuples. The\n\
3238encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3239PKCS_7_ASN_ENCODING.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003240
Christian Heimes46bebee2013-06-09 19:03:31 +02003241static PyObject *
3242PySSL_enum_cert_store(PyObject *self, PyObject *args, PyObject *kwds)
3243{
3244 char *kwlist[] = {"store_name", "cert_type", NULL};
3245 char *store_name;
3246 char *cert_type = "certificate";
3247 HCERTSTORE hStore = NULL;
3248 PyObject *result = NULL;
3249 PyObject *tup = NULL, *cert = NULL, *enc = NULL;
3250 int ok = 1;
3251
3252 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_cert_store",
3253 kwlist, &store_name, &cert_type)) {
3254 return NULL;
3255 }
3256
3257 if ((strcmp(cert_type, "certificate") != 0) &&
3258 (strcmp(cert_type, "crl") != 0)) {
3259 return PyErr_Format(PyExc_ValueError,
3260 "cert_type must be 'certificate' or 'crl', "
3261 "not %.100s", cert_type);
3262 }
3263
3264 if ((result = PyList_New(0)) == NULL) {
3265 return NULL;
3266 }
3267
Richard Oudkerkcabbde92013-08-24 23:46:27 +01003268 if ((hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name)) == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003269 Py_DECREF(result);
3270 return PyErr_SetFromWindowsErr(GetLastError());
3271 }
3272
3273 if (strcmp(cert_type, "certificate") == 0) {
3274 PCCERT_CONTEXT pCertCtx = NULL;
3275 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3276 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3277 pCertCtx->cbCertEncoded);
3278 if (!cert) {
3279 ok = 0;
3280 break;
3281 }
3282 if ((enc = PyLong_FromLong(pCertCtx->dwCertEncodingType)) == NULL) {
3283 ok = 0;
3284 break;
3285 }
3286 if ((tup = PyTuple_New(2)) == NULL) {
3287 ok = 0;
3288 break;
3289 }
3290 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3291 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3292
3293 if (PyList_Append(result, tup) < 0) {
3294 ok = 0;
3295 break;
3296 }
3297 Py_CLEAR(tup);
3298 }
3299 if (pCertCtx) {
3300 /* loop ended with an error, need to clean up context manually */
3301 CertFreeCertificateContext(pCertCtx);
3302 }
3303 } else {
3304 PCCRL_CONTEXT pCrlCtx = NULL;
3305 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3306 cert = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3307 pCrlCtx->cbCrlEncoded);
3308 if (!cert) {
3309 ok = 0;
3310 break;
3311 }
3312 if ((enc = PyLong_FromLong(pCrlCtx->dwCertEncodingType)) == NULL) {
3313 ok = 0;
3314 break;
3315 }
3316 if ((tup = PyTuple_New(2)) == NULL) {
3317 ok = 0;
3318 break;
3319 }
3320 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3321 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3322
3323 if (PyList_Append(result, tup) < 0) {
3324 ok = 0;
3325 break;
3326 }
3327 Py_CLEAR(tup);
3328 }
3329 if (pCrlCtx) {
3330 /* loop ended with an error, need to clean up context manually */
3331 CertFreeCRLContext(pCrlCtx);
3332 }
3333 }
3334
3335 /* In error cases cert, enc and tup may not be NULL */
3336 Py_XDECREF(cert);
3337 Py_XDECREF(enc);
3338 Py_XDECREF(tup);
3339
3340 if (!CertCloseStore(hStore, 0)) {
3341 /* This error case might shadow another exception.*/
3342 Py_DECREF(result);
3343 return PyErr_SetFromWindowsErr(GetLastError());
3344 }
3345 if (ok) {
3346 return result;
3347 } else {
3348 Py_DECREF(result);
3349 return NULL;
3350 }
3351}
3352#endif
Bill Janssen40a0f662008-08-12 16:56:25 +00003353
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003354/* List of functions exported by this module. */
3355
3356static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003357 {"_test_decode_cert", PySSL_test_decode_certificate,
3358 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003359#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003360 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3361 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003362 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3363 PySSL_RAND_bytes_doc},
3364 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3365 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003366 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003367 PySSL_RAND_egd_doc},
3368 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3369 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003370#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003371 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003372 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003373#ifdef _MSC_VER
3374 {"enum_cert_store", (PyCFunction)PySSL_enum_cert_store,
3375 METH_VARARGS | METH_KEYWORDS, PySSL_enum_cert_store_doc},
3376#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003377 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3378 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3379 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3380 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003381 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003382};
3383
3384
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003385#ifdef WITH_THREAD
3386
3387/* an implementation of OpenSSL threading operations in terms
3388 of the Python C thread library */
3389
3390static PyThread_type_lock *_ssl_locks = NULL;
3391
Christian Heimes4d98ca92013-08-19 17:36:29 +02003392#if OPENSSL_VERSION_NUMBER >= 0x10000000
3393/* use new CRYPTO_THREADID API. */
3394static void
3395_ssl_threadid_callback(CRYPTO_THREADID *id)
3396{
3397 CRYPTO_THREADID_set_numeric(id,
3398 (unsigned long)PyThread_get_thread_ident());
3399}
3400#else
3401/* deprecated CRYPTO_set_id_callback() API. */
3402static unsigned long
3403_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003404 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003405}
Christian Heimes4d98ca92013-08-19 17:36:29 +02003406#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003407
Bill Janssen6e027db2007-11-15 22:23:56 +00003408static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003409 (int mode, int n, const char *file, int line) {
3410 /* this function is needed to perform locking on shared data
3411 structures. (Note that OpenSSL uses a number of global data
3412 structures that will be implicitly shared whenever multiple
3413 threads use OpenSSL.) Multi-threaded applications will
3414 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003415
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003416 locking_function() must be able to handle up to
3417 CRYPTO_num_locks() different mutex locks. It sets the n-th
3418 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003419
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003420 file and line are the file number of the function setting the
3421 lock. They can be useful for debugging.
3422 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003423
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003424 if ((_ssl_locks == NULL) ||
3425 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3426 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003427
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003428 if (mode & CRYPTO_LOCK) {
3429 PyThread_acquire_lock(_ssl_locks[n], 1);
3430 } else {
3431 PyThread_release_lock(_ssl_locks[n]);
3432 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003433}
3434
3435static int _setup_ssl_threads(void) {
3436
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003437 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003438
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003439 if (_ssl_locks == NULL) {
3440 _ssl_locks_count = CRYPTO_num_locks();
3441 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02003442 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003443 if (_ssl_locks == NULL)
3444 return 0;
3445 memset(_ssl_locks, 0,
3446 sizeof(PyThread_type_lock) * _ssl_locks_count);
3447 for (i = 0; i < _ssl_locks_count; i++) {
3448 _ssl_locks[i] = PyThread_allocate_lock();
3449 if (_ssl_locks[i] == NULL) {
3450 unsigned int j;
3451 for (j = 0; j < i; j++) {
3452 PyThread_free_lock(_ssl_locks[j]);
3453 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003454 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003455 return 0;
3456 }
3457 }
3458 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003459#if OPENSSL_VERSION_NUMBER >= 0x10000000
3460 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3461#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003462 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003463#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003464 }
3465 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003466}
3467
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003468#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003469
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003470PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003471"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003472for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003473
Martin v. Löwis1a214512008-06-11 05:26:20 +00003474
3475static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003476 PyModuleDef_HEAD_INIT,
3477 "_ssl",
3478 module_doc,
3479 -1,
3480 PySSL_methods,
3481 NULL,
3482 NULL,
3483 NULL,
3484 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003485};
3486
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003487
3488static void
3489parse_openssl_version(unsigned long libver,
3490 unsigned int *major, unsigned int *minor,
3491 unsigned int *fix, unsigned int *patch,
3492 unsigned int *status)
3493{
3494 *status = libver & 0xF;
3495 libver >>= 4;
3496 *patch = libver & 0xFF;
3497 libver >>= 8;
3498 *fix = libver & 0xFF;
3499 libver >>= 8;
3500 *minor = libver & 0xFF;
3501 libver >>= 8;
3502 *major = libver & 0xFF;
3503}
3504
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003505PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003506PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003507{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003508 PyObject *m, *d, *r;
3509 unsigned long libver;
3510 unsigned int major, minor, fix, patch, status;
3511 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003512 struct py_ssl_error_code *errcode;
3513 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003514
Antoine Pitrou152efa22010-05-16 18:19:27 +00003515 if (PyType_Ready(&PySSLContext_Type) < 0)
3516 return NULL;
3517 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003518 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003519
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003520 m = PyModule_Create(&_sslmodule);
3521 if (m == NULL)
3522 return NULL;
3523 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003524
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003525 /* Load _socket module and its C API */
3526 socket_api = PySocketModule_ImportModuleAndAPI();
3527 if (!socket_api)
3528 return NULL;
3529 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003530
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003531 /* Init OpenSSL */
3532 SSL_load_error_strings();
3533 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003534#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003535 /* note that this will start threading if not already started */
3536 if (!_setup_ssl_threads()) {
3537 return NULL;
3538 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003539#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003540 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003541
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003542 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003543 sslerror_type_slots[0].pfunc = PyExc_OSError;
3544 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003545 if (PySSLErrorObject == NULL)
3546 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003547
Antoine Pitrou41032a62011-10-27 23:56:55 +02003548 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3549 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3550 PySSLErrorObject, NULL);
3551 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3552 "ssl.SSLWantReadError", SSLWantReadError_doc,
3553 PySSLErrorObject, NULL);
3554 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3555 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3556 PySSLErrorObject, NULL);
3557 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3558 "ssl.SSLSyscallError", SSLSyscallError_doc,
3559 PySSLErrorObject, NULL);
3560 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3561 "ssl.SSLEOFError", SSLEOFError_doc,
3562 PySSLErrorObject, NULL);
3563 if (PySSLZeroReturnErrorObject == NULL
3564 || PySSLWantReadErrorObject == NULL
3565 || PySSLWantWriteErrorObject == NULL
3566 || PySSLSyscallErrorObject == NULL
3567 || PySSLEOFErrorObject == NULL)
3568 return NULL;
3569 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3570 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3571 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3572 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3573 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3574 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003575 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003576 if (PyDict_SetItemString(d, "_SSLContext",
3577 (PyObject *)&PySSLContext_Type) != 0)
3578 return NULL;
3579 if (PyDict_SetItemString(d, "_SSLSocket",
3580 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003581 return NULL;
3582 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3583 PY_SSL_ERROR_ZERO_RETURN);
3584 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3585 PY_SSL_ERROR_WANT_READ);
3586 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3587 PY_SSL_ERROR_WANT_WRITE);
3588 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3589 PY_SSL_ERROR_WANT_X509_LOOKUP);
3590 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3591 PY_SSL_ERROR_SYSCALL);
3592 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3593 PY_SSL_ERROR_SSL);
3594 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3595 PY_SSL_ERROR_WANT_CONNECT);
3596 /* non ssl.h errorcodes */
3597 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3598 PY_SSL_ERROR_EOF);
3599 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3600 PY_SSL_ERROR_INVALID_ERROR_CODE);
3601 /* cert requirements */
3602 PyModule_AddIntConstant(m, "CERT_NONE",
3603 PY_SSL_CERT_NONE);
3604 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3605 PY_SSL_CERT_OPTIONAL);
3606 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3607 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00003608
Christian Heimes46bebee2013-06-09 19:03:31 +02003609#ifdef _MSC_VER
3610 /* Windows dwCertEncodingType */
3611 PyModule_AddIntMacro(m, X509_ASN_ENCODING);
3612 PyModule_AddIntMacro(m, PKCS_7_ASN_ENCODING);
3613#endif
3614
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003615 /* Alert Descriptions from ssl.h */
3616 /* note RESERVED constants no longer intended for use have been removed */
3617 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
3618
3619#define ADD_AD_CONSTANT(s) \
3620 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
3621 SSL_AD_##s)
3622
3623 ADD_AD_CONSTANT(CLOSE_NOTIFY);
3624 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
3625 ADD_AD_CONSTANT(BAD_RECORD_MAC);
3626 ADD_AD_CONSTANT(RECORD_OVERFLOW);
3627 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
3628 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
3629 ADD_AD_CONSTANT(BAD_CERTIFICATE);
3630 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
3631 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
3632 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
3633 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
3634 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
3635 ADD_AD_CONSTANT(UNKNOWN_CA);
3636 ADD_AD_CONSTANT(ACCESS_DENIED);
3637 ADD_AD_CONSTANT(DECODE_ERROR);
3638 ADD_AD_CONSTANT(DECRYPT_ERROR);
3639 ADD_AD_CONSTANT(PROTOCOL_VERSION);
3640 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
3641 ADD_AD_CONSTANT(INTERNAL_ERROR);
3642 ADD_AD_CONSTANT(USER_CANCELLED);
3643 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003644 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003645#ifdef SSL_AD_UNSUPPORTED_EXTENSION
3646 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
3647#endif
3648#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
3649 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
3650#endif
3651#ifdef SSL_AD_UNRECOGNIZED_NAME
3652 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
3653#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003654#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
3655 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
3656#endif
3657#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
3658 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
3659#endif
3660#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
3661 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
3662#endif
3663
3664#undef ADD_AD_CONSTANT
3665
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003666 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02003667#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003668 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
3669 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02003670#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003671 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
3672 PY_SSL_VERSION_SSL3);
3673 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
3674 PY_SSL_VERSION_SSL23);
3675 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
3676 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003677#if HAVE_TLSv1_2
3678 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
3679 PY_SSL_VERSION_TLS1_1);
3680 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
3681 PY_SSL_VERSION_TLS1_2);
3682#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003683
Antoine Pitroub5218772010-05-21 09:56:06 +00003684 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01003685 PyModule_AddIntConstant(m, "OP_ALL",
3686 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00003687 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
3688 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
3689 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003690#if HAVE_TLSv1_2
3691 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
3692 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
3693#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01003694 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
3695 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003696 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003697#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003698 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003699#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003700#ifdef SSL_OP_NO_COMPRESSION
3701 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
3702 SSL_OP_NO_COMPRESSION);
3703#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00003704
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003705#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00003706 r = Py_True;
3707#else
3708 r = Py_False;
3709#endif
3710 Py_INCREF(r);
3711 PyModule_AddObject(m, "HAS_SNI", r);
3712
Antoine Pitroud6494802011-07-21 01:11:30 +02003713#if HAVE_OPENSSL_FINISHED
3714 r = Py_True;
3715#else
3716 r = Py_False;
3717#endif
3718 Py_INCREF(r);
3719 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
3720
Antoine Pitrou501da612011-12-21 09:27:41 +01003721#ifdef OPENSSL_NO_ECDH
3722 r = Py_False;
3723#else
3724 r = Py_True;
3725#endif
3726 Py_INCREF(r);
3727 PyModule_AddObject(m, "HAS_ECDH", r);
3728
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003729#ifdef OPENSSL_NPN_NEGOTIATED
3730 r = Py_True;
3731#else
3732 r = Py_False;
3733#endif
3734 Py_INCREF(r);
3735 PyModule_AddObject(m, "HAS_NPN", r);
3736
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003737 /* Mappings for error codes */
3738 err_codes_to_names = PyDict_New();
3739 err_names_to_codes = PyDict_New();
3740 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
3741 return NULL;
3742 errcode = error_codes;
3743 while (errcode->mnemonic != NULL) {
3744 PyObject *mnemo, *key;
3745 mnemo = PyUnicode_FromString(errcode->mnemonic);
3746 key = Py_BuildValue("ii", errcode->library, errcode->reason);
3747 if (mnemo == NULL || key == NULL)
3748 return NULL;
3749 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
3750 return NULL;
3751 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
3752 return NULL;
3753 Py_DECREF(key);
3754 Py_DECREF(mnemo);
3755 errcode++;
3756 }
3757 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
3758 return NULL;
3759 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
3760 return NULL;
3761
3762 lib_codes_to_names = PyDict_New();
3763 if (lib_codes_to_names == NULL)
3764 return NULL;
3765 libcode = library_codes;
3766 while (libcode->library != NULL) {
3767 PyObject *mnemo, *key;
3768 key = PyLong_FromLong(libcode->code);
3769 mnemo = PyUnicode_FromString(libcode->library);
3770 if (key == NULL || mnemo == NULL)
3771 return NULL;
3772 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
3773 return NULL;
3774 Py_DECREF(key);
3775 Py_DECREF(mnemo);
3776 libcode++;
3777 }
3778 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
3779 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02003780
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003781 /* OpenSSL version */
3782 /* SSLeay() gives us the version of the library linked against,
3783 which could be different from the headers version.
3784 */
3785 libver = SSLeay();
3786 r = PyLong_FromUnsignedLong(libver);
3787 if (r == NULL)
3788 return NULL;
3789 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
3790 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003791 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003792 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3793 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
3794 return NULL;
3795 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
3796 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
3797 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003798
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003799 libver = OPENSSL_VERSION_NUMBER;
3800 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
3801 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3802 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
3803 return NULL;
3804
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003805 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003806}