blob: 3a72530c37019b6c3abf4aa020e182f99daff15f [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 *
Christian Heimesbd3a7f92013-11-21 03:40:15 +0100968_get_aia_uri(X509 *certificate, int nid) {
969 PyObject *lst = NULL, *ostr = NULL;
970 int i, result;
971 AUTHORITY_INFO_ACCESS *info;
972
973 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
974 if ((info == NULL) || (sk_ACCESS_DESCRIPTION_num(info) == 0)) {
975 return Py_None;
976 }
977
978 if ((lst = PyList_New(0)) == NULL) {
979 goto fail;
980 }
981
982 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
983 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
984 ASN1_IA5STRING *uri;
985
986 if ((OBJ_obj2nid(ad->method) != nid) ||
987 (ad->location->type != GEN_URI)) {
988 continue;
989 }
990 uri = ad->location->d.uniformResourceIdentifier;
991 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
992 uri->length);
993 if (ostr == NULL) {
994 goto fail;
995 }
996 result = PyList_Append(lst, ostr);
997 Py_DECREF(ostr);
998 if (result < 0) {
999 goto fail;
1000 }
1001 }
1002 AUTHORITY_INFO_ACCESS_free(info);
1003
1004 /* convert to tuple or None */
1005 if (PyList_Size(lst) == 0) {
1006 Py_DECREF(lst);
1007 return Py_None;
1008 } else {
1009 PyObject *tup;
1010 tup = PyList_AsTuple(lst);
1011 Py_DECREF(lst);
1012 return tup;
1013 }
1014
1015 fail:
1016 AUTHORITY_INFO_ACCESS_free(info);
1017 Py_DECREF(lst);
1018 return NULL;
1019}
1020
1021static PyObject *
1022_get_crl_dp(X509 *certificate) {
1023 STACK_OF(DIST_POINT) *dps;
1024 int i, j, result;
1025 PyObject *lst;
1026
Christian Heimes949ec142013-11-21 16:26:51 +01001027#if OPENSSL_VERSION_NUMBER < 0x10001000L
1028 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points,
1029 NULL, NULL);
1030#else
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001031 /* Calls x509v3_cache_extensions and sets up crldp */
1032 X509_check_ca(certificate);
1033 dps = certificate->crldp;
Christian Heimes949ec142013-11-21 16:26:51 +01001034#endif
1035
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001036 if (dps == NULL) {
1037 return Py_None;
1038 }
1039
1040 if ((lst = PyList_New(0)) == NULL) {
1041 return NULL;
1042 }
1043
1044 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1045 DIST_POINT *dp;
1046 STACK_OF(GENERAL_NAME) *gns;
1047
1048 dp = sk_DIST_POINT_value(dps, i);
1049 gns = dp->distpoint->name.fullname;
1050
1051 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1052 GENERAL_NAME *gn;
1053 ASN1_IA5STRING *uri;
1054 PyObject *ouri;
1055
1056 gn = sk_GENERAL_NAME_value(gns, j);
1057 if (gn->type != GEN_URI) {
1058 continue;
1059 }
1060 uri = gn->d.uniformResourceIdentifier;
1061 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1062 uri->length);
1063 if (ouri == NULL) {
1064 Py_DECREF(lst);
1065 return NULL;
1066 }
1067 result = PyList_Append(lst, ouri);
1068 Py_DECREF(ouri);
1069 if (result < 0) {
1070 Py_DECREF(lst);
1071 return NULL;
1072 }
1073 }
1074 }
1075 /* convert to tuple or None */
1076 if (PyList_Size(lst) == 0) {
1077 Py_DECREF(lst);
1078 return Py_None;
1079 } else {
1080 PyObject *tup;
1081 tup = PyList_AsTuple(lst);
1082 Py_DECREF(lst);
1083 return tup;
1084 }
1085}
1086
1087static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001088_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001089
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001090 PyObject *retval = NULL;
1091 BIO *biobuf = NULL;
1092 PyObject *peer;
1093 PyObject *peer_alt_names = NULL;
1094 PyObject *issuer;
1095 PyObject *version;
1096 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001097 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001098 ASN1_INTEGER *serialNumber;
1099 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001100 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 ASN1_TIME *notBefore, *notAfter;
1102 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001103
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001104 retval = PyDict_New();
1105 if (retval == NULL)
1106 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001107
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001108 peer = _create_tuple_for_X509_NAME(
1109 X509_get_subject_name(certificate));
1110 if (peer == NULL)
1111 goto fail0;
1112 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1113 Py_DECREF(peer);
1114 goto fail0;
1115 }
1116 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001117
Antoine Pitroufb046912010-11-09 20:21:19 +00001118 issuer = _create_tuple_for_X509_NAME(
1119 X509_get_issuer_name(certificate));
1120 if (issuer == NULL)
1121 goto fail0;
1122 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001123 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001124 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001125 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001126 Py_DECREF(issuer);
1127
1128 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001129 if (version == NULL)
1130 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001131 if (PyDict_SetItemString(retval, "version", version) < 0) {
1132 Py_DECREF(version);
1133 goto fail0;
1134 }
1135 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 /* get a memory buffer */
1138 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001139
Antoine Pitroufb046912010-11-09 20:21:19 +00001140 (void) BIO_reset(biobuf);
1141 serialNumber = X509_get_serialNumber(certificate);
1142 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1143 i2a_ASN1_INTEGER(biobuf, serialNumber);
1144 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1145 if (len < 0) {
1146 _setSSLError(NULL, 0, __FILE__, __LINE__);
1147 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001149 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1150 if (sn_obj == NULL)
1151 goto fail1;
1152 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1153 Py_DECREF(sn_obj);
1154 goto fail1;
1155 }
1156 Py_DECREF(sn_obj);
1157
1158 (void) BIO_reset(biobuf);
1159 notBefore = X509_get_notBefore(certificate);
1160 ASN1_TIME_print(biobuf, notBefore);
1161 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1162 if (len < 0) {
1163 _setSSLError(NULL, 0, __FILE__, __LINE__);
1164 goto fail1;
1165 }
1166 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1167 if (pnotBefore == NULL)
1168 goto fail1;
1169 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1170 Py_DECREF(pnotBefore);
1171 goto fail1;
1172 }
1173 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001174
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001175 (void) BIO_reset(biobuf);
1176 notAfter = X509_get_notAfter(certificate);
1177 ASN1_TIME_print(biobuf, notAfter);
1178 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1179 if (len < 0) {
1180 _setSSLError(NULL, 0, __FILE__, __LINE__);
1181 goto fail1;
1182 }
1183 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1184 if (pnotAfter == NULL)
1185 goto fail1;
1186 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1187 Py_DECREF(pnotAfter);
1188 goto fail1;
1189 }
1190 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001191
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001192 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001193
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001194 peer_alt_names = _get_peer_alt_names(certificate);
1195 if (peer_alt_names == NULL)
1196 goto fail1;
1197 else if (peer_alt_names != Py_None) {
1198 if (PyDict_SetItemString(retval, "subjectAltName",
1199 peer_alt_names) < 0) {
1200 Py_DECREF(peer_alt_names);
1201 goto fail1;
1202 }
1203 Py_DECREF(peer_alt_names);
1204 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001205
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001206 /* Authority Information Access: OCSP URIs */
1207 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1208 if (obj == NULL) {
1209 goto fail1;
1210 } else if (obj != Py_None) {
1211 result = PyDict_SetItemString(retval, "OCSP", obj);
1212 Py_DECREF(obj);
1213 if (result < 0) {
1214 goto fail1;
1215 }
1216 }
1217
1218 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1219 if (obj == NULL) {
1220 goto fail1;
1221 } else if (obj != Py_None) {
1222 result = PyDict_SetItemString(retval, "caIssuers", obj);
1223 Py_DECREF(obj);
1224 if (result < 0) {
1225 goto fail1;
1226 }
1227 }
1228
1229 /* CDP (CRL distribution points) */
1230 obj = _get_crl_dp(certificate);
1231 if (obj == NULL) {
1232 goto fail1;
1233 } else if (obj != Py_None) {
1234 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1235 Py_DECREF(obj);
1236 if (result < 0) {
1237 goto fail1;
1238 }
1239 }
1240
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241 BIO_free(biobuf);
1242 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001243
1244 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001245 if (biobuf != NULL)
1246 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001247 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001248 Py_XDECREF(retval);
1249 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001250}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001251
Christian Heimes9a5395a2013-06-17 15:44:12 +02001252static PyObject *
1253_certificate_to_der(X509 *certificate)
1254{
1255 unsigned char *bytes_buf = NULL;
1256 int len;
1257 PyObject *retval;
1258
1259 bytes_buf = NULL;
1260 len = i2d_X509(certificate, &bytes_buf);
1261 if (len < 0) {
1262 _setSSLError(NULL, 0, __FILE__, __LINE__);
1263 return NULL;
1264 }
1265 /* this is actually an immutable bytes sequence */
1266 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1267 OPENSSL_free(bytes_buf);
1268 return retval;
1269}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001270
1271static PyObject *
1272PySSL_test_decode_certificate (PyObject *mod, PyObject *args) {
1273
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001274 PyObject *retval = NULL;
Victor Stinner3800e1e2010-05-16 21:23:48 +00001275 PyObject *filename;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 X509 *x=NULL;
1277 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001278
Antoine Pitroufb046912010-11-09 20:21:19 +00001279 if (!PyArg_ParseTuple(args, "O&:test_decode_certificate",
1280 PyUnicode_FSConverter, &filename))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001282
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001283 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1284 PyErr_SetString(PySSLErrorObject,
1285 "Can't malloc memory to read file");
1286 goto fail0;
1287 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001288
Victor Stinner3800e1e2010-05-16 21:23:48 +00001289 if (BIO_read_filename(cert, PyBytes_AsString(filename)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 PyErr_SetString(PySSLErrorObject,
1291 "Can't open file");
1292 goto fail0;
1293 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001294
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1296 if (x == NULL) {
1297 PyErr_SetString(PySSLErrorObject,
1298 "Error decoding PEM-encoded file");
1299 goto fail0;
1300 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001301
Antoine Pitroufb046912010-11-09 20:21:19 +00001302 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001303 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001304
1305 fail0:
Victor Stinner3800e1e2010-05-16 21:23:48 +00001306 Py_DECREF(filename);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001307 if (cert != NULL) BIO_free(cert);
1308 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001309}
1310
1311
1312static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00001313PySSL_peercert(PySSLSocket *self, PyObject *args)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001314{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001315 int verification;
Antoine Pitrou721738f2012-08-15 23:20:39 +02001316 int binary_mode = 0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001317
Antoine Pitrou721738f2012-08-15 23:20:39 +02001318 if (!PyArg_ParseTuple(args, "|p:peer_certificate", &binary_mode))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001319 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001320
Antoine Pitrou20b85552013-09-29 19:50:53 +02001321 if (!self->handshake_done) {
1322 PyErr_SetString(PyExc_ValueError,
1323 "handshake not done yet");
1324 return NULL;
1325 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001326 if (!self->peer_cert)
1327 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001328
Antoine Pitrou721738f2012-08-15 23:20:39 +02001329 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 /* return cert in DER-encoded format */
Christian Heimes9a5395a2013-06-17 15:44:12 +02001331 return _certificate_to_der(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001332 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001333 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 if ((verification & SSL_VERIFY_PEER) == 0)
1335 return PyDict_New();
1336 else
Antoine Pitroufb046912010-11-09 20:21:19 +00001337 return _decode_certificate(self->peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001339}
1340
1341PyDoc_STRVAR(PySSL_peercert_doc,
1342"peer_certificate([der=False]) -> certificate\n\
1343\n\
1344Returns the certificate for the peer. If no certificate was provided,\n\
1345returns None. If a certificate was provided, but not validated, returns\n\
1346an empty dictionary. Otherwise returns a dict containing information\n\
1347about the peer certificate.\n\
1348\n\
1349If the optional argument is True, returns a DER-encoded copy of the\n\
1350peer certificate, or None if no certificate was provided. This will\n\
1351return the certificate even if it wasn't validated.");
1352
Antoine Pitrou152efa22010-05-16 18:19:27 +00001353static PyObject *PySSL_cipher (PySSLSocket *self) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001354
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001355 PyObject *retval, *v;
Benjamin Petersoneb1410f2010-10-13 22:06:39 +00001356 const SSL_CIPHER *current;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001357 char *cipher_name;
1358 char *cipher_protocol;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001359
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001360 if (self->ssl == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001361 Py_RETURN_NONE;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001362 current = SSL_get_current_cipher(self->ssl);
1363 if (current == NULL)
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001364 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001365
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 retval = PyTuple_New(3);
1367 if (retval == NULL)
1368 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001369
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 cipher_name = (char *) SSL_CIPHER_get_name(current);
1371 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001372 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001373 PyTuple_SET_ITEM(retval, 0, Py_None);
1374 } else {
1375 v = PyUnicode_FromString(cipher_name);
1376 if (v == NULL)
1377 goto fail0;
1378 PyTuple_SET_ITEM(retval, 0, v);
1379 }
1380 cipher_protocol = SSL_CIPHER_get_version(current);
1381 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001382 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001383 PyTuple_SET_ITEM(retval, 1, Py_None);
1384 } else {
1385 v = PyUnicode_FromString(cipher_protocol);
1386 if (v == NULL)
1387 goto fail0;
1388 PyTuple_SET_ITEM(retval, 1, v);
1389 }
1390 v = PyLong_FromLong(SSL_CIPHER_get_bits(current, NULL));
1391 if (v == NULL)
1392 goto fail0;
1393 PyTuple_SET_ITEM(retval, 2, v);
1394 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001395
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001396 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 Py_DECREF(retval);
1398 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001399}
1400
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001401#ifdef OPENSSL_NPN_NEGOTIATED
1402static PyObject *PySSL_selected_npn_protocol(PySSLSocket *self) {
1403 const unsigned char *out;
1404 unsigned int outlen;
1405
Victor Stinner4569cd52013-06-23 14:58:43 +02001406 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001407 &out, &outlen);
1408
1409 if (out == NULL)
1410 Py_RETURN_NONE;
1411 return PyUnicode_FromStringAndSize((char *) out, outlen);
1412}
1413#endif
1414
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001415static PyObject *PySSL_compression(PySSLSocket *self) {
1416#ifdef OPENSSL_NO_COMP
1417 Py_RETURN_NONE;
1418#else
1419 const COMP_METHOD *comp_method;
1420 const char *short_name;
1421
1422 if (self->ssl == NULL)
1423 Py_RETURN_NONE;
1424 comp_method = SSL_get_current_compression(self->ssl);
1425 if (comp_method == NULL || comp_method->type == NID_undef)
1426 Py_RETURN_NONE;
1427 short_name = OBJ_nid2sn(comp_method->type);
1428 if (short_name == NULL)
1429 Py_RETURN_NONE;
1430 return PyUnicode_DecodeFSDefault(short_name);
1431#endif
1432}
1433
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001434static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1435 Py_INCREF(self->ctx);
1436 return self->ctx;
1437}
1438
1439static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1440 void *closure) {
1441
1442 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001443#if !HAVE_SNI
1444 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1445 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001446 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001447#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001448 Py_INCREF(value);
1449 Py_DECREF(self->ctx);
1450 self->ctx = (PySSLContext *) value;
1451 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001452#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001453 } else {
1454 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1455 return -1;
1456 }
1457
1458 return 0;
1459}
1460
1461PyDoc_STRVAR(PySSL_set_context_doc,
1462"_setter_context(ctx)\n\
1463\
1464This changes the context associated with the SSLSocket. This is typically\n\
1465used from within a callback function set by the set_servername_callback\n\
1466on the SSLContext to change the certificate information associated with the\n\
1467SSLSocket before the cryptographic exchange handshake messages\n");
1468
1469
1470
Antoine Pitrou152efa22010-05-16 18:19:27 +00001471static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001472{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001473 if (self->peer_cert) /* Possible not to have one? */
1474 X509_free (self->peer_cert);
1475 if (self->ssl)
1476 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001477 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001478 Py_XDECREF(self->ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001479 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001480}
1481
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001482/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001483 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001484 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001485 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001486
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001487static int
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001488check_socket_and_wait_for_timeout(PySocketSockObject *s, int writing)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001489{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001490 fd_set fds;
1491 struct timeval tv;
1492 int rc;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001493
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001494 /* Nothing to do unless we're in timeout mode (not non-blocking) */
1495 if (s->sock_timeout < 0.0)
1496 return SOCKET_IS_BLOCKING;
1497 else if (s->sock_timeout == 0.0)
1498 return SOCKET_IS_NONBLOCKING;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001499
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001500 /* Guard against closed socket */
1501 if (s->sock_fd < 0)
1502 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001503
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001504 /* Prefer poll, if available, since you can poll() any fd
1505 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001506#ifdef HAVE_POLL
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001507 {
1508 struct pollfd pollfd;
1509 int timeout;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001510
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001511 pollfd.fd = s->sock_fd;
1512 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001513
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001514 /* s->sock_timeout is in seconds, timeout in ms */
1515 timeout = (int)(s->sock_timeout * 1000 + 0.5);
1516 PySSL_BEGIN_ALLOW_THREADS
1517 rc = poll(&pollfd, 1, timeout);
1518 PySSL_END_ALLOW_THREADS
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001519
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001520 goto normal_return;
1521 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001522#endif
1523
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001525 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001526 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001527
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 /* Construct the arguments to select */
1529 tv.tv_sec = (int)s->sock_timeout;
1530 tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
1531 FD_ZERO(&fds);
1532 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001533
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001534 /* See if the socket is ready */
1535 PySSL_BEGIN_ALLOW_THREADS
1536 if (writing)
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001537 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1538 NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001539 else
Christian Heimesb08ff7d2013-11-18 10:04:07 +01001540 rc = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
1541 &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001542 PySSL_END_ALLOW_THREADS
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001543
Bill Janssen6e027db2007-11-15 22:23:56 +00001544#ifdef HAVE_POLL
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001545normal_return:
Bill Janssen6e027db2007-11-15 22:23:56 +00001546#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001547 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1548 (when we are able to write or when there's something to read) */
1549 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001550}
1551
Antoine Pitrou152efa22010-05-16 18:19:27 +00001552static PyObject *PySSL_SSLwrite(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001553{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001554 Py_buffer buf;
1555 int len;
1556 int sockstate;
1557 int err;
1558 int nonblocking;
1559 PySocketSockObject *sock
1560 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001561
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001562 if (((PyObject*)sock) == Py_None) {
1563 _setSSLError("Underlying socket connection gone",
1564 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1565 return NULL;
1566 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001567 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001569 if (!PyArg_ParseTuple(args, "y*:write", &buf)) {
1570 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001571 return NULL;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001572 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001573
Victor Stinner6efa9652013-06-25 00:42:31 +02001574 if (buf.len > INT_MAX) {
1575 PyErr_Format(PyExc_OverflowError,
1576 "string longer than %d bytes", INT_MAX);
1577 goto error;
1578 }
1579
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001580 /* just in case the blocking state of the socket has been changed */
1581 nonblocking = (sock->sock_timeout >= 0.0);
1582 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1583 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1584
1585 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1586 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001587 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001588 "The write operation timed out");
1589 goto error;
1590 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1591 PyErr_SetString(PySSLErrorObject,
1592 "Underlying socket has been closed.");
1593 goto error;
1594 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1595 PyErr_SetString(PySSLErrorObject,
1596 "Underlying socket too large for select().");
1597 goto error;
1598 }
1599 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001600 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner6efa9652013-06-25 00:42:31 +02001601 len = SSL_write(self->ssl, buf.buf, (int)buf.len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001602 err = SSL_get_error(self->ssl, len);
1603 PySSL_END_ALLOW_THREADS
1604 if (PyErr_CheckSignals()) {
1605 goto error;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001606 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001607 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001608 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001609 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001610 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001611 } else {
1612 sockstate = SOCKET_OPERATION_OK;
1613 }
1614 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001615 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001616 "The write operation timed out");
1617 goto error;
1618 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1619 PyErr_SetString(PySSLErrorObject,
1620 "Underlying socket has been closed.");
1621 goto error;
1622 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1623 break;
1624 }
1625 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001626
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001627 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001628 PyBuffer_Release(&buf);
1629 if (len > 0)
1630 return PyLong_FromLong(len);
1631 else
1632 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00001633
1634error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001635 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001636 PyBuffer_Release(&buf);
1637 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001638}
1639
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001640PyDoc_STRVAR(PySSL_SSLwrite_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001641"write(s) -> len\n\
1642\n\
1643Writes the string s into the SSL object. Returns the number\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001644of bytes written.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001645
Antoine Pitrou152efa22010-05-16 18:19:27 +00001646static PyObject *PySSL_SSLpending(PySSLSocket *self)
Bill Janssen6e027db2007-11-15 22:23:56 +00001647{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001648 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00001649
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001650 PySSL_BEGIN_ALLOW_THREADS
1651 count = SSL_pending(self->ssl);
1652 PySSL_END_ALLOW_THREADS
1653 if (count < 0)
1654 return PySSL_SetError(self, count, __FILE__, __LINE__);
1655 else
1656 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00001657}
1658
1659PyDoc_STRVAR(PySSL_SSLpending_doc,
1660"pending() -> count\n\
1661\n\
1662Returns the number of already decrypted bytes available for read,\n\
1663pending on the connection.\n");
1664
Antoine Pitrou152efa22010-05-16 18:19:27 +00001665static PyObject *PySSL_SSLread(PySSLSocket *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001666{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001667 PyObject *dest = NULL;
1668 Py_buffer buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001669 char *mem;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001670 int len, count;
1671 int buf_passed = 0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001672 int sockstate;
1673 int err;
1674 int nonblocking;
1675 PySocketSockObject *sock
1676 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen54cc54c2007-12-14 22:08:56 +00001677
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001678 if (((PyObject*)sock) == Py_None) {
1679 _setSSLError("Underlying socket connection gone",
1680 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1681 return NULL;
1682 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001683 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001684
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001685 buf.obj = NULL;
1686 buf.buf = NULL;
1687 if (!PyArg_ParseTuple(args, "i|w*:read", &len, &buf))
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001688 goto error;
1689
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001690 if ((buf.buf == NULL) && (buf.obj == NULL)) {
1691 dest = PyBytes_FromStringAndSize(NULL, len);
1692 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001693 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001694 mem = PyBytes_AS_STRING(dest);
1695 }
1696 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001697 buf_passed = 1;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001698 mem = buf.buf;
1699 if (len <= 0 || len > buf.len) {
1700 len = (int) buf.len;
1701 if (buf.len != len) {
1702 PyErr_SetString(PyExc_OverflowError,
1703 "maximum length can't fit in a C 'int'");
1704 goto error;
1705 }
1706 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001707 }
1708
1709 /* just in case the blocking state of the socket has been changed */
1710 nonblocking = (sock->sock_timeout >= 0.0);
1711 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1712 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1713
1714 /* first check if there are bytes ready to be read */
1715 PySSL_BEGIN_ALLOW_THREADS
1716 count = SSL_pending(self->ssl);
1717 PySSL_END_ALLOW_THREADS
1718
1719 if (!count) {
1720 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1721 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001722 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001723 "The read operation timed out");
1724 goto error;
1725 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1726 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001727 "Underlying socket too large for select().");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001728 goto error;
1729 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1730 count = 0;
1731 goto done;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001732 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001733 }
1734 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001735 PySSL_BEGIN_ALLOW_THREADS
1736 count = SSL_read(self->ssl, mem, len);
1737 err = SSL_get_error(self->ssl, count);
1738 PySSL_END_ALLOW_THREADS
1739 if (PyErr_CheckSignals())
1740 goto error;
1741 if (err == SSL_ERROR_WANT_READ) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001742 sockstate = check_socket_and_wait_for_timeout(sock, 0);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001743 } else if (err == SSL_ERROR_WANT_WRITE) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00001744 sockstate = check_socket_and_wait_for_timeout(sock, 1);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001745 } else if ((err == SSL_ERROR_ZERO_RETURN) &&
1746 (SSL_get_shutdown(self->ssl) ==
1747 SSL_RECEIVED_SHUTDOWN))
1748 {
1749 count = 0;
1750 goto done;
1751 } else {
1752 sockstate = SOCKET_OPERATION_OK;
1753 }
1754 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001755 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001756 "The read operation timed out");
1757 goto error;
1758 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1759 break;
1760 }
1761 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
1762 if (count <= 0) {
1763 PySSL_SetError(self, count, __FILE__, __LINE__);
1764 goto error;
1765 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001766
1767done:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001768 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001769 if (!buf_passed) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001770 _PyBytes_Resize(&dest, count);
1771 return dest;
1772 }
1773 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001774 PyBuffer_Release(&buf);
1775 return PyLong_FromLong(count);
1776 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001777
1778error:
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001779 Py_DECREF(sock);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001780 if (!buf_passed)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001781 Py_XDECREF(dest);
Antoine Pitrou24e561a2010-09-03 18:38:17 +00001782 else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001783 PyBuffer_Release(&buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001784 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001785}
1786
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001787PyDoc_STRVAR(PySSL_SSLread_doc,
Bill Janssen6e027db2007-11-15 22:23:56 +00001788"read([len]) -> string\n\
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001789\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001790Read up to len bytes from the SSL socket.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001791
Antoine Pitrou152efa22010-05-16 18:19:27 +00001792static PyObject *PySSL_SSLshutdown(PySSLSocket *self)
Bill Janssen40a0f662008-08-12 16:56:25 +00001793{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001794 int err, ssl_err, sockstate, nonblocking;
1795 int zeros = 0;
1796 PySocketSockObject *sock
1797 = (PySocketSockObject *) PyWeakref_GetObject(self->Socket);
Bill Janssen40a0f662008-08-12 16:56:25 +00001798
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001799 /* Guard against closed socket */
1800 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd < 0)) {
1801 _setSSLError("Underlying socket connection gone",
1802 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1803 return NULL;
1804 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001805 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001806
1807 /* Just in case the blocking state of the socket has been changed */
1808 nonblocking = (sock->sock_timeout >= 0.0);
1809 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1810 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1811
1812 while (1) {
1813 PySSL_BEGIN_ALLOW_THREADS
1814 /* Disable read-ahead so that unwrap can work correctly.
1815 * Otherwise OpenSSL might read in too much data,
1816 * eating clear text data that happens to be
1817 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03001818 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001819 * function is used and the shutdown_seen_zero != 0
1820 * condition is met.
1821 */
1822 if (self->shutdown_seen_zero)
1823 SSL_set_read_ahead(self->ssl, 0);
1824 err = SSL_shutdown(self->ssl);
1825 PySSL_END_ALLOW_THREADS
1826 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
1827 if (err > 0)
1828 break;
1829 if (err == 0) {
1830 /* Don't loop endlessly; instead preserve legacy
1831 behaviour of trying SSL_shutdown() only twice.
1832 This looks necessary for OpenSSL < 0.9.8m */
1833 if (++zeros > 1)
1834 break;
1835 /* Shutdown was sent, now try receiving */
1836 self->shutdown_seen_zero = 1;
1837 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00001838 }
1839
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001840 /* Possibly retry shutdown until timeout or failure */
1841 ssl_err = SSL_get_error(self->ssl, err);
1842 if (ssl_err == SSL_ERROR_WANT_READ)
1843 sockstate = check_socket_and_wait_for_timeout(sock, 0);
1844 else if (ssl_err == SSL_ERROR_WANT_WRITE)
1845 sockstate = check_socket_and_wait_for_timeout(sock, 1);
1846 else
1847 break;
1848 if (sockstate == SOCKET_HAS_TIMED_OUT) {
1849 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001850 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001851 "The read operation timed out");
1852 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001853 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001854 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001855 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 }
1857 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1858 PyErr_SetString(PySSLErrorObject,
1859 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001860 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001861 }
1862 else if (sockstate != SOCKET_OPERATION_OK)
1863 /* Retain the SSL error code */
1864 break;
1865 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00001866
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001867 if (err < 0) {
1868 Py_DECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001869 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001870 }
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001871 else
1872 /* It's already INCREF'ed */
1873 return (PyObject *) sock;
1874
1875error:
1876 Py_DECREF(sock);
1877 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00001878}
1879
1880PyDoc_STRVAR(PySSL_SSLshutdown_doc,
1881"shutdown(s) -> socket\n\
1882\n\
1883Does the SSL shutdown handshake with the remote end, and returns\n\
1884the underlying socket object.");
1885
Antoine Pitroud6494802011-07-21 01:11:30 +02001886#if HAVE_OPENSSL_FINISHED
1887static PyObject *
1888PySSL_tls_unique_cb(PySSLSocket *self)
1889{
1890 PyObject *retval = NULL;
1891 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02001892 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02001893
1894 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
1895 /* if session is resumed XOR we are the client */
1896 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1897 }
1898 else {
1899 /* if a new session XOR we are the server */
1900 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
1901 }
1902
1903 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02001904 if (len == 0)
1905 Py_RETURN_NONE;
1906
1907 retval = PyBytes_FromStringAndSize(buf, len);
1908
1909 return retval;
1910}
1911
1912PyDoc_STRVAR(PySSL_tls_unique_cb_doc,
1913"tls_unique_cb() -> bytes\n\
1914\n\
1915Returns the 'tls-unique' channel binding data, as defined by RFC 5929.\n\
1916\n\
1917If the TLS handshake is not yet complete, None is returned");
1918
1919#endif /* HAVE_OPENSSL_FINISHED */
Bill Janssen40a0f662008-08-12 16:56:25 +00001920
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001921static PyGetSetDef ssl_getsetlist[] = {
1922 {"context", (getter) PySSL_get_context,
1923 (setter) PySSL_set_context, PySSL_set_context_doc},
1924 {NULL}, /* sentinel */
1925};
1926
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001927static PyMethodDef PySSLMethods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001928 {"do_handshake", (PyCFunction)PySSL_SSLdo_handshake, METH_NOARGS},
1929 {"write", (PyCFunction)PySSL_SSLwrite, METH_VARARGS,
1930 PySSL_SSLwrite_doc},
1931 {"read", (PyCFunction)PySSL_SSLread, METH_VARARGS,
1932 PySSL_SSLread_doc},
1933 {"pending", (PyCFunction)PySSL_SSLpending, METH_NOARGS,
1934 PySSL_SSLpending_doc},
1935 {"peer_certificate", (PyCFunction)PySSL_peercert, METH_VARARGS,
1936 PySSL_peercert_doc},
1937 {"cipher", (PyCFunction)PySSL_cipher, METH_NOARGS},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001938#ifdef OPENSSL_NPN_NEGOTIATED
1939 {"selected_npn_protocol", (PyCFunction)PySSL_selected_npn_protocol, METH_NOARGS},
1940#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001941 {"compression", (PyCFunction)PySSL_compression, METH_NOARGS},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001942 {"shutdown", (PyCFunction)PySSL_SSLshutdown, METH_NOARGS,
1943 PySSL_SSLshutdown_doc},
Antoine Pitroud6494802011-07-21 01:11:30 +02001944#if HAVE_OPENSSL_FINISHED
1945 {"tls_unique_cb", (PyCFunction)PySSL_tls_unique_cb, METH_NOARGS,
1946 PySSL_tls_unique_cb_doc},
1947#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001948 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001949};
1950
Antoine Pitrou152efa22010-05-16 18:19:27 +00001951static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001952 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00001953 "_ssl._SSLSocket", /*tp_name*/
1954 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001955 0, /*tp_itemsize*/
1956 /* methods */
1957 (destructor)PySSL_dealloc, /*tp_dealloc*/
1958 0, /*tp_print*/
1959 0, /*tp_getattr*/
1960 0, /*tp_setattr*/
1961 0, /*tp_reserved*/
1962 0, /*tp_repr*/
1963 0, /*tp_as_number*/
1964 0, /*tp_as_sequence*/
1965 0, /*tp_as_mapping*/
1966 0, /*tp_hash*/
1967 0, /*tp_call*/
1968 0, /*tp_str*/
1969 0, /*tp_getattro*/
1970 0, /*tp_setattro*/
1971 0, /*tp_as_buffer*/
1972 Py_TPFLAGS_DEFAULT, /*tp_flags*/
1973 0, /*tp_doc*/
1974 0, /*tp_traverse*/
1975 0, /*tp_clear*/
1976 0, /*tp_richcompare*/
1977 0, /*tp_weaklistoffset*/
1978 0, /*tp_iter*/
1979 0, /*tp_iternext*/
1980 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001981 0, /*tp_members*/
1982 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001983};
1984
Antoine Pitrou152efa22010-05-16 18:19:27 +00001985
1986/*
1987 * _SSLContext objects
1988 */
1989
1990static PyObject *
1991context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1992{
1993 char *kwlist[] = {"protocol", NULL};
1994 PySSLContext *self;
1995 int proto_version = PY_SSL_VERSION_SSL23;
1996 SSL_CTX *ctx = NULL;
1997
1998 if (!PyArg_ParseTupleAndKeywords(
1999 args, kwds, "i:_SSLContext", kwlist,
2000 &proto_version))
2001 return NULL;
2002
2003 PySSL_BEGIN_ALLOW_THREADS
2004 if (proto_version == PY_SSL_VERSION_TLS1)
2005 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002006#if HAVE_TLSv1_2
2007 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2008 ctx = SSL_CTX_new(TLSv1_1_method());
2009 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2010 ctx = SSL_CTX_new(TLSv1_2_method());
2011#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002012 else if (proto_version == PY_SSL_VERSION_SSL3)
2013 ctx = SSL_CTX_new(SSLv3_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002014#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002015 else if (proto_version == PY_SSL_VERSION_SSL2)
2016 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002017#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002018 else if (proto_version == PY_SSL_VERSION_SSL23)
2019 ctx = SSL_CTX_new(SSLv23_method());
2020 else
2021 proto_version = -1;
2022 PySSL_END_ALLOW_THREADS
2023
2024 if (proto_version == -1) {
2025 PyErr_SetString(PyExc_ValueError,
2026 "invalid protocol version");
2027 return NULL;
2028 }
2029 if (ctx == NULL) {
2030 PyErr_SetString(PySSLErrorObject,
2031 "failed to allocate SSL context");
2032 return NULL;
2033 }
2034
2035 assert(type != NULL && type->tp_alloc != NULL);
2036 self = (PySSLContext *) type->tp_alloc(type, 0);
2037 if (self == NULL) {
2038 SSL_CTX_free(ctx);
2039 return NULL;
2040 }
2041 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002042#ifdef OPENSSL_NPN_NEGOTIATED
2043 self->npn_protocols = NULL;
2044#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002045#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002046 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002047#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002048 /* Defaults */
2049 SSL_CTX_set_verify(self->ctx, SSL_VERIFY_NONE, NULL);
Antoine Pitrou3f366312012-01-27 09:50:45 +01002050 SSL_CTX_set_options(self->ctx,
2051 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002052
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002053#define SID_CTX "Python"
2054 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2055 sizeof(SID_CTX));
2056#undef SID_CTX
2057
Antoine Pitrou152efa22010-05-16 18:19:27 +00002058 return (PyObject *)self;
2059}
2060
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002061static int
2062context_traverse(PySSLContext *self, visitproc visit, void *arg)
2063{
2064#ifndef OPENSSL_NO_TLSEXT
2065 Py_VISIT(self->set_hostname);
2066#endif
2067 return 0;
2068}
2069
2070static int
2071context_clear(PySSLContext *self)
2072{
2073#ifndef OPENSSL_NO_TLSEXT
2074 Py_CLEAR(self->set_hostname);
2075#endif
2076 return 0;
2077}
2078
Antoine Pitrou152efa22010-05-16 18:19:27 +00002079static void
2080context_dealloc(PySSLContext *self)
2081{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002082 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002083 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002084#ifdef OPENSSL_NPN_NEGOTIATED
2085 PyMem_Free(self->npn_protocols);
2086#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002087 Py_TYPE(self)->tp_free(self);
2088}
2089
2090static PyObject *
2091set_ciphers(PySSLContext *self, PyObject *args)
2092{
2093 int ret;
2094 const char *cipherlist;
2095
2096 if (!PyArg_ParseTuple(args, "s:set_ciphers", &cipherlist))
2097 return NULL;
2098 ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
2099 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002100 /* Clearing the error queue is necessary on some OpenSSL versions,
2101 otherwise the error will be reported again when another SSL call
2102 is done. */
2103 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002104 PyErr_SetString(PySSLErrorObject,
2105 "No cipher can be selected.");
2106 return NULL;
2107 }
2108 Py_RETURN_NONE;
2109}
2110
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002111#ifdef OPENSSL_NPN_NEGOTIATED
2112/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2113static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002114_advertiseNPN_cb(SSL *s,
2115 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002116 void *args)
2117{
2118 PySSLContext *ssl_ctx = (PySSLContext *) args;
2119
2120 if (ssl_ctx->npn_protocols == NULL) {
2121 *data = (unsigned char *) "";
2122 *len = 0;
2123 } else {
2124 *data = (unsigned char *) ssl_ctx->npn_protocols;
2125 *len = ssl_ctx->npn_protocols_len;
2126 }
2127
2128 return SSL_TLSEXT_ERR_OK;
2129}
2130/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2131static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002132_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002133 unsigned char **out, unsigned char *outlen,
2134 const unsigned char *server, unsigned int server_len,
2135 void *args)
2136{
2137 PySSLContext *ssl_ctx = (PySSLContext *) args;
2138
2139 unsigned char *client = (unsigned char *) ssl_ctx->npn_protocols;
2140 int client_len;
2141
2142 if (client == NULL) {
2143 client = (unsigned char *) "";
2144 client_len = 0;
2145 } else {
2146 client_len = ssl_ctx->npn_protocols_len;
2147 }
2148
2149 SSL_select_next_proto(out, outlen,
2150 server, server_len,
2151 client, client_len);
2152
2153 return SSL_TLSEXT_ERR_OK;
2154}
2155#endif
2156
2157static PyObject *
2158_set_npn_protocols(PySSLContext *self, PyObject *args)
2159{
2160#ifdef OPENSSL_NPN_NEGOTIATED
2161 Py_buffer protos;
2162
2163 if (!PyArg_ParseTuple(args, "y*:set_npn_protocols", &protos))
2164 return NULL;
2165
Christian Heimes5cb31c92012-09-20 12:42:54 +02002166 if (self->npn_protocols != NULL) {
2167 PyMem_Free(self->npn_protocols);
2168 }
2169
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002170 self->npn_protocols = PyMem_Malloc(protos.len);
2171 if (self->npn_protocols == NULL) {
2172 PyBuffer_Release(&protos);
2173 return PyErr_NoMemory();
2174 }
2175 memcpy(self->npn_protocols, protos.buf, protos.len);
2176 self->npn_protocols_len = (int) protos.len;
2177
2178 /* set both server and client callbacks, because the context can
2179 * be used to create both types of sockets */
2180 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2181 _advertiseNPN_cb,
2182 self);
2183 SSL_CTX_set_next_proto_select_cb(self->ctx,
2184 _selectNPN_cb,
2185 self);
2186
2187 PyBuffer_Release(&protos);
2188 Py_RETURN_NONE;
2189#else
2190 PyErr_SetString(PyExc_NotImplementedError,
2191 "The NPN extension requires OpenSSL 1.0.1 or later.");
2192 return NULL;
2193#endif
2194}
2195
Antoine Pitrou152efa22010-05-16 18:19:27 +00002196static PyObject *
2197get_verify_mode(PySSLContext *self, void *c)
2198{
2199 switch (SSL_CTX_get_verify_mode(self->ctx)) {
2200 case SSL_VERIFY_NONE:
2201 return PyLong_FromLong(PY_SSL_CERT_NONE);
2202 case SSL_VERIFY_PEER:
2203 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
2204 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
2205 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
2206 }
2207 PyErr_SetString(PySSLErrorObject,
2208 "invalid return value from SSL_CTX_get_verify_mode");
2209 return NULL;
2210}
2211
2212static int
2213set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
2214{
2215 int n, mode;
2216 if (!PyArg_Parse(arg, "i", &n))
2217 return -1;
2218 if (n == PY_SSL_CERT_NONE)
2219 mode = SSL_VERIFY_NONE;
2220 else if (n == PY_SSL_CERT_OPTIONAL)
2221 mode = SSL_VERIFY_PEER;
2222 else if (n == PY_SSL_CERT_REQUIRED)
2223 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2224 else {
2225 PyErr_SetString(PyExc_ValueError,
2226 "invalid value for verify_mode");
2227 return -1;
2228 }
2229 SSL_CTX_set_verify(self->ctx, mode, NULL);
2230 return 0;
2231}
2232
2233static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00002234get_options(PySSLContext *self, void *c)
2235{
2236 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
2237}
2238
2239static int
2240set_options(PySSLContext *self, PyObject *arg, void *c)
2241{
2242 long new_opts, opts, set, clear;
2243 if (!PyArg_Parse(arg, "l", &new_opts))
2244 return -1;
2245 opts = SSL_CTX_get_options(self->ctx);
2246 clear = opts & ~new_opts;
2247 set = ~opts & new_opts;
2248 if (clear) {
2249#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
2250 SSL_CTX_clear_options(self->ctx, clear);
2251#else
2252 PyErr_SetString(PyExc_ValueError,
2253 "can't clear options before OpenSSL 0.9.8m");
2254 return -1;
2255#endif
2256 }
2257 if (set)
2258 SSL_CTX_set_options(self->ctx, set);
2259 return 0;
2260}
2261
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002262typedef struct {
2263 PyThreadState *thread_state;
2264 PyObject *callable;
2265 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02002266 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002267 int error;
2268} _PySSLPasswordInfo;
2269
2270static int
2271_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
2272 const char *bad_type_error)
2273{
2274 /* Set the password and size fields of a _PySSLPasswordInfo struct
2275 from a unicode, bytes, or byte array object.
2276 The password field will be dynamically allocated and must be freed
2277 by the caller */
2278 PyObject *password_bytes = NULL;
2279 const char *data = NULL;
2280 Py_ssize_t size;
2281
2282 if (PyUnicode_Check(password)) {
2283 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
2284 if (!password_bytes) {
2285 goto error;
2286 }
2287 data = PyBytes_AS_STRING(password_bytes);
2288 size = PyBytes_GET_SIZE(password_bytes);
2289 } else if (PyBytes_Check(password)) {
2290 data = PyBytes_AS_STRING(password);
2291 size = PyBytes_GET_SIZE(password);
2292 } else if (PyByteArray_Check(password)) {
2293 data = PyByteArray_AS_STRING(password);
2294 size = PyByteArray_GET_SIZE(password);
2295 } else {
2296 PyErr_SetString(PyExc_TypeError, bad_type_error);
2297 goto error;
2298 }
2299
Victor Stinner9ee02032013-06-23 15:08:23 +02002300 if (size > (Py_ssize_t)INT_MAX) {
2301 PyErr_Format(PyExc_ValueError,
2302 "password cannot be longer than %d bytes", INT_MAX);
2303 goto error;
2304 }
2305
Victor Stinner11ebff22013-07-07 17:07:52 +02002306 PyMem_Free(pw_info->password);
2307 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002308 if (!pw_info->password) {
2309 PyErr_SetString(PyExc_MemoryError,
2310 "unable to allocate password buffer");
2311 goto error;
2312 }
2313 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02002314 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002315
2316 Py_XDECREF(password_bytes);
2317 return 1;
2318
2319error:
2320 Py_XDECREF(password_bytes);
2321 return 0;
2322}
2323
2324static int
2325_password_callback(char *buf, int size, int rwflag, void *userdata)
2326{
2327 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
2328 PyObject *fn_ret = NULL;
2329
2330 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
2331
2332 if (pw_info->callable) {
2333 fn_ret = PyObject_CallFunctionObjArgs(pw_info->callable, NULL);
2334 if (!fn_ret) {
2335 /* TODO: It would be nice to move _ctypes_add_traceback() into the
2336 core python API, so we could use it to add a frame here */
2337 goto error;
2338 }
2339
2340 if (!_pwinfo_set(pw_info, fn_ret,
2341 "password callback must return a string")) {
2342 goto error;
2343 }
2344 Py_CLEAR(fn_ret);
2345 }
2346
2347 if (pw_info->size > size) {
2348 PyErr_Format(PyExc_ValueError,
2349 "password cannot be longer than %d bytes", size);
2350 goto error;
2351 }
2352
2353 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2354 memcpy(buf, pw_info->password, pw_info->size);
2355 return pw_info->size;
2356
2357error:
2358 Py_XDECREF(fn_ret);
2359 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
2360 pw_info->error = 1;
2361 return -1;
2362}
2363
Antoine Pitroub5218772010-05-21 09:56:06 +00002364static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002365load_cert_chain(PySSLContext *self, PyObject *args, PyObject *kwds)
2366{
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002367 char *kwlist[] = {"certfile", "keyfile", "password", NULL};
2368 PyObject *certfile, *keyfile = NULL, *password = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002369 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002370 pem_password_cb *orig_passwd_cb = self->ctx->default_passwd_callback;
2371 void *orig_passwd_userdata = self->ctx->default_passwd_callback_userdata;
2372 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00002373 int r;
2374
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002375 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00002376 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002377 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002378 "O|OO:load_cert_chain", kwlist,
2379 &certfile, &keyfile, &password))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002380 return NULL;
2381 if (keyfile == Py_None)
2382 keyfile = NULL;
2383 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
2384 PyErr_SetString(PyExc_TypeError,
2385 "certfile should be a valid filesystem path");
2386 return NULL;
2387 }
2388 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
2389 PyErr_SetString(PyExc_TypeError,
2390 "keyfile should be a valid filesystem path");
2391 goto error;
2392 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002393 if (password && password != Py_None) {
2394 if (PyCallable_Check(password)) {
2395 pw_info.callable = password;
2396 } else if (!_pwinfo_set(&pw_info, password,
2397 "password should be a string or callable")) {
2398 goto error;
2399 }
2400 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
2401 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
2402 }
2403 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002404 r = SSL_CTX_use_certificate_chain_file(self->ctx,
2405 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002406 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002407 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002408 if (pw_info.error) {
2409 ERR_clear_error();
2410 /* the password callback has already set the error information */
2411 }
2412 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002413 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002414 PyErr_SetFromErrno(PyExc_IOError);
2415 }
2416 else {
2417 _setSSLError(NULL, 0, __FILE__, __LINE__);
2418 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002419 goto error;
2420 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002421 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02002422 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002423 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
2424 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002425 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
2426 Py_CLEAR(keyfile_bytes);
2427 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002428 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002429 if (pw_info.error) {
2430 ERR_clear_error();
2431 /* the password callback has already set the error information */
2432 }
2433 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00002434 ERR_clear_error();
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002435 PyErr_SetFromErrno(PyExc_IOError);
2436 }
2437 else {
2438 _setSSLError(NULL, 0, __FILE__, __LINE__);
2439 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002440 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002441 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002442 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002443 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002444 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002445 if (r != 1) {
2446 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002447 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002448 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002449 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2450 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002451 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002452 Py_RETURN_NONE;
2453
2454error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02002455 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
2456 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02002457 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002458 Py_XDECREF(keyfile_bytes);
2459 Py_XDECREF(certfile_bytes);
2460 return NULL;
2461}
2462
Christian Heimesefff7062013-11-21 03:35:02 +01002463/* internal helper function, returns -1 on error
2464 */
2465static int
2466_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
2467 int filetype)
2468{
2469 BIO *biobuf = NULL;
2470 X509_STORE *store;
2471 int retval = 0, err, loaded = 0;
2472
2473 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
2474
2475 if (len <= 0) {
2476 PyErr_SetString(PyExc_ValueError,
2477 "Empty certificate data");
2478 return -1;
2479 } else if (len > INT_MAX) {
2480 PyErr_SetString(PyExc_OverflowError,
2481 "Certificate data is too long.");
2482 return -1;
2483 }
2484
2485 biobuf = BIO_new_mem_buf(data, len);
2486 if (biobuf == NULL) {
2487 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
2488 return -1;
2489 }
2490
2491 store = SSL_CTX_get_cert_store(self->ctx);
2492 assert(store != NULL);
2493
2494 while (1) {
2495 X509 *cert = NULL;
2496 int r;
2497
2498 if (filetype == SSL_FILETYPE_ASN1) {
2499 cert = d2i_X509_bio(biobuf, NULL);
2500 } else {
2501 cert = PEM_read_bio_X509(biobuf, NULL,
2502 self->ctx->default_passwd_callback,
2503 self->ctx->default_passwd_callback_userdata);
2504 }
2505 if (cert == NULL) {
2506 break;
2507 }
2508 r = X509_STORE_add_cert(store, cert);
2509 X509_free(cert);
2510 if (!r) {
2511 err = ERR_peek_last_error();
2512 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
2513 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
2514 /* cert already in hash table, not an error */
2515 ERR_clear_error();
2516 } else {
2517 break;
2518 }
2519 }
2520 loaded++;
2521 }
2522
2523 err = ERR_peek_last_error();
2524 if ((filetype == SSL_FILETYPE_ASN1) &&
2525 (loaded > 0) &&
2526 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
2527 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
2528 /* EOF ASN1 file, not an error */
2529 ERR_clear_error();
2530 retval = 0;
2531 } else if ((filetype == SSL_FILETYPE_PEM) &&
2532 (loaded > 0) &&
2533 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
2534 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
2535 /* EOF PEM file, not an error */
2536 ERR_clear_error();
2537 retval = 0;
2538 } else {
2539 _setSSLError(NULL, 0, __FILE__, __LINE__);
2540 retval = -1;
2541 }
2542
2543 BIO_free(biobuf);
2544 return retval;
2545}
2546
2547
Antoine Pitrou152efa22010-05-16 18:19:27 +00002548static PyObject *
2549load_verify_locations(PySSLContext *self, PyObject *args, PyObject *kwds)
2550{
Christian Heimesefff7062013-11-21 03:35:02 +01002551 char *kwlist[] = {"cafile", "capath", "cadata", NULL};
2552 PyObject *cafile = NULL, *capath = NULL, *cadata = NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002553 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
2554 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002555 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002556
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00002557 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002558 if (!PyArg_ParseTupleAndKeywords(args, kwds,
Christian Heimesefff7062013-11-21 03:35:02 +01002559 "|OOO:load_verify_locations", kwlist,
2560 &cafile, &capath, &cadata))
Antoine Pitrou152efa22010-05-16 18:19:27 +00002561 return NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002562
Antoine Pitrou152efa22010-05-16 18:19:27 +00002563 if (cafile == Py_None)
2564 cafile = NULL;
2565 if (capath == Py_None)
2566 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01002567 if (cadata == Py_None)
2568 cadata = NULL;
2569
2570 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002571 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01002572 "cafile, capath and cadata cannot be all omitted");
2573 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002574 }
2575 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
2576 PyErr_SetString(PyExc_TypeError,
2577 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002578 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002579 }
2580 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002581 PyErr_SetString(PyExc_TypeError,
2582 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01002583 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002584 }
Christian Heimesefff7062013-11-21 03:35:02 +01002585
2586 /* validata cadata type and load cadata */
2587 if (cadata) {
2588 Py_buffer buf;
2589 PyObject *cadata_ascii = NULL;
2590
2591 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
2592 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
2593 PyBuffer_Release(&buf);
2594 PyErr_SetString(PyExc_TypeError,
2595 "cadata should be a contiguous buffer with "
2596 "a single dimension");
2597 goto error;
2598 }
2599 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
2600 PyBuffer_Release(&buf);
2601 if (r == -1) {
2602 goto error;
2603 }
2604 } else {
2605 PyErr_Clear();
2606 cadata_ascii = PyUnicode_AsASCIIString(cadata);
2607 if (cadata_ascii == NULL) {
2608 PyErr_SetString(PyExc_TypeError,
2609 "cadata should be a ASCII string or a "
2610 "bytes-like object");
2611 goto error;
2612 }
2613 r = _add_ca_certs(self,
2614 PyBytes_AS_STRING(cadata_ascii),
2615 PyBytes_GET_SIZE(cadata_ascii),
2616 SSL_FILETYPE_PEM);
2617 Py_DECREF(cadata_ascii);
2618 if (r == -1) {
2619 goto error;
2620 }
2621 }
2622 }
2623
2624 /* load cafile or capath */
2625 if (cafile || capath) {
2626 if (cafile)
2627 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
2628 if (capath)
2629 capath_buf = PyBytes_AS_STRING(capath_bytes);
2630 PySSL_BEGIN_ALLOW_THREADS
2631 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
2632 PySSL_END_ALLOW_THREADS
2633 if (r != 1) {
2634 ok = 0;
2635 if (errno != 0) {
2636 ERR_clear_error();
2637 PyErr_SetFromErrno(PyExc_IOError);
2638 }
2639 else {
2640 _setSSLError(NULL, 0, __FILE__, __LINE__);
2641 }
2642 goto error;
2643 }
2644 }
2645 goto end;
2646
2647 error:
2648 ok = 0;
2649 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00002650 Py_XDECREF(cafile_bytes);
2651 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01002652 if (ok) {
2653 Py_RETURN_NONE;
2654 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00002655 return NULL;
2656 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002657}
2658
2659static PyObject *
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002660load_dh_params(PySSLContext *self, PyObject *filepath)
2661{
2662 FILE *f;
2663 DH *dh;
2664
Victor Stinnerdaf45552013-08-28 00:53:59 +02002665 f = _Py_fopen_obj(filepath, "rb");
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002666 if (f == NULL) {
2667 if (!PyErr_Occurred())
2668 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2669 return NULL;
2670 }
2671 errno = 0;
2672 PySSL_BEGIN_ALLOW_THREADS
2673 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01002674 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01002675 PySSL_END_ALLOW_THREADS
2676 if (dh == NULL) {
2677 if (errno != 0) {
2678 ERR_clear_error();
2679 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
2680 }
2681 else {
2682 _setSSLError(NULL, 0, __FILE__, __LINE__);
2683 }
2684 return NULL;
2685 }
2686 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
2687 _setSSLError(NULL, 0, __FILE__, __LINE__);
2688 DH_free(dh);
2689 Py_RETURN_NONE;
2690}
2691
2692static PyObject *
Antoine Pitrou152efa22010-05-16 18:19:27 +00002693context_wrap_socket(PySSLContext *self, PyObject *args, PyObject *kwds)
2694{
Antoine Pitroud5323212010-10-22 18:19:07 +00002695 char *kwlist[] = {"sock", "server_side", "server_hostname", NULL};
Antoine Pitrou152efa22010-05-16 18:19:27 +00002696 PySocketSockObject *sock;
2697 int server_side = 0;
Antoine Pitroud5323212010-10-22 18:19:07 +00002698 char *hostname = NULL;
2699 PyObject *hostname_obj, *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002700
Antoine Pitroud5323212010-10-22 18:19:07 +00002701 /* server_hostname is either None (or absent), or to be encoded
2702 using the idna encoding. */
2703 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!i|O!:_wrap_socket", kwlist,
Antoine Pitrou152efa22010-05-16 18:19:27 +00002704 PySocketModule.Sock_Type,
Antoine Pitroud5323212010-10-22 18:19:07 +00002705 &sock, &server_side,
2706 Py_TYPE(Py_None), &hostname_obj)) {
2707 PyErr_Clear();
2708 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!iet:_wrap_socket", kwlist,
2709 PySocketModule.Sock_Type,
2710 &sock, &server_side,
2711 "idna", &hostname))
2712 return NULL;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002713#if !HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00002714 PyMem_Free(hostname);
2715 PyErr_SetString(PyExc_ValueError, "server_hostname is not supported "
2716 "by your OpenSSL library");
Antoine Pitrou152efa22010-05-16 18:19:27 +00002717 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00002718#endif
2719 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002720
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002721 res = (PyObject *) newPySSLSocket(self, sock, server_side,
Antoine Pitroud5323212010-10-22 18:19:07 +00002722 hostname);
2723 if (hostname != NULL)
2724 PyMem_Free(hostname);
2725 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002726}
2727
Antoine Pitroub0182c82010-10-12 20:09:02 +00002728static PyObject *
2729session_stats(PySSLContext *self, PyObject *unused)
2730{
2731 int r;
2732 PyObject *value, *stats = PyDict_New();
2733 if (!stats)
2734 return NULL;
2735
2736#define ADD_STATS(SSL_NAME, KEY_NAME) \
2737 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
2738 if (value == NULL) \
2739 goto error; \
2740 r = PyDict_SetItemString(stats, KEY_NAME, value); \
2741 Py_DECREF(value); \
2742 if (r < 0) \
2743 goto error;
2744
2745 ADD_STATS(number, "number");
2746 ADD_STATS(connect, "connect");
2747 ADD_STATS(connect_good, "connect_good");
2748 ADD_STATS(connect_renegotiate, "connect_renegotiate");
2749 ADD_STATS(accept, "accept");
2750 ADD_STATS(accept_good, "accept_good");
2751 ADD_STATS(accept_renegotiate, "accept_renegotiate");
2752 ADD_STATS(accept, "accept");
2753 ADD_STATS(hits, "hits");
2754 ADD_STATS(misses, "misses");
2755 ADD_STATS(timeouts, "timeouts");
2756 ADD_STATS(cache_full, "cache_full");
2757
2758#undef ADD_STATS
2759
2760 return stats;
2761
2762error:
2763 Py_DECREF(stats);
2764 return NULL;
2765}
2766
Antoine Pitrou664c2d12010-11-17 20:29:42 +00002767static PyObject *
2768set_default_verify_paths(PySSLContext *self, PyObject *unused)
2769{
2770 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
2771 _setSSLError(NULL, 0, __FILE__, __LINE__);
2772 return NULL;
2773 }
2774 Py_RETURN_NONE;
2775}
2776
Antoine Pitrou501da612011-12-21 09:27:41 +01002777#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002778static PyObject *
2779set_ecdh_curve(PySSLContext *self, PyObject *name)
2780{
2781 PyObject *name_bytes;
2782 int nid;
2783 EC_KEY *key;
2784
2785 if (!PyUnicode_FSConverter(name, &name_bytes))
2786 return NULL;
2787 assert(PyBytes_Check(name_bytes));
2788 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
2789 Py_DECREF(name_bytes);
2790 if (nid == 0) {
2791 PyErr_Format(PyExc_ValueError,
2792 "unknown elliptic curve name %R", name);
2793 return NULL;
2794 }
2795 key = EC_KEY_new_by_curve_name(nid);
2796 if (key == NULL) {
2797 _setSSLError(NULL, 0, __FILE__, __LINE__);
2798 return NULL;
2799 }
2800 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2801 EC_KEY_free(key);
2802 Py_RETURN_NONE;
2803}
Antoine Pitrou501da612011-12-21 09:27:41 +01002804#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01002805
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002806#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002807static int
2808_servername_callback(SSL *s, int *al, void *args)
2809{
2810 int ret;
2811 PySSLContext *ssl_ctx = (PySSLContext *) args;
2812 PySSLSocket *ssl;
2813 PyObject *servername_o;
2814 PyObject *servername_idna;
2815 PyObject *result;
2816 /* The high-level ssl.SSLSocket object */
2817 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002818 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01002819#ifdef WITH_THREAD
2820 PyGILState_STATE gstate = PyGILState_Ensure();
2821#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002822
2823 if (ssl_ctx->set_hostname == NULL) {
2824 /* remove race condition in this the call back while if removing the
2825 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01002826#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002827 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002828#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01002829 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002830 }
2831
2832 ssl = SSL_get_app_data(s);
2833 assert(PySSLSocket_Check(ssl));
2834 ssl_socket = PyWeakref_GetObject(ssl->Socket);
2835 Py_INCREF(ssl_socket);
2836 if (ssl_socket == Py_None) {
2837 goto error;
2838 }
Victor Stinner7e001512013-06-25 00:44:31 +02002839
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002840 if (servername == NULL) {
2841 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2842 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002843 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002844 else {
2845 servername_o = PyBytes_FromString(servername);
2846 if (servername_o == NULL) {
2847 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
2848 goto error;
2849 }
2850 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
2851 if (servername_idna == NULL) {
2852 PyErr_WriteUnraisable(servername_o);
2853 Py_DECREF(servername_o);
2854 goto error;
2855 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002856 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02002857 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
2858 servername_idna, ssl_ctx, NULL);
2859 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002860 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002861 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002862
2863 if (result == NULL) {
2864 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
2865 *al = SSL_AD_HANDSHAKE_FAILURE;
2866 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2867 }
2868 else {
2869 if (result != Py_None) {
2870 *al = (int) PyLong_AsLong(result);
2871 if (PyErr_Occurred()) {
2872 PyErr_WriteUnraisable(result);
2873 *al = SSL_AD_INTERNAL_ERROR;
2874 }
2875 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
2876 }
2877 else {
2878 ret = SSL_TLSEXT_ERR_OK;
2879 }
2880 Py_DECREF(result);
2881 }
2882
Stefan Krah20d60802013-01-17 17:07:17 +01002883#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002884 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002885#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002886 return ret;
2887
2888error:
2889 Py_DECREF(ssl_socket);
2890 *al = SSL_AD_INTERNAL_ERROR;
2891 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01002892#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002893 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01002894#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002895 return ret;
2896}
Antoine Pitroua5963382013-03-30 16:39:00 +01002897#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002898
2899PyDoc_STRVAR(PySSL_set_servername_callback_doc,
2900"set_servername_callback(method)\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002901\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002902This sets a callback that will be called when a server name is provided by\n\
2903the SSL/TLS client in the SNI extension.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002904\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002905If the argument is None then the callback is disabled. The method is called\n\
2906with the SSLSocket, the server name as a string, and the SSLContext object.\n\
Antoine Pitrouedbc18e2013-03-30 16:40:27 +01002907See RFC 6066 for details of the SNI extension.");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002908
2909static PyObject *
2910set_servername_callback(PySSLContext *self, PyObject *args)
2911{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002912#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002913 PyObject *cb;
2914
2915 if (!PyArg_ParseTuple(args, "O", &cb))
2916 return NULL;
2917
2918 Py_CLEAR(self->set_hostname);
2919 if (cb == Py_None) {
2920 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2921 }
2922 else {
2923 if (!PyCallable_Check(cb)) {
2924 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
2925 PyErr_SetString(PyExc_TypeError,
2926 "not a callable object");
2927 return NULL;
2928 }
2929 Py_INCREF(cb);
2930 self->set_hostname = cb;
2931 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
2932 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
2933 }
2934 Py_RETURN_NONE;
2935#else
2936 PyErr_SetString(PyExc_NotImplementedError,
2937 "The TLS extension servername callback, "
2938 "SSL_CTX_set_tlsext_servername_callback, "
2939 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002940 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002941#endif
2942}
2943
Christian Heimes9a5395a2013-06-17 15:44:12 +02002944PyDoc_STRVAR(PySSL_get_stats_doc,
2945"cert_store_stats() -> {'crl': int, 'x509_ca': int, 'x509': int}\n\
2946\n\
2947Returns quantities of loaded X.509 certificates. X.509 certificates with a\n\
2948CA extension and certificate revocation lists inside the context's cert\n\
2949store.\n\
2950NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2951been used at least once.");
2952
2953static PyObject *
2954cert_store_stats(PySSLContext *self)
2955{
2956 X509_STORE *store;
2957 X509_OBJECT *obj;
2958 int x509 = 0, crl = 0, pkey = 0, ca = 0, i;
2959
2960 store = SSL_CTX_get_cert_store(self->ctx);
2961 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
2962 obj = sk_X509_OBJECT_value(store->objs, i);
2963 switch (obj->type) {
2964 case X509_LU_X509:
2965 x509++;
2966 if (X509_check_ca(obj->data.x509)) {
2967 ca++;
2968 }
2969 break;
2970 case X509_LU_CRL:
2971 crl++;
2972 break;
2973 case X509_LU_PKEY:
2974 pkey++;
2975 break;
2976 default:
2977 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
2978 * As far as I can tell they are internal states and never
2979 * stored in a cert store */
2980 break;
2981 }
2982 }
2983 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
2984 "x509_ca", ca);
2985}
2986
2987PyDoc_STRVAR(PySSL_get_ca_certs_doc,
2988"get_ca_certs([der=False]) -> list of loaded certificate\n\
2989\n\
2990Returns a list of dicts with information of loaded CA certs. If the\n\
2991optional argument is True, returns a DER-encoded copy of the CA certificate.\n\
2992NOTE: Certificates in a capath directory aren't loaded unless they have\n\
2993been used at least once.");
2994
2995static PyObject *
2996get_ca_certs(PySSLContext *self, PyObject *args)
2997{
2998 X509_STORE *store;
2999 PyObject *ci = NULL, *rlist = NULL;
3000 int i;
3001 int binary_mode = 0;
3002
3003 if (!PyArg_ParseTuple(args, "|p:get_ca_certs", &binary_mode)) {
3004 return NULL;
3005 }
3006
3007 if ((rlist = PyList_New(0)) == NULL) {
3008 return NULL;
3009 }
3010
3011 store = SSL_CTX_get_cert_store(self->ctx);
3012 for (i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
3013 X509_OBJECT *obj;
3014 X509 *cert;
3015
3016 obj = sk_X509_OBJECT_value(store->objs, i);
3017 if (obj->type != X509_LU_X509) {
3018 /* not a x509 cert */
3019 continue;
3020 }
3021 /* CA for any purpose */
3022 cert = obj->data.x509;
3023 if (!X509_check_ca(cert)) {
3024 continue;
3025 }
3026 if (binary_mode) {
3027 ci = _certificate_to_der(cert);
3028 } else {
3029 ci = _decode_certificate(cert);
3030 }
3031 if (ci == NULL) {
3032 goto error;
3033 }
3034 if (PyList_Append(rlist, ci) == -1) {
3035 goto error;
3036 }
3037 Py_CLEAR(ci);
3038 }
3039 return rlist;
3040
3041 error:
3042 Py_XDECREF(ci);
3043 Py_XDECREF(rlist);
3044 return NULL;
3045}
3046
3047
Antoine Pitrou152efa22010-05-16 18:19:27 +00003048static PyGetSetDef context_getsetlist[] = {
Antoine Pitroub5218772010-05-21 09:56:06 +00003049 {"options", (getter) get_options,
3050 (setter) set_options, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003051 {"verify_mode", (getter) get_verify_mode,
3052 (setter) set_verify_mode, NULL},
3053 {NULL}, /* sentinel */
3054};
3055
3056static struct PyMethodDef context_methods[] = {
3057 {"_wrap_socket", (PyCFunction) context_wrap_socket,
3058 METH_VARARGS | METH_KEYWORDS, NULL},
3059 {"set_ciphers", (PyCFunction) set_ciphers,
3060 METH_VARARGS, NULL},
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003061 {"_set_npn_protocols", (PyCFunction) _set_npn_protocols,
3062 METH_VARARGS, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003063 {"load_cert_chain", (PyCFunction) load_cert_chain,
3064 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003065 {"load_dh_params", (PyCFunction) load_dh_params,
3066 METH_O, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003067 {"load_verify_locations", (PyCFunction) load_verify_locations,
3068 METH_VARARGS | METH_KEYWORDS, NULL},
Antoine Pitroub0182c82010-10-12 20:09:02 +00003069 {"session_stats", (PyCFunction) session_stats,
3070 METH_NOARGS, NULL},
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003071 {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
3072 METH_NOARGS, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003073#ifndef OPENSSL_NO_ECDH
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003074 {"set_ecdh_curve", (PyCFunction) set_ecdh_curve,
3075 METH_O, NULL},
Antoine Pitrou501da612011-12-21 09:27:41 +01003076#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003077 {"set_servername_callback", (PyCFunction) set_servername_callback,
3078 METH_VARARGS, PySSL_set_servername_callback_doc},
Christian Heimes9a5395a2013-06-17 15:44:12 +02003079 {"cert_store_stats", (PyCFunction) cert_store_stats,
3080 METH_NOARGS, PySSL_get_stats_doc},
3081 {"get_ca_certs", (PyCFunction) get_ca_certs,
3082 METH_VARARGS, PySSL_get_ca_certs_doc},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003083 {NULL, NULL} /* sentinel */
3084};
3085
3086static PyTypeObject PySSLContext_Type = {
3087 PyVarObject_HEAD_INIT(NULL, 0)
3088 "_ssl._SSLContext", /*tp_name*/
3089 sizeof(PySSLContext), /*tp_basicsize*/
3090 0, /*tp_itemsize*/
3091 (destructor)context_dealloc, /*tp_dealloc*/
3092 0, /*tp_print*/
3093 0, /*tp_getattr*/
3094 0, /*tp_setattr*/
3095 0, /*tp_reserved*/
3096 0, /*tp_repr*/
3097 0, /*tp_as_number*/
3098 0, /*tp_as_sequence*/
3099 0, /*tp_as_mapping*/
3100 0, /*tp_hash*/
3101 0, /*tp_call*/
3102 0, /*tp_str*/
3103 0, /*tp_getattro*/
3104 0, /*tp_setattro*/
3105 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003106 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003107 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003108 (traverseproc) context_traverse, /*tp_traverse*/
3109 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003110 0, /*tp_richcompare*/
3111 0, /*tp_weaklistoffset*/
3112 0, /*tp_iter*/
3113 0, /*tp_iternext*/
3114 context_methods, /*tp_methods*/
3115 0, /*tp_members*/
3116 context_getsetlist, /*tp_getset*/
3117 0, /*tp_base*/
3118 0, /*tp_dict*/
3119 0, /*tp_descr_get*/
3120 0, /*tp_descr_set*/
3121 0, /*tp_dictoffset*/
3122 0, /*tp_init*/
3123 0, /*tp_alloc*/
3124 context_new, /*tp_new*/
3125};
3126
3127
3128
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003129#ifdef HAVE_OPENSSL_RAND
3130
3131/* helper routines for seeding the SSL PRNG */
3132static PyObject *
3133PySSL_RAND_add(PyObject *self, PyObject *args)
3134{
3135 char *buf;
3136 int len;
3137 double entropy;
3138
3139 if (!PyArg_ParseTuple(args, "s#d:RAND_add", &buf, &len, &entropy))
Antoine Pitrou525807b2010-05-12 14:05:24 +00003140 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003141 RAND_add(buf, len, entropy);
3142 Py_INCREF(Py_None);
3143 return Py_None;
3144}
3145
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003146PyDoc_STRVAR(PySSL_RAND_add_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003147"RAND_add(string, entropy)\n\
3148\n\
3149Mix string into the OpenSSL PRNG state. entropy (a float) is a lower\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003150bound on the entropy contained in string. See RFC 1750.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003151
3152static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02003153PySSL_RAND(int len, int pseudo)
3154{
3155 int ok;
3156 PyObject *bytes;
3157 unsigned long err;
3158 const char *errstr;
3159 PyObject *v;
3160
3161 bytes = PyBytes_FromStringAndSize(NULL, len);
3162 if (bytes == NULL)
3163 return NULL;
3164 if (pseudo) {
3165 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3166 if (ok == 0 || ok == 1)
3167 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
3168 }
3169 else {
3170 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
3171 if (ok == 1)
3172 return bytes;
3173 }
3174 Py_DECREF(bytes);
3175
3176 err = ERR_get_error();
3177 errstr = ERR_reason_error_string(err);
3178 v = Py_BuildValue("(ks)", err, errstr);
3179 if (v != NULL) {
3180 PyErr_SetObject(PySSLErrorObject, v);
3181 Py_DECREF(v);
3182 }
3183 return NULL;
3184}
3185
3186static PyObject *
3187PySSL_RAND_bytes(PyObject *self, PyObject *args)
3188{
3189 int len;
3190 if (!PyArg_ParseTuple(args, "i:RAND_bytes", &len))
3191 return NULL;
3192 return PySSL_RAND(len, 0);
3193}
3194
3195PyDoc_STRVAR(PySSL_RAND_bytes_doc,
3196"RAND_bytes(n) -> bytes\n\
3197\n\
3198Generate n cryptographically strong pseudo-random bytes.");
3199
3200static PyObject *
3201PySSL_RAND_pseudo_bytes(PyObject *self, PyObject *args)
3202{
3203 int len;
3204 if (!PyArg_ParseTuple(args, "i:RAND_pseudo_bytes", &len))
3205 return NULL;
3206 return PySSL_RAND(len, 1);
3207}
3208
3209PyDoc_STRVAR(PySSL_RAND_pseudo_bytes_doc,
3210"RAND_pseudo_bytes(n) -> (bytes, is_cryptographic)\n\
3211\n\
3212Generate n pseudo-random bytes. is_cryptographic is True if the bytes\
3213generated are cryptographically strong.");
3214
3215static PyObject *
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003216PySSL_RAND_status(PyObject *self)
3217{
Christian Heimes217cfd12007-12-02 14:31:20 +00003218 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003219}
3220
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003221PyDoc_STRVAR(PySSL_RAND_status_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003222"RAND_status() -> 0 or 1\n\
3223\n\
Bill Janssen6e027db2007-11-15 22:23:56 +00003224Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.\n\
3225It is necessary to seed the PRNG with RAND_add() on some platforms before\n\
3226using the ssl() function.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003227
3228static PyObject *
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003229PySSL_RAND_egd(PyObject *self, PyObject *args)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003230{
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003231 PyObject *path;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003232 int bytes;
3233
Jesus Ceac8754a12012-09-11 02:00:58 +02003234 if (!PyArg_ParseTuple(args, "O&:RAND_egd",
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003235 PyUnicode_FSConverter, &path))
3236 return NULL;
3237
3238 bytes = RAND_egd(PyBytes_AsString(path));
3239 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003240 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00003241 PyErr_SetString(PySSLErrorObject,
3242 "EGD connection failed or EGD did not return "
3243 "enough data to seed the PRNG");
3244 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003245 }
Christian Heimes217cfd12007-12-02 14:31:20 +00003246 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003247}
3248
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003249PyDoc_STRVAR(PySSL_RAND_egd_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003250"RAND_egd(path) -> bytes\n\
3251\n\
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003252Queries the entropy gather daemon (EGD) on the socket named by 'path'.\n\
3253Returns number of bytes read. Raises SSLError if connection to EGD\n\
Christian Heimes3c2593b2013-08-17 17:25:18 +02003254fails or if it does not provide enough data to seed PRNG.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003255
Christian Heimesf77b4b22013-08-21 13:26:05 +02003256#endif /* HAVE_OPENSSL_RAND */
3257
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003258
Christian Heimes6d7ad132013-06-09 18:02:55 +02003259PyDoc_STRVAR(PySSL_get_default_verify_paths_doc,
3260"get_default_verify_paths() -> tuple\n\
3261\n\
3262Return search paths and environment vars that are used by SSLContext's\n\
3263set_default_verify_paths() to load default CAs. The values are\n\
3264'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.");
3265
3266static PyObject *
Christian Heimes200bb1b2013-06-14 15:14:29 +02003267PySSL_get_default_verify_paths(PyObject *self)
Christian Heimes6d7ad132013-06-09 18:02:55 +02003268{
3269 PyObject *ofile_env = NULL;
3270 PyObject *ofile = NULL;
3271 PyObject *odir_env = NULL;
3272 PyObject *odir = NULL;
3273
3274#define convert(info, target) { \
3275 const char *tmp = (info); \
3276 target = NULL; \
3277 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
3278 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
3279 target = PyBytes_FromString(tmp); } \
3280 if (!target) goto error; \
3281 } while(0)
3282
3283 convert(X509_get_default_cert_file_env(), ofile_env);
3284 convert(X509_get_default_cert_file(), ofile);
3285 convert(X509_get_default_cert_dir_env(), odir_env);
3286 convert(X509_get_default_cert_dir(), odir);
3287#undef convert
3288
Christian Heimes200bb1b2013-06-14 15:14:29 +02003289 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02003290
3291 error:
3292 Py_XDECREF(ofile_env);
3293 Py_XDECREF(ofile);
3294 Py_XDECREF(odir_env);
3295 Py_XDECREF(odir);
3296 return NULL;
3297}
3298
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003299static PyObject*
3300asn1obj2py(ASN1_OBJECT *obj)
3301{
3302 int nid;
3303 const char *ln, *sn;
3304 char buf[100];
3305 int buflen;
3306
3307 nid = OBJ_obj2nid(obj);
3308 if (nid == NID_undef) {
3309 PyErr_Format(PyExc_ValueError, "Unknown object");
3310 return NULL;
3311 }
3312 sn = OBJ_nid2sn(nid);
3313 ln = OBJ_nid2ln(nid);
3314 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
3315 if (buflen < 0) {
3316 _setSSLError(NULL, 0, __FILE__, __LINE__);
3317 return NULL;
3318 }
3319 if (buflen) {
3320 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
3321 } else {
3322 return Py_BuildValue("issO", nid, sn, ln, Py_None);
3323 }
3324}
3325
3326PyDoc_STRVAR(PySSL_txt2obj_doc,
3327"txt2obj(txt, name=False) -> (nid, shortname, longname, oid)\n\
3328\n\
3329Lookup NID, short name, long name and OID of an ASN1_OBJECT. By default\n\
3330objects are looked up by OID. With name=True short and long name are also\n\
3331matched.");
3332
3333static PyObject*
3334PySSL_txt2obj(PyObject *self, PyObject *args, PyObject *kwds)
3335{
3336 char *kwlist[] = {"txt", "name", NULL};
3337 PyObject *result = NULL;
3338 char *txt;
3339 int name = 0;
3340 ASN1_OBJECT *obj;
3341
3342 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|p:txt2obj",
3343 kwlist, &txt, &name)) {
3344 return NULL;
3345 }
3346 obj = OBJ_txt2obj(txt, name ? 0 : 1);
3347 if (obj == NULL) {
3348 PyErr_Format(PyExc_ValueError, "Unknown object");
3349 return NULL;
3350 }
3351 result = asn1obj2py(obj);
3352 ASN1_OBJECT_free(obj);
3353 return result;
3354}
3355
3356PyDoc_STRVAR(PySSL_nid2obj_doc,
3357"nid2obj(nid) -> (nid, shortname, longname, oid)\n\
3358\n\
3359Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.");
3360
3361static PyObject*
3362PySSL_nid2obj(PyObject *self, PyObject *args)
3363{
3364 PyObject *result = NULL;
3365 int nid;
3366 ASN1_OBJECT *obj;
3367
3368 if (!PyArg_ParseTuple(args, "i:nid2obj", &nid)) {
3369 return NULL;
3370 }
3371 if (nid < NID_undef) {
3372 PyErr_Format(PyExc_ValueError, "NID must be positive.");
3373 return NULL;
3374 }
3375 obj = OBJ_nid2obj(nid);
3376 if (obj == NULL) {
3377 PyErr_Format(PyExc_ValueError, "Unknown NID");
3378 return NULL;
3379 }
3380 result = asn1obj2py(obj);
3381 ASN1_OBJECT_free(obj);
3382 return result;
3383}
3384
3385
Christian Heimes46bebee2013-06-09 19:03:31 +02003386#ifdef _MSC_VER
3387PyDoc_STRVAR(PySSL_enum_cert_store_doc,
3388"enum_cert_store(store_name, cert_type='certificate') -> []\n\
3389\n\
3390Retrieve certificates from Windows' cert store. store_name may be one of\n\
3391'CA', 'ROOT' or 'MY'. The system may provide more cert storages, too.\n\
3392cert_type must be either 'certificate' or 'crl'.\n\
3393The function returns a list of (bytes, encoding_type) tuples. The\n\
3394encoding_type flag can be interpreted with X509_ASN_ENCODING or\n\
3395PKCS_7_ASN_ENCODING.");
Bill Janssen40a0f662008-08-12 16:56:25 +00003396
Christian Heimes46bebee2013-06-09 19:03:31 +02003397static PyObject *
3398PySSL_enum_cert_store(PyObject *self, PyObject *args, PyObject *kwds)
3399{
3400 char *kwlist[] = {"store_name", "cert_type", NULL};
3401 char *store_name;
3402 char *cert_type = "certificate";
3403 HCERTSTORE hStore = NULL;
3404 PyObject *result = NULL;
3405 PyObject *tup = NULL, *cert = NULL, *enc = NULL;
3406 int ok = 1;
3407
3408 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|s:enum_cert_store",
3409 kwlist, &store_name, &cert_type)) {
3410 return NULL;
3411 }
3412
3413 if ((strcmp(cert_type, "certificate") != 0) &&
3414 (strcmp(cert_type, "crl") != 0)) {
3415 return PyErr_Format(PyExc_ValueError,
3416 "cert_type must be 'certificate' or 'crl', "
3417 "not %.100s", cert_type);
3418 }
3419
3420 if ((result = PyList_New(0)) == NULL) {
3421 return NULL;
3422 }
3423
Richard Oudkerkcabbde92013-08-24 23:46:27 +01003424 if ((hStore = CertOpenSystemStore((HCRYPTPROV)NULL, store_name)) == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02003425 Py_DECREF(result);
3426 return PyErr_SetFromWindowsErr(GetLastError());
3427 }
3428
3429 if (strcmp(cert_type, "certificate") == 0) {
3430 PCCERT_CONTEXT pCertCtx = NULL;
3431 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
3432 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
3433 pCertCtx->cbCertEncoded);
3434 if (!cert) {
3435 ok = 0;
3436 break;
3437 }
3438 if ((enc = PyLong_FromLong(pCertCtx->dwCertEncodingType)) == NULL) {
3439 ok = 0;
3440 break;
3441 }
3442 if ((tup = PyTuple_New(2)) == NULL) {
3443 ok = 0;
3444 break;
3445 }
3446 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3447 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3448
3449 if (PyList_Append(result, tup) < 0) {
3450 ok = 0;
3451 break;
3452 }
3453 Py_CLEAR(tup);
3454 }
3455 if (pCertCtx) {
3456 /* loop ended with an error, need to clean up context manually */
3457 CertFreeCertificateContext(pCertCtx);
3458 }
3459 } else {
3460 PCCRL_CONTEXT pCrlCtx = NULL;
3461 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
3462 cert = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
3463 pCrlCtx->cbCrlEncoded);
3464 if (!cert) {
3465 ok = 0;
3466 break;
3467 }
3468 if ((enc = PyLong_FromLong(pCrlCtx->dwCertEncodingType)) == NULL) {
3469 ok = 0;
3470 break;
3471 }
3472 if ((tup = PyTuple_New(2)) == NULL) {
3473 ok = 0;
3474 break;
3475 }
3476 PyTuple_SET_ITEM(tup, 0, cert); cert = NULL;
3477 PyTuple_SET_ITEM(tup, 1, enc); enc = NULL;
3478
3479 if (PyList_Append(result, tup) < 0) {
3480 ok = 0;
3481 break;
3482 }
3483 Py_CLEAR(tup);
3484 }
3485 if (pCrlCtx) {
3486 /* loop ended with an error, need to clean up context manually */
3487 CertFreeCRLContext(pCrlCtx);
3488 }
3489 }
3490
3491 /* In error cases cert, enc and tup may not be NULL */
3492 Py_XDECREF(cert);
3493 Py_XDECREF(enc);
3494 Py_XDECREF(tup);
3495
3496 if (!CertCloseStore(hStore, 0)) {
3497 /* This error case might shadow another exception.*/
3498 Py_DECREF(result);
3499 return PyErr_SetFromWindowsErr(GetLastError());
3500 }
3501 if (ok) {
3502 return result;
3503 } else {
3504 Py_DECREF(result);
3505 return NULL;
3506 }
3507}
3508#endif
Bill Janssen40a0f662008-08-12 16:56:25 +00003509
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003510/* List of functions exported by this module. */
3511
3512static PyMethodDef PySSL_methods[] = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003513 {"_test_decode_cert", PySSL_test_decode_certificate,
3514 METH_VARARGS},
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003515#ifdef HAVE_OPENSSL_RAND
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003516 {"RAND_add", PySSL_RAND_add, METH_VARARGS,
3517 PySSL_RAND_add_doc},
Victor Stinner99c8b162011-05-24 12:05:19 +02003518 {"RAND_bytes", PySSL_RAND_bytes, METH_VARARGS,
3519 PySSL_RAND_bytes_doc},
3520 {"RAND_pseudo_bytes", PySSL_RAND_pseudo_bytes, METH_VARARGS,
3521 PySSL_RAND_pseudo_bytes_doc},
Victor Stinnerf9faaad2010-05-16 21:36:37 +00003522 {"RAND_egd", PySSL_RAND_egd, METH_VARARGS,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003523 PySSL_RAND_egd_doc},
3524 {"RAND_status", (PyCFunction)PySSL_RAND_status, METH_NOARGS,
3525 PySSL_RAND_status_doc},
Christian Heimes142ec2c2013-06-09 18:29:54 +02003526#endif
Christian Heimes200bb1b2013-06-14 15:14:29 +02003527 {"get_default_verify_paths", (PyCFunction)PySSL_get_default_verify_paths,
Christian Heimes6d7ad132013-06-09 18:02:55 +02003528 METH_NOARGS, PySSL_get_default_verify_paths_doc},
Christian Heimes46bebee2013-06-09 19:03:31 +02003529#ifdef _MSC_VER
3530 {"enum_cert_store", (PyCFunction)PySSL_enum_cert_store,
3531 METH_VARARGS | METH_KEYWORDS, PySSL_enum_cert_store_doc},
3532#endif
Christian Heimesa6bc95a2013-11-17 19:59:14 +01003533 {"txt2obj", (PyCFunction)PySSL_txt2obj,
3534 METH_VARARGS | METH_KEYWORDS, PySSL_txt2obj_doc},
3535 {"nid2obj", (PyCFunction)PySSL_nid2obj,
3536 METH_VARARGS, PySSL_nid2obj_doc},
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003537 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003538};
3539
3540
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003541#ifdef WITH_THREAD
3542
3543/* an implementation of OpenSSL threading operations in terms
3544 of the Python C thread library */
3545
3546static PyThread_type_lock *_ssl_locks = NULL;
3547
Christian Heimes4d98ca92013-08-19 17:36:29 +02003548#if OPENSSL_VERSION_NUMBER >= 0x10000000
3549/* use new CRYPTO_THREADID API. */
3550static void
3551_ssl_threadid_callback(CRYPTO_THREADID *id)
3552{
3553 CRYPTO_THREADID_set_numeric(id,
3554 (unsigned long)PyThread_get_thread_ident());
3555}
3556#else
3557/* deprecated CRYPTO_set_id_callback() API. */
3558static unsigned long
3559_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003560 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003561}
Christian Heimes4d98ca92013-08-19 17:36:29 +02003562#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003563
Bill Janssen6e027db2007-11-15 22:23:56 +00003564static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003565 (int mode, int n, const char *file, int line) {
3566 /* this function is needed to perform locking on shared data
3567 structures. (Note that OpenSSL uses a number of global data
3568 structures that will be implicitly shared whenever multiple
3569 threads use OpenSSL.) Multi-threaded applications will
3570 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003571
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003572 locking_function() must be able to handle up to
3573 CRYPTO_num_locks() different mutex locks. It sets the n-th
3574 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003575
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003576 file and line are the file number of the function setting the
3577 lock. They can be useful for debugging.
3578 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003579
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003580 if ((_ssl_locks == NULL) ||
3581 (n < 0) || ((unsigned)n >= _ssl_locks_count))
3582 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003583
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003584 if (mode & CRYPTO_LOCK) {
3585 PyThread_acquire_lock(_ssl_locks[n], 1);
3586 } else {
3587 PyThread_release_lock(_ssl_locks[n]);
3588 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003589}
3590
3591static int _setup_ssl_threads(void) {
3592
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003593 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003594
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003595 if (_ssl_locks == NULL) {
3596 _ssl_locks_count = CRYPTO_num_locks();
3597 _ssl_locks = (PyThread_type_lock *)
Victor Stinnerb6404912013-07-07 16:21:41 +02003598 PyMem_Malloc(sizeof(PyThread_type_lock) * _ssl_locks_count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003599 if (_ssl_locks == NULL)
3600 return 0;
3601 memset(_ssl_locks, 0,
3602 sizeof(PyThread_type_lock) * _ssl_locks_count);
3603 for (i = 0; i < _ssl_locks_count; i++) {
3604 _ssl_locks[i] = PyThread_allocate_lock();
3605 if (_ssl_locks[i] == NULL) {
3606 unsigned int j;
3607 for (j = 0; j < i; j++) {
3608 PyThread_free_lock(_ssl_locks[j]);
3609 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003610 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003611 return 0;
3612 }
3613 }
3614 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003615#if OPENSSL_VERSION_NUMBER >= 0x10000000
3616 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
3617#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003618 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02003619#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003620 }
3621 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003622}
3623
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003624#endif /* def HAVE_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003625
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003626PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003627"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003628for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003629
Martin v. Löwis1a214512008-06-11 05:26:20 +00003630
3631static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003632 PyModuleDef_HEAD_INIT,
3633 "_ssl",
3634 module_doc,
3635 -1,
3636 PySSL_methods,
3637 NULL,
3638 NULL,
3639 NULL,
3640 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00003641};
3642
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003643
3644static void
3645parse_openssl_version(unsigned long libver,
3646 unsigned int *major, unsigned int *minor,
3647 unsigned int *fix, unsigned int *patch,
3648 unsigned int *status)
3649{
3650 *status = libver & 0xF;
3651 libver >>= 4;
3652 *patch = libver & 0xFF;
3653 libver >>= 8;
3654 *fix = libver & 0xFF;
3655 libver >>= 8;
3656 *minor = libver & 0xFF;
3657 libver >>= 8;
3658 *major = libver & 0xFF;
3659}
3660
Mark Hammondfe51c6d2002-08-02 02:27:13 +00003661PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00003662PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003663{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003664 PyObject *m, *d, *r;
3665 unsigned long libver;
3666 unsigned int major, minor, fix, patch, status;
3667 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003668 struct py_ssl_error_code *errcode;
3669 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003670
Antoine Pitrou152efa22010-05-16 18:19:27 +00003671 if (PyType_Ready(&PySSLContext_Type) < 0)
3672 return NULL;
3673 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003674 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003675
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003676 m = PyModule_Create(&_sslmodule);
3677 if (m == NULL)
3678 return NULL;
3679 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003680
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003681 /* Load _socket module and its C API */
3682 socket_api = PySocketModule_ImportModuleAndAPI();
3683 if (!socket_api)
3684 return NULL;
3685 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003686
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003687 /* Init OpenSSL */
3688 SSL_load_error_strings();
3689 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003690#ifdef WITH_THREAD
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003691 /* note that this will start threading if not already started */
3692 if (!_setup_ssl_threads()) {
3693 return NULL;
3694 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00003695#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003696 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003697
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003698 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003699 sslerror_type_slots[0].pfunc = PyExc_OSError;
3700 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003701 if (PySSLErrorObject == NULL)
3702 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003703
Antoine Pitrou41032a62011-10-27 23:56:55 +02003704 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
3705 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
3706 PySSLErrorObject, NULL);
3707 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
3708 "ssl.SSLWantReadError", SSLWantReadError_doc,
3709 PySSLErrorObject, NULL);
3710 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
3711 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
3712 PySSLErrorObject, NULL);
3713 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
3714 "ssl.SSLSyscallError", SSLSyscallError_doc,
3715 PySSLErrorObject, NULL);
3716 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
3717 "ssl.SSLEOFError", SSLEOFError_doc,
3718 PySSLErrorObject, NULL);
3719 if (PySSLZeroReturnErrorObject == NULL
3720 || PySSLWantReadErrorObject == NULL
3721 || PySSLWantWriteErrorObject == NULL
3722 || PySSLSyscallErrorObject == NULL
3723 || PySSLEOFErrorObject == NULL)
3724 return NULL;
3725 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
3726 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
3727 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
3728 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
3729 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
3730 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003731 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003732 if (PyDict_SetItemString(d, "_SSLContext",
3733 (PyObject *)&PySSLContext_Type) != 0)
3734 return NULL;
3735 if (PyDict_SetItemString(d, "_SSLSocket",
3736 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003737 return NULL;
3738 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
3739 PY_SSL_ERROR_ZERO_RETURN);
3740 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
3741 PY_SSL_ERROR_WANT_READ);
3742 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
3743 PY_SSL_ERROR_WANT_WRITE);
3744 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
3745 PY_SSL_ERROR_WANT_X509_LOOKUP);
3746 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
3747 PY_SSL_ERROR_SYSCALL);
3748 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
3749 PY_SSL_ERROR_SSL);
3750 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
3751 PY_SSL_ERROR_WANT_CONNECT);
3752 /* non ssl.h errorcodes */
3753 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
3754 PY_SSL_ERROR_EOF);
3755 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
3756 PY_SSL_ERROR_INVALID_ERROR_CODE);
3757 /* cert requirements */
3758 PyModule_AddIntConstant(m, "CERT_NONE",
3759 PY_SSL_CERT_NONE);
3760 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
3761 PY_SSL_CERT_OPTIONAL);
3762 PyModule_AddIntConstant(m, "CERT_REQUIRED",
3763 PY_SSL_CERT_REQUIRED);
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00003764
Christian Heimes46bebee2013-06-09 19:03:31 +02003765#ifdef _MSC_VER
3766 /* Windows dwCertEncodingType */
3767 PyModule_AddIntMacro(m, X509_ASN_ENCODING);
3768 PyModule_AddIntMacro(m, PKCS_7_ASN_ENCODING);
3769#endif
3770
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003771 /* Alert Descriptions from ssl.h */
3772 /* note RESERVED constants no longer intended for use have been removed */
3773 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
3774
3775#define ADD_AD_CONSTANT(s) \
3776 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
3777 SSL_AD_##s)
3778
3779 ADD_AD_CONSTANT(CLOSE_NOTIFY);
3780 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
3781 ADD_AD_CONSTANT(BAD_RECORD_MAC);
3782 ADD_AD_CONSTANT(RECORD_OVERFLOW);
3783 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
3784 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
3785 ADD_AD_CONSTANT(BAD_CERTIFICATE);
3786 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
3787 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
3788 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
3789 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
3790 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
3791 ADD_AD_CONSTANT(UNKNOWN_CA);
3792 ADD_AD_CONSTANT(ACCESS_DENIED);
3793 ADD_AD_CONSTANT(DECODE_ERROR);
3794 ADD_AD_CONSTANT(DECRYPT_ERROR);
3795 ADD_AD_CONSTANT(PROTOCOL_VERSION);
3796 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
3797 ADD_AD_CONSTANT(INTERNAL_ERROR);
3798 ADD_AD_CONSTANT(USER_CANCELLED);
3799 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003800 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003801#ifdef SSL_AD_UNSUPPORTED_EXTENSION
3802 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
3803#endif
3804#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
3805 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
3806#endif
3807#ifdef SSL_AD_UNRECOGNIZED_NAME
3808 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
3809#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003810#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
3811 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
3812#endif
3813#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
3814 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
3815#endif
3816#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
3817 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
3818#endif
3819
3820#undef ADD_AD_CONSTANT
3821
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003822 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02003823#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003824 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
3825 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02003826#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003827 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
3828 PY_SSL_VERSION_SSL3);
3829 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
3830 PY_SSL_VERSION_SSL23);
3831 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
3832 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003833#if HAVE_TLSv1_2
3834 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
3835 PY_SSL_VERSION_TLS1_1);
3836 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
3837 PY_SSL_VERSION_TLS1_2);
3838#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003839
Antoine Pitroub5218772010-05-21 09:56:06 +00003840 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01003841 PyModule_AddIntConstant(m, "OP_ALL",
3842 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00003843 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
3844 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
3845 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003846#if HAVE_TLSv1_2
3847 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
3848 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
3849#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01003850 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
3851 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003852 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003853#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003854 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01003855#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01003856#ifdef SSL_OP_NO_COMPRESSION
3857 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
3858 SSL_OP_NO_COMPRESSION);
3859#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00003860
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003861#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00003862 r = Py_True;
3863#else
3864 r = Py_False;
3865#endif
3866 Py_INCREF(r);
3867 PyModule_AddObject(m, "HAS_SNI", r);
3868
Antoine Pitroud6494802011-07-21 01:11:30 +02003869#if HAVE_OPENSSL_FINISHED
3870 r = Py_True;
3871#else
3872 r = Py_False;
3873#endif
3874 Py_INCREF(r);
3875 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
3876
Antoine Pitrou501da612011-12-21 09:27:41 +01003877#ifdef OPENSSL_NO_ECDH
3878 r = Py_False;
3879#else
3880 r = Py_True;
3881#endif
3882 Py_INCREF(r);
3883 PyModule_AddObject(m, "HAS_ECDH", r);
3884
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003885#ifdef OPENSSL_NPN_NEGOTIATED
3886 r = Py_True;
3887#else
3888 r = Py_False;
3889#endif
3890 Py_INCREF(r);
3891 PyModule_AddObject(m, "HAS_NPN", r);
3892
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02003893 /* Mappings for error codes */
3894 err_codes_to_names = PyDict_New();
3895 err_names_to_codes = PyDict_New();
3896 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
3897 return NULL;
3898 errcode = error_codes;
3899 while (errcode->mnemonic != NULL) {
3900 PyObject *mnemo, *key;
3901 mnemo = PyUnicode_FromString(errcode->mnemonic);
3902 key = Py_BuildValue("ii", errcode->library, errcode->reason);
3903 if (mnemo == NULL || key == NULL)
3904 return NULL;
3905 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
3906 return NULL;
3907 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
3908 return NULL;
3909 Py_DECREF(key);
3910 Py_DECREF(mnemo);
3911 errcode++;
3912 }
3913 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
3914 return NULL;
3915 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
3916 return NULL;
3917
3918 lib_codes_to_names = PyDict_New();
3919 if (lib_codes_to_names == NULL)
3920 return NULL;
3921 libcode = library_codes;
3922 while (libcode->library != NULL) {
3923 PyObject *mnemo, *key;
3924 key = PyLong_FromLong(libcode->code);
3925 mnemo = PyUnicode_FromString(libcode->library);
3926 if (key == NULL || mnemo == NULL)
3927 return NULL;
3928 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
3929 return NULL;
3930 Py_DECREF(key);
3931 Py_DECREF(mnemo);
3932 libcode++;
3933 }
3934 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
3935 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02003936
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003937 /* OpenSSL version */
3938 /* SSLeay() gives us the version of the library linked against,
3939 which could be different from the headers version.
3940 */
3941 libver = SSLeay();
3942 r = PyLong_FromUnsignedLong(libver);
3943 if (r == NULL)
3944 return NULL;
3945 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
3946 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003947 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003948 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3949 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
3950 return NULL;
3951 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
3952 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
3953 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00003954
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02003955 libver = OPENSSL_VERSION_NUMBER;
3956 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
3957 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
3958 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
3959 return NULL;
3960
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003961 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003962}